





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


snake_case_     :       Tuple						=  logging.get_logger(__name__)


@add_end_docstrings(lowerCamelCase     )
class 					__a      (lowerCamelCase     ):

							def __init__(							self							:     Optional[Any]       ,     **__magic_name__							:     List[Any]   )					->       Union[str, Any]:







													"""simple docstring"""
													super().__init__(**__magic_name__   )

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

							def __call__(							self							:     Union[str, Any]       ,     __magic_name__							:     Union[np.ndarray, bytes, str]       ,     **__magic_name__							:     Any   )					->       Any:







													"""simple docstring"""
													return super().__call__(__magic_name__       ,     **__magic_name__   )

							def     UpperCAmelCase__	(							self							:     str       ,     **__magic_name__							:     List[str]   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  {}
													if "candidate_labels" in kwargs:
																			UpperCAmelCase_			:      Optional[int]     						=  kwargs['''candidate_labels''']
													if "hypothesis_template" in kwargs:
																			UpperCAmelCase_			:      Union[str, Any]     						=  kwargs['''hypothesis_template''']

													return preprocess_params, {}, {}

							def     UpperCAmelCase__	(							self							:     Union[str, Any]       ,     __magic_name__							:     List[Any]       ,     __magic_name__							:     int=None       ,     __magic_name__							:     Optional[Any]="This is a sound of {}."   )					->       str:







													"""simple docstring"""
													if isinstance(__magic_name__       ,     __magic_name__   ):
																			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_			:      Optional[int]     						=  requests.get(__magic_name__   ).content
																			else:
																									with open(__magic_name__       ,     '''rb'''   ) as f:
																															UpperCAmelCase_			:      Optional[int]     						=  f.read()

													if isinstance(__magic_name__       ,     __magic_name__   ):
																			UpperCAmelCase_			:      str     						=  ffmpeg_read(__magic_name__       ,     self.feature_extractor.sampling_rate   )

													if not isinstance(__magic_name__       ,     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_			:      Union[str, Any]     						=  self.feature_extractor(
													    [audio]       ,     sampling_rate=self.feature_extractor.sampling_rate       ,     return_tensors='''pt'''   )
													UpperCAmelCase_			:      List[Any]     						=  candidate_labels
													UpperCAmelCase_			:      Dict     						=  [hypothesis_template.format(__magic_name__   ) for x in candidate_labels]
													UpperCAmelCase_			:      Optional[int]     						=  self.tokenizer(__magic_name__       ,     return_tensors=self.framework       ,     padding=__magic_name__   )
													UpperCAmelCase_			:      Optional[Any]     						=  [text_inputs]
													return inputs

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     Tuple   )					->       Tuple:







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  model_inputs.pop('''candidate_labels'''   )
													UpperCAmelCase_			:      Dict     						=  model_inputs.pop('''text_inputs'''   )
													if isinstance(text_inputs[0]       ,     __magic_name__   ):
																			UpperCAmelCase_			:      str     						=  text_inputs[0]
													else:
																			# Batching case.
																			UpperCAmelCase_			:      List[Any]     						=  text_inputs[0][0]

													UpperCAmelCase_			:      Optional[int]     						=  self.model(**__magic_name__       ,     **__magic_name__   )

													UpperCAmelCase_			:      Union[str, Any]     						=  {
													    '''candidate_labels''': candidate_labels,
													    '''logits''': outputs.logits_per_audio,
													}
													return model_outputs



							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     str   )					->       str:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  model_outputs.pop('''candidate_labels'''   )
													UpperCAmelCase_			:      Optional[int]     						=  model_outputs['''logits'''][0]

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

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












'''simple docstring'''







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool


class 					__a      (lowerCamelCase     ):
							__a					:   List[Any]									=       "openai/whisper-base"
							__a					:   Optional[Any]									=       (
							    "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the "
							    "transcribed text."
							)
							__a					:   Any									=       "transcriber"
							__a					:   str									=       WhisperProcessor
							__a					:   List[Any]									=       WhisperForConditionalGeneration

							__a					:   int									=       ["audio"]
							__a					:   Optional[Any]									=       ["text"]

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     List[str]   )					->       Optional[int]:







													"""simple docstring"""
													return self.pre_processor(__magic_name__       ,     return_tensors='''pt'''   ).input_features

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     Dict   )					->       Tuple:







													"""simple docstring"""
													return self.model.generate(inputs=__magic_name__   )



							def     UpperCAmelCase__	(							self							:     List[str]       ,     __magic_name__							:     Dict   )					->       str:







													"""simple docstring"""
													return self.pre_processor.batch_decode(__magic_name__       ,     skip_special_tokens=__magic_name__   )[0]





