"""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


lowerCAmelCase__  :  int						     =	logging.get_logger(__name__)
@add_end_docstrings(snake_case__				)
class 				snake_case       ( snake_case__				):




					"""simple docstring"""

					def __init__(				self   :	List[str]    ,**lowerCamelCase__   :	Any			):
									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   :	List[str]    ,lowerCamelCase__   :	Any    ,**lowerCamelCase__   :	List[str]			):
									return super().__call__(_A    ,**_A			)







					def 		__lowerCAmelCase						(				self   :	Optional[int]    ,**lowerCamelCase__   :	List[str]			):
									UpperCAmelCase__             =							{}
									if "candidate_labels" in kwargs:
													UpperCAmelCase__             =							kwargs['candidate_labels']
									if "hypothesis_template" in kwargs:
													UpperCAmelCase__             =							kwargs['hypothesis_template']

									return preprocess_params, {}, {}







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	int    ,lowerCamelCase__   :	Dict=None    ,lowerCamelCase__   :	str="This is a sound of {}."			):
									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
																	UpperCAmelCase__             =							requests.get(_A			).content
													else:
																	with open(_A    ,'rb'			) as f:
																					UpperCAmelCase__             =							f.read()

									if isinstance(_A    ,_A			):
													UpperCAmelCase__             =							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'			)

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







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	int			):
									UpperCAmelCase__             =							model_inputs.pop('candidate_labels'			)
									UpperCAmelCase__             =							model_inputs.pop('text_inputs'			)
									if isinstance(text_inputs[0]    ,_A			):
													UpperCAmelCase__             =							text_inputs[0]
									else:
													# Batching case.
													UpperCAmelCase__             =							text_inputs[0][0]

									UpperCAmelCase__             =							self.model(**_A    ,**_A			)

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







					def 		__lowerCAmelCase						(				self   :	Union[str, Any]    ,lowerCamelCase__   :	str			):
									UpperCAmelCase__             =							model_outputs.pop('candidate_labels'			)
									UpperCAmelCase__             =							model_outputs['logits'][0]

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

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










from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCAmelCase						:   Any			  =     {
    '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''],
}

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				UpperCAmelCase						:   Any			  =     [
				    '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''',
				    '''FalconForCausalLM''',
				    '''FalconModel''',
				    '''FalconPreTrainedModel''',
				    '''FalconForSequenceClassification''',
				    '''FalconForTokenClassification''',
				    '''FalconForQuestionAnswering''',
				]


if TYPE_CHECKING:
				from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_falcon import (
								    FALCON_PRETRAINED_MODEL_ARCHIVE_LIST,
								    FalconForCausalLM,
								    FalconForQuestionAnswering,
								    FalconForSequenceClassification,
								    FalconForTokenClassification,
								    FalconModel,
								    FalconPreTrainedModel,
								)


else:
				import sys

				UpperCAmelCase						:   List[str]			  =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




