




import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow





@is_pipeline_test
@require_torch
class 	lowerCamelCase_							(				unittest.TestCase ):


 '''simple docstring'''







 @require_torch
 def 				lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_ :    Dict     						=      pipeline(
           task='zero-shot-audio-classification'    ,    model='hf-internal-testing/tiny-clap-htsat-unfused'						)
       SCREAMING_SNAKE_CASE_ :    List[str]     						=      load_dataset('ashraq/esc50'						)
       SCREAMING_SNAKE_CASE_ :    Optional[int]     						=      dataset['train']['audio'][-1]['array']
       SCREAMING_SNAKE_CASE_ :    List[Any]     						=      audio_classifier(__lowerCAmelCase    ,    candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)
       self.assertEqual(
           nested_simplify(__lowerCAmelCase						)    ,    [{'score': 0.501, 'label': 'Sound of a dog'}, {'score': 0.499, 'label': 'Sound of vaccum cleaner'}]    ,    )



 @unittest.skip('No models are available in TF'						)
 def 				lowerCAmelCase_  (							self  :		int						):
       pass



 @slow
 @require_torch
 def 				lowerCAmelCase_  (							self  :		List[Any]						):
       SCREAMING_SNAKE_CASE_ :    Tuple     						=      pipeline(
           task='zero-shot-audio-classification'    ,    model='laion/clap-htsat-unfused'    ,    )
       # This is an audio of a dog
       SCREAMING_SNAKE_CASE_ :    Any     						=      load_dataset('ashraq/esc50'						)
       SCREAMING_SNAKE_CASE_ :    Tuple     						=      dataset['train']['audio'][-1]['array']
       SCREAMING_SNAKE_CASE_ :    Any     						=      audio_classifier(__lowerCAmelCase    ,    candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)

       self.assertEqual(
           nested_simplify(__lowerCAmelCase						)    ,    [
               {'score': 0.999, 'label': 'Sound of a dog'},
               {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
           ]    ,    )

       SCREAMING_SNAKE_CASE_ :    List[Any]     						=      audio_classifier([audio] * 5    ,    candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']						)
       self.assertEqual(
           nested_simplify(__lowerCAmelCase						)    ,    [
               [
                   {'score': 0.999, 'label': 'Sound of a dog'},
                   {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
               ],
           ]
           * 5    ,    )
       SCREAMING_SNAKE_CASE_ :    Tuple     						=      audio_classifier(
           [audio] * 5    ,    candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner']    ,    batch_size=5						)
       self.assertEqual(
           nested_simplify(__lowerCAmelCase						)    ,    [
               [
                   {'score': 0.999, 'label': 'Sound of a dog'},
                   {'score': 0.001, 'label': 'Sound of vaccum cleaner'},
               ],
           ]
           * 5    ,    )




 @unittest.skip('No models are available in TF'						)
 def 				lowerCAmelCase_  (							self  :		str						):
       pass





import gc
import threading
import time

import psutil
import torch





class 	lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_     						=      psutil.Process()
       SCREAMING_SNAKE_CASE_     						=      False



 def 				lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_     						=      -1

       while True:
             SCREAMING_SNAKE_CASE_     						=      max(self.process.memory_info().rss    ,    self.cpu_memory_peak						)

             # can't sleep or will not catch the peak right (this comment is here on purpose)
             if not self.peak_monitoring:
                   break



 def 				lowerCAmelCase_  (							self  :		List[str]						):
       SCREAMING_SNAKE_CASE_     						=      True
       SCREAMING_SNAKE_CASE_     						=      threading.Thread(target=self.peak_monitor						)
       SCREAMING_SNAKE_CASE_     						=      True
       self.thread.start()




 def 				lowerCAmelCase_  (							self  :		List[str]						):
       SCREAMING_SNAKE_CASE_     						=      False
       self.thread.join()
       return self.cpu_memory_peak


lowerCamelCase__			:       List[str]         =							PeakCPUMemory()

def  UpperCAmelCase_							(				) ->			Tuple:
      # Time
      SCREAMING_SNAKE_CASE_     						=      {'time': time.time()}

      gc.collect()
      torch.cuda.empty_cache()

      # CPU mem
      SCREAMING_SNAKE_CASE_     						=      psutil.Process().memory_info().rss
      cpu_peak_tracker.start()

      # GPU mem
      for i in range(torch.cuda.device_count()							):
            SCREAMING_SNAKE_CASE_     						=      torch.cuda.memory_allocated(__UpperCAmelCase							)
      torch.cuda.reset_peak_memory_stats()

      return measures

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[int]							) ->			Optional[Any]:
      # Time
      SCREAMING_SNAKE_CASE_     						=      {'time': time.time() - start_measures['time']}

      gc.collect()
      torch.cuda.empty_cache()

      # CPU mem
      SCREAMING_SNAKE_CASE_     						=      (psutil.Process().memory_info().rss - start_measures['cpu']) / 2**20
      SCREAMING_SNAKE_CASE_     						=      (cpu_peak_tracker.stop() - start_measures['cpu']) / 2**20

      # GPU mem
      for i in range(torch.cuda.device_count()							):
            SCREAMING_SNAKE_CASE_     						=      (torch.cuda.memory_allocated(__UpperCAmelCase							) - start_measures[str(__UpperCAmelCase							)]) / 2**20
            SCREAMING_SNAKE_CASE_     						=      (torch.cuda.max_memory_allocated(__UpperCAmelCase							) - start_measures[str(__UpperCAmelCase							)]) / 2**20

      return measures





def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[int]      ,      __UpperCAmelCase						:     Any							) ->			Optional[Any]:
      print(f"{description}:"							)
      print(f"- Time: {measures['time']:.2f}s"							)
      for i in range(torch.cuda.device_count()							):
            print(f"- GPU {i} allocated: {measures[str(__UpperCAmelCase							)]:.2f}MiB"							)
            SCREAMING_SNAKE_CASE_     						=      measures[f"{i}-peak"]
            print(f"- GPU {i} peak: {peak:.2f}MiB"							)
      print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB"							)
      print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB"							)