


'''simple docstring'''



from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


__lowercase	:						int       =	logging.get_logger(__name__)





@add_end_docstrings(lowerCAmelCase_					)
class 							__UpperCamelCase				(		lowerCAmelCase_					):




	def __init__(   self						,				**__a							):

						'''simple docstring'''





						super().__init__(**__a							)

						if self.framework != "pt":
											raise ValueError(f"""The {self.__class__} is only available in PyTorch."""							)
						# No specific FOR_XXX available yet




	def __call__(   self						,				__a						,				**__a							):

						'''simple docstring'''





						return super().__call__(__a						,				**__a							)




	def       __UpperCAmelCase							(   self						,				**__a							):

						'''simple docstring'''





						__a			:       List[str]					    =  {}
						if "candidate_labels" in kwargs:
											__a			:       List[Any]					    =  kwargs['candidate_labels']
						if "hypothesis_template" in kwargs:
											__a			:       Optional[int]					    =  kwargs['hypothesis_template']

						return preprocess_params, {}, {}




	def       __UpperCAmelCase							(   self						,				__a						,				__a=None						,				__a="This is a sound of {}."							):

						'''simple docstring'''





						if isinstance(__a						,				__a							):
											if audio.startswith('http://'							) or audio.startswith('https://'							):
																# We need to actually check for a real protocol, otherwise it's impossible to use a local file
																# like http_huggingface_co.png
																__a			:       Union[str, Any]					    =  requests.get(__a							).content
											else:
																with open(__a						,				'rb'							) as f:
																					__a			:       Tuple					    =  f.read()

						if isinstance(__a						,				__a							):
											__a			:       Dict					    =  ffmpeg_read(__a						,				self.feature_extractor.sampling_rate							)

						if not isinstance(__a						,				np.ndarray							):
											raise ValueError('We expect a numpy ndarray as input'							)
						if len(audio.shape							) != 1:
											raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline'							)

						__a			:       Dict					    =  self.feature_extractor(
						    [audio]						,				sampling_rate=self.feature_extractor.sampling_rate						,				return_tensors='pt'							)
						__a			:       Tuple					    =  candidate_labels
						__a			:       int					    =  [hypothesis_template.format(__a							) for x in candidate_labels]
						__a			:       Tuple					    =  self.tokenizer(__a						,				return_tensors=self.framework						,				padding=__a							)
						__a			:       Union[str, Any]					    =  [text_inputs]
						return inputs




	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Union[str, Any]					    =  model_inputs.pop('candidate_labels'							)
						__a			:       List[str]					    =  model_inputs.pop('text_inputs'							)
						if isinstance(text_inputs[0]						,				__a							):
											__a			:       Dict					    =  text_inputs[0]
						else:
											# Batching case.
											__a			:       Tuple					    =  text_inputs[0][0]

						__a			:       Union[str, Any]					    =  self.model(**__a						,				**__a							)

						__a			:       Tuple					    =  {
						    'candidate_labels': candidate_labels,
						    'logits': outputs.logits_per_audio,
						}
						return model_outputs





	def       __UpperCAmelCase							(   self						,				__a							):

						'''simple docstring'''





						__a			:       Dict					    =  model_outputs.pop('candidate_labels'							)
						__a			:       Tuple					    =  model_outputs['logits'][0]

						if self.framework == "pt":
											__a			:       Optional[Any]					    =  logits.softmax(dim=0							)
											__a			:       List[Any]					    =  probs.tolist()
						else:
											raise ValueError('`tf` framework not supported.'							)

						__a			:       Union[str, Any]					    =  [
						    {'score': score, 'label': candidate_label}
						    for score, candidate_label in sorted(zip(__a						,				__a							)						,				key=lambda __a							: -x[0]							)
						]
						return result







'''simple docstring'''



