


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


_UpperCAmelCase			:		Union[str, Any]   				=    logging.get_logger(__name__)
@add_end_docstrings(lowercase_					)
class  lowerCAmelCase_       (				lowercase_					):




							def __init__(   self     :   int ,							**SCREAMING_SNAKE_CASE_     :   Any	):
											super().__init__(**UpperCamelCase__	)

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




							def __call__(   self     :   Optional[int] ,							SCREAMING_SNAKE_CASE_     :   Union[np.ndarray, bytes, str] ,							**SCREAMING_SNAKE_CASE_     :   Any	):
											return super().__call__(UpperCamelCase__ ,							**UpperCamelCase__	)




							def 						__snake_case					(   self     :   int ,							**SCREAMING_SNAKE_CASE_     :   List[Any]	):
											lowerCAmelCase__      			=						{}
											if "candidate_labels" in kwargs:
															lowerCAmelCase__      			=						kwargs['''candidate_labels''']
											if "hypothesis_template" in kwargs:
															lowerCAmelCase__      			=						kwargs['''hypothesis_template''']

											return preprocess_params, {}, {}




							def 						__snake_case					(   self     :   Dict ,							SCREAMING_SNAKE_CASE_     :   Any ,							SCREAMING_SNAKE_CASE_     :   Dict=None ,							SCREAMING_SNAKE_CASE_     :   List[str]="This is a sound of {}."	):







											if isinstance(UpperCamelCase__ ,							UpperCamelCase__	):
															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
																			lowerCAmelCase__      			=						requests.get(UpperCamelCase__	).content
															else:
																			with open(UpperCamelCase__ ,							'''rb'''	) as f:
																							lowerCAmelCase__      			=						f.read()

											if isinstance(UpperCamelCase__ ,							UpperCamelCase__	):
															lowerCAmelCase__      			=						ffmpeg_read(UpperCamelCase__ ,							self.feature_extractor.sampling_rate	)

											if not isinstance(UpperCamelCase__ ,							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'''	)

											lowerCAmelCase__      			=						self.feature_extractor(
											    [audio] ,							sampling_rate=self.feature_extractor.sampling_rate ,							return_tensors='''pt'''	)
											lowerCAmelCase__      			=						candidate_labels
											lowerCAmelCase__      			=						[hypothesis_template.format(UpperCamelCase__	) for x in candidate_labels]
											lowerCAmelCase__      			=						self.tokenizer(UpperCamelCase__ ,							return_tensors=self.framework ,							padding=UpperCamelCase__	)
											lowerCAmelCase__      			=						[text_inputs]
											return inputs




							def 						__snake_case					(   self     :   int ,							SCREAMING_SNAKE_CASE_     :   Optional[int]	):
											lowerCAmelCase__      			=						model_inputs.pop('''candidate_labels'''	)
											lowerCAmelCase__      			=						model_inputs.pop('''text_inputs'''	)
											if isinstance(text_inputs[0] ,							UpperCamelCase__	):
															lowerCAmelCase__      			=						text_inputs[0]
											else:
															# Batching case.
															lowerCAmelCase__      			=						text_inputs[0][0]

											lowerCAmelCase__      			=						self.model(**UpperCamelCase__ ,							**UpperCamelCase__	)

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




							def 						__snake_case					(   self     :   Dict ,							SCREAMING_SNAKE_CASE_     :   List[str]	):
											lowerCAmelCase__      			=						model_outputs.pop('''candidate_labels'''	)
											lowerCAmelCase__      			=						model_outputs['''logits'''][0]

											if self.framework == "pt":
															lowerCAmelCase__      			=						logits.softmax(dim=0	)
															lowerCAmelCase__      			=						probs.tolist()
											else:
															raise ValueError('''`tf` framework not supported.'''	)

											lowerCAmelCase__      			=						[
											    {'''score''': score, '''label''': candidate_label}
											    for score, candidate_label in sorted(zip(UpperCamelCase__ ,							UpperCamelCase__	) ,							key=lambda SCREAMING_SNAKE_CASE_	: -x[0]	)
											]
											return result













import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


_UpperCAmelCase			:		List[Any]   				=    logging.getLogger()
@unittest.skip('Temporarily disable the doc tests.'					)
@require_torch
@require_tf
@slow
class  lowerCAmelCase_       (				unittest.TestCase					):




							def 						__snake_case					(   self     :   Tuple ,							SCREAMING_SNAKE_CASE_     :   Path ,							SCREAMING_SNAKE_CASE_     :   Union[str, None] = None ,							SCREAMING_SNAKE_CASE_     :   Union[List[str], None] = None ,							SCREAMING_SNAKE_CASE_     :   Union[str, List[str], None] = None ,							SCREAMING_SNAKE_CASE_     :   bool = True ,							):
											lowerCAmelCase__      			=						[file for file in os.listdir(SCREAMING_SNAKE_CASE_	) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE_ ,							SCREAMING_SNAKE_CASE_	)	)]

											if identifier is not None:
															lowerCAmelCase__      			=						[file for file in files if identifier in file]

											if n_identifier is not None:
															if isinstance(SCREAMING_SNAKE_CASE_ ,							SCREAMING_SNAKE_CASE_	):
																			for n_ in n_identifier:
																							lowerCAmelCase__      			=						[file for file in files if n_ not in file]
															else:
																			lowerCAmelCase__      			=						[file for file in files if n_identifier not in file]

											lowerCAmelCase__      			=						ignore_files or []
											ignore_files.append('''__init__.py'''	)
											lowerCAmelCase__      			=						[file for file in files if file not in ignore_files]

											for file in files:
															# Open all files
															print('''Testing''' ,							SCREAMING_SNAKE_CASE_	)

															if only_modules:
																			lowerCAmelCase__      			=						file.split('''.'''	)[0]
																			try:
																							lowerCAmelCase__      			=						getattr(SCREAMING_SNAKE_CASE_ ,							SCREAMING_SNAKE_CASE_	)
																							lowerCAmelCase__      			=						doctest.DocTestSuite(SCREAMING_SNAKE_CASE_	)
																							lowerCAmelCase__      			=						unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE_	)
																							self.assertIs(len(result.failures	) ,							0	)
																			except AttributeError:
																							logger.info(f'{module_identifier} is not a module.'	)
															else:
																			lowerCAmelCase__      			=						doctest.testfile(str('''..''' / directory / file	) ,							optionflags=doctest.ELLIPSIS	)
																			self.assertIs(result.failed ,							0	)




							def 						__snake_case					(   self     :   Optional[Any]	):
											lowerCAmelCase__      			=						Path('''src/transformers'''	)
											lowerCAmelCase__      			=						'''modeling'''
											lowerCAmelCase__      			=						[
											    '''modeling_ctrl.py''',
											    '''modeling_tf_ctrl.py''',
											]
											self.analyze_directory(SCREAMING_SNAKE_CASE_ ,							identifier=SCREAMING_SNAKE_CASE_ ,							ignore_files=SCREAMING_SNAKE_CASE_	)




							def 						__snake_case					(   self     :   Dict	):
											lowerCAmelCase__      			=						Path('''src/transformers'''	)
											lowerCAmelCase__      			=						'''tokenization'''
											self.analyze_directory(SCREAMING_SNAKE_CASE_ ,							identifier=SCREAMING_SNAKE_CASE_	)




							def 						__snake_case					(   self     :   Tuple	):
											lowerCAmelCase__      			=						Path('''src/transformers'''	)
											lowerCAmelCase__      			=						'''configuration'''
											self.analyze_directory(SCREAMING_SNAKE_CASE_ ,							identifier=SCREAMING_SNAKE_CASE_	)




							def 						__snake_case					(   self     :   Optional[Any]	):
											lowerCAmelCase__      			=						Path('''src/transformers'''	)
											lowerCAmelCase__      			=						['''configuration''', '''modeling''', '''tokenization''']
											self.analyze_directory(SCREAMING_SNAKE_CASE_ ,							n_identifier=SCREAMING_SNAKE_CASE_	)




							def 						__snake_case					(   self     :   Tuple	):
											lowerCAmelCase__      			=						Path('''docs/source'''	)
											lowerCAmelCase__      			=						['''favicon.ico''']
											self.analyze_directory(SCREAMING_SNAKE_CASE_ ,							ignore_files=SCREAMING_SNAKE_CASE_ ,							only_modules=SCREAMING_SNAKE_CASE_	)





