




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


a_				:    Tuple										=     logging.get_logger(__name__)

@add_end_docstrings(lowercase__				)
class __lowercase(      lowercase__				):




					'''simple docstring'''


					def __init__(    self						,	**__a     ):
								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     ):
								return super().__call__(__a						,	**__a     )
					def     snake_case_				(    self						,	**__a     ):
								__lowerCamelCase					:	str	       =				{}
								if "candidate_labels" in kwargs:
											__lowerCamelCase					:	Any	       =				kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
											__lowerCamelCase					:	Optional[int]	       =				kwargs['hypothesis_template']

								return preprocess_params, {}, {}
					def     snake_case_				(    self						,	__a						,	__a=None						,	__a="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
														__lowerCamelCase					:	Any	       =				requests.get(__a     ).content
											else:
														with open(__a						,	'rb'     ) as f:
																	__lowerCamelCase					:	Tuple	       =				f.read()

								if isinstance(__a						,	__a     ):
											__lowerCamelCase					:	Optional[Any]	       =				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'     )

								__lowerCamelCase					:	Union[str, Any]	       =				self.feature_extractor(
								    [audio]						,	sampling_rate=self.feature_extractor.sampling_rate						,	return_tensors='pt'     )
								__lowerCamelCase					:	Optional[Any]	       =				candidate_labels
								__lowerCamelCase					:	List[Any]	       =				[hypothesis_template.format(__a     ) for x in candidate_labels]
								__lowerCamelCase					:	Dict	       =				self.tokenizer(__a						,	return_tensors=self.framework						,	padding=__a     )
								__lowerCamelCase					:	List[Any]	       =				[text_inputs]
								return inputs
					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	List[Any]	       =				model_inputs.pop('candidate_labels'     )
								__lowerCamelCase					:	str	       =				model_inputs.pop('text_inputs'     )
								if isinstance(text_inputs[0]						,	__a     ):
											__lowerCamelCase					:	List[Any]	       =				text_inputs[0]
								else:
											# Batching case.
											__lowerCamelCase					:	Optional[Any]	       =				text_inputs[0][0]

								__lowerCamelCase					:	Any	       =				self.model(**__a						,	**__a     )

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





					def     snake_case_				(    self						,	__a     ):
								__lowerCamelCase					:	str	       =				model_outputs.pop('candidate_labels'     )
								__lowerCamelCase					:	List[Any]	       =				model_outputs['logits'][0]

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

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









"""simple docstring"""
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin

class __lowercase(      lowercase__				):




					'''simple docstring'''


					__a						:						List[str]     		= 'Speech2TextFeatureExtractor'
					__a						:						Optional[int]     		= 'Speech2TextTokenizer'
					def __init__(    self						,	__a						,	__a     ):
								super().__init__(__a						,	__a     )
								__lowerCamelCase					:	Union[str, Any]	       =				self.feature_extractor
								__lowerCamelCase					:	List[str]	       =				False
					def __call__(    self						,	*__a						,	**__a     ):
								# For backward compatibility
								if self._in_target_context_manager:
											return self.current_processor(*__a						,	**__a     )

								if "raw_speech" in kwargs:
											warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'     )
											__lowerCamelCase					:	str	       =				kwargs.pop('raw_speech'     )
								else:
											__lowerCamelCase					:	Optional[Any]	       =				kwargs.pop('audio'						,	__a     )
								__lowerCamelCase					:	Optional[Any]	       =				kwargs.pop('sampling_rate'						,	__a     )
								__lowerCamelCase					:	Optional[int]	       =				kwargs.pop('text'						,	__a     )
								if len(__a     ) > 0:
											__lowerCamelCase					:	Optional[int]	       =				args[0]
											__lowerCamelCase					:	str	       =				args[1:]

								if audio is None and text is None:
											raise ValueError('You need to specify either an `audio` or `text` input to process.'     )

								if audio is not None:
											__lowerCamelCase					:	Dict	       =				self.feature_extractor(__a						,	*__a						,	sampling_rate=__a						,	**__a     )
								if text is not None:
											__lowerCamelCase					:	Optional[int]	       =				self.tokenizer(__a						,	**__a     )

								if text is None:
											return inputs
								elif audio is None:
											return encodings
								else:
											__lowerCamelCase					:	Any	       =				encodings['input_ids']
											return inputs
					def     snake_case_				(    self						,	*__a						,	**__a     ):
								return self.tokenizer.batch_decode(*__a						,	**__a     )
					def     snake_case_				(    self						,	*__a						,	**__a     ):
								return self.tokenizer.decode(*__a						,	**__a     )





					@contextmanager
					def     snake_case_				(    self     ):
								warnings.warn(
								    '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '
								    'labels by using the argument `text` of the regular `__call__` method (either in the same call as '
								    'your audio inputs, or in a separate call.'     )
								__lowerCamelCase					:	int	       =				True
								__lowerCamelCase					:	Union[str, Any]	       =				self.tokenizer
								yield
								__lowerCamelCase					:	Tuple	       =				self.feature_extractor
								__lowerCamelCase					:	List[str]	       =				False