import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append('.')






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   List[Any]   ):
					__a			:       Any					    =  test_file.split(os.path.sep   )
					if components[0:2] != ["tests", "models"]:
										raise ValueError(
										    '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '
										    F"""{test_file} instead."""   )
					__a			:       Tuple					    =  components[-1]
					if not test_fn.endswith('py'   ):
										raise ValueError(F"""`test_file` should be a python file. Got {test_fn} instead."""   )
					if not test_fn.startswith('test_modeling_'   ):
										raise ValueError(
										    F"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead."""   )

					__a			:       List[str]					    =  components[:-1] + [test_fn.replace('.py'						,      ''   )]
					__a			:       Optional[Any]					    =  '.'.join(_SCREAMING_SNAKE_CASE   )

					return test_module_path






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Tuple   ):
					__a			:       List[str]					    =  get_module_path(_SCREAMING_SNAKE_CASE   )
					__a			:       Dict					    =  importlib.import_module(_SCREAMING_SNAKE_CASE   )

					return test_module






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Tuple   ):
					__a			:       List[str]					    =  []
					__a			:       List[str]					    =  get_test_module(_SCREAMING_SNAKE_CASE   )
					for attr in dir(_SCREAMING_SNAKE_CASE   ):
										if attr.endswith('ModelTester'   ):
															tester_classes.append(getattr(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )   )

    # sort with class names
					return sorted(_SCREAMING_SNAKE_CASE						,      key=lambda _SCREAMING_SNAKE_CASE   : x.__name__   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Tuple   ):
					__a			:       Any					    =  []
					__a			:       str					    =  get_test_module(_SCREAMING_SNAKE_CASE   )
					for attr in dir(_SCREAMING_SNAKE_CASE   ):
										__a			:       int					    =  getattr(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )
										# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
										# `all_model_classes` is not empty (which also excludes other special classes).
										__a			:       Optional[Any]					    =  getattr(_SCREAMING_SNAKE_CASE						,      'all_model_classes'						,      []   )
										if len(_SCREAMING_SNAKE_CASE   ) > 0:
															test_classes.append(_SCREAMING_SNAKE_CASE   )

    # sort with class names
					return sorted(_SCREAMING_SNAKE_CASE						,      key=lambda _SCREAMING_SNAKE_CASE   : x.__name__   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   int   ):
					__a			:       str					    =  get_test_classes(_SCREAMING_SNAKE_CASE   )
					__a			:       Any					    =  set()
					for test_class in test_classes:
										model_classes.update(test_class.all_model_classes   )

					# sort with class names
					return sorted(_SCREAMING_SNAKE_CASE						,      key=lambda _SCREAMING_SNAKE_CASE   : x.__name__   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Optional[Any]   ):
					__a			:       Tuple					    =  test_class()
					if hasattr(_SCREAMING_SNAKE_CASE						,      'setUp'   ):
										test.setUp()

					__a			:       List[Any]					    =  None
					if hasattr(_SCREAMING_SNAKE_CASE						,      'model_tester'   ):
										# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
										if test.model_tester is not None:
															__a			:       List[str]					    =  test.model_tester.__class__

					return model_tester






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   int						,      _SCREAMING_SNAKE_CASE      :   Optional[Any]   ):
					__a			:       str					    =  get_test_classes(_SCREAMING_SNAKE_CASE   )

					__a			:       int					    =  []
					for test_class in test_classes:
										if model_class in test_class.all_model_classes:
															target_test_classes.append(_SCREAMING_SNAKE_CASE   )

    # sort with class names
					return sorted(_SCREAMING_SNAKE_CASE						,      key=lambda _SCREAMING_SNAKE_CASE   : x.__name__   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Tuple						,      _SCREAMING_SNAKE_CASE      :   List[str]   ):
					__a			:       List[Any]					    =  get_test_classes_for_model(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )

					__a			:       Any					    =  []
					for test_class in test_classes:
										__a			:       Any					    =  get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE   )
										if tester_class is not None:
															tester_classes.append(_SCREAMING_SNAKE_CASE   )

    # sort with class names
					return sorted(_SCREAMING_SNAKE_CASE						,      key=lambda _SCREAMING_SNAKE_CASE   : x.__name__   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Optional[int]   ):
					__a			:       str					    =  get_test_classes(_SCREAMING_SNAKE_CASE   )
					__a			:       int					    =  {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE   ) for test_class in test_classes}
					return test_tester_mapping






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   List[str]   ):
					__a			:       Optional[Any]					    =  get_model_classes(_SCREAMING_SNAKE_CASE   )
					__a			:       Optional[int]					    =  {
					    model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ) for model_class in model_classes
					}
					return model_test_mapping






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   List[str]   ):
					__a			:       Optional[Any]					    =  get_model_classes(_SCREAMING_SNAKE_CASE   )
					__a			:       str					    =  {
					    model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ) for model_class in model_classes
					}
					return model_to_tester_mapping






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   str   ):
					if isinstance(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ):
										return o
					elif isinstance(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ):
										return o.__name__
					elif isinstance(_SCREAMING_SNAKE_CASE						,      (list, tuple)   ):
										return [to_json(_SCREAMING_SNAKE_CASE   ) for x in o]
					elif isinstance(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   ):
										return {to_json(_SCREAMING_SNAKE_CASE   ): to_json(_SCREAMING_SNAKE_CASE   ) for k, v in o.items()}
					else:
										return o



