


import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
		import jax.numpy as jnp

class 						__a (							snake_case_     ):
		def __get__(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=None		)					->			Union[str, Any]:




									"""simple docstring"""





									if obj is None:
																return self
									if self.fget is None:
																raise AttributeError('unreadable attribute'		)
									_UpperCAmelCase											=     "__cached_" + self.fget.__name__
									_UpperCAmelCase											=     getattr(UpperCamelCase__     ,       UpperCamelCase__     ,       UpperCamelCase__		)
									if cached is None:
																_UpperCAmelCase											=     self.fget(UpperCamelCase__		)
																setattr(UpperCamelCase__     ,       UpperCamelCase__     ,       UpperCamelCase__		)
									return cached



def 			lowerCAmelCase__					(     a__:						Dict			)    ->						Dict:


							'''simple docstring'''





							_UpperCAmelCase											=     val.lower()
							if val in {"y", "yes", "t", "true", "on", "1"}:
														return 1
							if val in {"n", "no", "f", "false", "off", "0"}:
														return 0
							raise ValueError(F'''invalid truth value {val!r}'''			)

def 			lowerCAmelCase__					(     a__:						Tuple			)    ->						Optional[Any]:


							'''simple docstring'''





							if is_torch_fx_proxy(a__			):
														return True
							if is_torch_available():
														import torch

														if isinstance(a__     ,    torch.Tensor			):
																					return True
							if is_tf_available():
														import tensorflow as tf

														if isinstance(a__     ,    tf.Tensor			):
																					return True

							if is_flax_available():
														import jax.numpy as jnp
														from jax.core import Tracer

														if isinstance(a__     ,    (jnp.ndarray, Tracer)			):
																					return True

							return isinstance(a__     ,    np.ndarray			)

def 			lowerCAmelCase__					(     a__:						int			)    ->						Any:


							'''simple docstring'''





							return isinstance(a__     ,    np.ndarray			)

def 			lowerCAmelCase__					(     a__:						str			)    ->						int:


							'''simple docstring'''





							return _is_numpy(a__			)

def 			lowerCAmelCase__					(     a__:						Tuple			)    ->						Optional[Any]:


							'''simple docstring'''





							import torch

							return isinstance(a__     ,    torch.Tensor			)

def 			lowerCAmelCase__					(     a__:						Dict			)    ->						Dict:


							'''simple docstring'''





							return False if not is_torch_available() else _is_torch(a__			)

def 			lowerCAmelCase__					(     a__:						str			)    ->						str:


							'''simple docstring'''





							import torch

							return isinstance(a__     ,    torch.device			)

def 			lowerCAmelCase__					(     a__:						Optional[Any]			)    ->						Optional[Any]:


							'''simple docstring'''





							return False if not is_torch_available() else _is_torch_device(a__			)

def 			lowerCAmelCase__					(     a__:						str			)    ->						Optional[Any]:


							'''simple docstring'''





							import torch

							if isinstance(a__     ,    a__			):
														if hasattr(a__     ,    a__			):
																					_UpperCAmelCase											=     getattr(a__     ,    a__			)
														else:
																					return False
							return isinstance(a__     ,    torch.dtype			)

def 			lowerCAmelCase__					(     a__:						Dict			)    ->						Optional[int]:


							'''simple docstring'''





							return False if not is_torch_available() else _is_torch_dtype(a__			)

def 			lowerCAmelCase__					(     a__:						Dict			)    ->						Any:


							'''simple docstring'''





							import tensorflow as tf

							return isinstance(a__     ,    tf.Tensor			)

def 			lowerCAmelCase__					(     a__:						List[str]			)    ->						int:


							'''simple docstring'''





							return False if not is_tf_available() else _is_tensorflow(a__			)

def 			lowerCAmelCase__					(     a__:						List[str]			)    ->						Dict:


							'''simple docstring'''





							import tensorflow as tf

							# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
							if hasattr(a__     ,    'is_symbolic_tensor'			):
														return tf.is_symbolic_tensor(a__			)
							return type(a__			) == tf.Tensor

def 			lowerCAmelCase__					(     a__:						int			)    ->						str:


							'''simple docstring'''





							return False if not is_tf_available() else _is_tf_symbolic_tensor(a__			)

def 			lowerCAmelCase__					(     a__:						Any			)    ->						Optional[Any]:


							'''simple docstring'''





							import jax.numpy as jnp  # noqa: F811

							return isinstance(a__     ,    jnp.ndarray			)

def 			lowerCAmelCase__					(     a__:						List[str]			)    ->						Optional[int]:


							'''simple docstring'''





							return False if not is_flax_available() else _is_jax(a__			)

def 			lowerCAmelCase__					(     a__:						Any			)    ->						Tuple:


							'''simple docstring'''





							if isinstance(a__     ,    (dict, UserDict)			):
														return {k: to_py_obj(a__			) for k, v in obj.items()}
							elif isinstance(a__     ,    (list, tuple)			):
														return [to_py_obj(a__			) for o in obj]
							elif is_tf_tensor(a__			):
														return obj.numpy().tolist()
							elif is_torch_tensor(a__			):
														return obj.detach().cpu().tolist()
							elif is_jax_tensor(a__			):
														return np.asarray(a__			).tolist()
							elif isinstance(a__     ,    (np.ndarray, np.number)			):  # tolist also works on 0d np arrays
														return obj.tolist()
							else:
														return obj

def 			lowerCAmelCase__					(     a__:						Union[str, Any]			)    ->						List[str]:


							'''simple docstring'''





							if isinstance(a__     ,    (dict, UserDict)			):
														return {k: to_numpy(a__			) for k, v in obj.items()}
							elif isinstance(a__     ,    (list, tuple)			):
														return np.array(a__			)
							elif is_tf_tensor(a__			):
														return obj.numpy()
							elif is_torch_tensor(a__			):
														return obj.detach().cpu().numpy()
							elif is_jax_tensor(a__			):
														return np.asarray(a__			)
							else:
														return obj

class 						__a (							snake_case_     ):
		def       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     fields(self		)

									# Safety and consistency checks
									if not len(UpperCamelCase__		):
																raise ValueError(f'''{self.__class__.__name__} has no fields.'''		)
									if not all(field.default is None for field in class_fields[1:]		):
																raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.'''		)

									_UpperCAmelCase											=     getattr(self     ,       class_fields[0].name		)
									_UpperCAmelCase											=     all(getattr(self     ,       field.name		) is None for field in class_fields[1:]		)

									if other_fields_are_none and not is_tensor(UpperCamelCase__		):
																if isinstance(UpperCamelCase__     ,       UpperCamelCase__		):
																							_UpperCAmelCase											=     first_field.items()
																							_UpperCAmelCase											=     True
																else:
																							try:
																														_UpperCAmelCase											=     iter(UpperCamelCase__		)
																														_UpperCAmelCase											=     True
																							except TypeError:
																														_UpperCAmelCase											=     False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
																if first_field_iterator:
																							for idx, element in enumerate(UpperCamelCase__		):
																														if (
																														    not isinstance(UpperCamelCase__     ,       (list, tuple)		)
																														    or not len(UpperCamelCase__		) == 2
																														    or not isinstance(element[0]     ,       UpperCamelCase__		)
																														):
																																					if idx == 0:
																																												# If we do not have an iterator of key/values, set it as attribute
																																												_UpperCAmelCase											=     first_field
																																					else:
																																												# If we have a mixed iterator, raise an error
																																												raise ValueError(
																																												    f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).'''		)
																																					break
																														setattr(self     ,       element[0]     ,       element[1]		)
																														if element[1] is not None:
																																					_UpperCAmelCase											=     element[1]
																elif first_field is not None:
																							_UpperCAmelCase											=     first_field
									else:
																for field in class_fields:
																							_UpperCAmelCase											=     getattr(self     ,       field.name		)
																							if v is not None:
																														_UpperCAmelCase											=     v
		def __delitem__(     self     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''		)
		def       UpperCAmelCase__							(     self     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE		)					->			Tuple:




									"""simple docstring"""





									raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''		)
		def       UpperCAmelCase__							(     self     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE		)					->			Any:




									"""simple docstring"""





									raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''		)
		def       UpperCAmelCase__							(     self     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE		)					->			Any:




									"""simple docstring"""





									raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''		)
		def __getitem__(     self     ,       _SCREAMING_SNAKE_CASE		)					->			Dict:




									"""simple docstring"""





									if isinstance(UpperCamelCase__     ,       UpperCamelCase__		):
																_UpperCAmelCase											=     dict(self.items()		)
																return inner_dict[k]
									else:
																return self.to_tuple()[k]
		def __setattr__(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[Any]:




									"""simple docstring"""





									if name in self.keys() and value is not None:
																# Don't call self.__setitem__ to avoid recursion errors
																super().__setitem__(UpperCamelCase__     ,       UpperCamelCase__		)
									super().__setattr__(UpperCamelCase__     ,       UpperCamelCase__		)
		def __setitem__(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[Any]:




									"""simple docstring"""





									super().__setitem__(UpperCamelCase__     ,       UpperCamelCase__		)
									# Don't call self.__setattr__ to avoid recursion errors
									super().__setattr__(UpperCamelCase__     ,       UpperCamelCase__		)






		def       UpperCAmelCase__							(     self		)					->			Tuple[Any]:




									"""simple docstring"""





									return tuple(self[k] for k in self.keys()		)



class 						__a (							snake_case_       , snake_case_     ):
		@classmethod
		def       UpperCAmelCase__							(     cls     ,       _SCREAMING_SNAKE_CASE		)					->			List[str]:




									"""simple docstring"""





									raise ValueError(
									    f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}'''		)



class 						__a (							snake_case_     ):
		_a      :    Optional[Any]           =      '''longest'''
		_a      :    Tuple           =      '''max_length'''
		_a      :    Optional[Any]           =      '''do_not_pad'''



class 						__a (							snake_case_     ):
		_a      :    Tuple           =      '''pt'''
		_a      :    int           =      '''tf'''
		_a      :    List[str]           =      '''np'''
		_a      :    Union[str, Any]           =      '''jax'''



class 						__a :
		def __init__(     self     ,       _SCREAMING_SNAKE_CASE		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     context_managers
									_UpperCAmelCase											=     ExitStack()
		def __enter__(     self		)					->			List[Any]:




									"""simple docstring"""





									for context_manager in self.context_managers:
																self.stack.enter_context(UpperCamelCase__		)






		def __exit__(     self     ,       *_SCREAMING_SNAKE_CASE     ,       **_SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									self.stack.__exit__(*UpperCamelCase__     ,       **UpperCamelCase__		)



def 			lowerCAmelCase__					(     a__:						List[Any]			)    ->						List[str]:


							'''simple docstring'''





							_UpperCAmelCase											=     infer_framework(a__			)
							if framework == "tf":
														_UpperCAmelCase											=     inspect.signature(model_class.call			)  # TensorFlow models
							elif framework == "pt":
														_UpperCAmelCase											=     inspect.signature(model_class.forward			)  # PyTorch models
							else:
														_UpperCAmelCase											=     inspect.signature(model_class.__call__			)  # Flax models

							for p in signature.parameters:
														if p == "return_loss" and signature.parameters[p].default is True:
																					return True

							return False

def 			lowerCAmelCase__					(     a__:						int			)    ->						Optional[int]:


							'''simple docstring'''





							_UpperCAmelCase											=     model_class.__name__
							_UpperCAmelCase											=     infer_framework(a__			)
							if framework == "tf":
														_UpperCAmelCase											=     inspect.signature(model_class.call			)  # TensorFlow models
							elif framework == "pt":
														_UpperCAmelCase											=     inspect.signature(model_class.forward			)  # PyTorch models
							else:
														_UpperCAmelCase											=     inspect.signature(model_class.__call__			)  # Flax models

							if "QuestionAnswering" in model_name:
														return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
							else:
														return [p for p in signature.parameters if "label" in p]

def 			lowerCAmelCase__					(     a__:						MutableMapping     ,    a__:						str = ""     ,    a__:						str = "."			)    ->						Tuple:


							'''simple docstring'''





							def _flatten_dict(a__:						List[Any]     ,    a__:						str=""     ,    a__:						Tuple="."			):
														for k, v in d.items():
																					_UpperCAmelCase											=     str(a__			) + delimiter + str(a__			) if parent_key else k
																					if v and isinstance(a__     ,    a__			):
																												yield from flatten_dict(a__     ,    a__     ,    delimiter=a__			).items()
																					else:
																												yield key, v

							return dict(_flatten_dict(a__     ,    a__     ,    a__			)			)

@contextmanager
def 			lowerCAmelCase__					(     a__:						str     ,    a__:						bool = False			)    ->						Union[str, Any]:


							'''simple docstring'''





							if use_temp_dir:
														with tempfile.TemporaryDirectory() as tmp_dir:
																					yield tmp_dir
							else:
														yield working_dir

def 			lowerCAmelCase__					(     a__:						List[Any]     ,    a__:						Any=None			)    ->						Optional[int]:


							'''simple docstring'''





							if is_numpy_array(a__			):
														return np.transpose(a__     ,    axes=a__			)
							elif is_torch_tensor(a__			):
														return array.T if axes is None else array.permute(*a__			)
							elif is_tf_tensor(a__			):
														import tensorflow as tf

														return tf.transpose(a__     ,    perm=a__			)
							elif is_jax_tensor(a__			):
														return jnp.transpose(a__     ,    axes=a__			)
							else:
														raise ValueError(F'''Type not supported for transpose: {type(a__			)}.'''			)

def 			lowerCAmelCase__					(     a__:						Union[str, Any]     ,    a__:						Any			)    ->						Union[str, Any]:


							'''simple docstring'''





							if is_numpy_array(a__			):
														return np.reshape(a__     ,    a__			)
							elif is_torch_tensor(a__			):
														return array.reshape(*a__			)
							elif is_tf_tensor(a__			):
														import tensorflow as tf

														return tf.reshape(a__     ,    a__			)
							elif is_jax_tensor(a__			):
														return jnp.reshape(a__     ,    a__			)
							else:
														raise ValueError(F'''Type not supported for reshape: {type(a__			)}.'''			)

def 			lowerCAmelCase__					(     a__:						str     ,    a__:						List[Any]=None			)    ->						str:


							'''simple docstring'''





							if is_numpy_array(a__			):
														return np.squeeze(a__     ,    axis=a__			)
							elif is_torch_tensor(a__			):
														return array.squeeze() if axis is None else array.squeeze(dim=a__			)
							elif is_tf_tensor(a__			):
														import tensorflow as tf

														return tf.squeeze(a__     ,    axis=a__			)
							elif is_jax_tensor(a__			):
														return jnp.squeeze(a__     ,    axis=a__			)
							else:
														raise ValueError(F'''Type not supported for squeeze: {type(a__			)}.'''			)

def 			lowerCAmelCase__					(     a__:						Optional[Any]     ,    a__:						List[Any]			)    ->						Any:


							'''simple docstring'''





							if is_numpy_array(a__			):
														return np.expand_dims(a__     ,    a__			)
							elif is_torch_tensor(a__			):
														return array.unsqueeze(dim=a__			)
							elif is_tf_tensor(a__			):
														import tensorflow as tf

														return tf.expand_dims(a__     ,    axis=a__			)
							elif is_jax_tensor(a__			):
														return jnp.expand_dims(a__     ,    axis=a__			)
							else:
														raise ValueError(F'''Type not supported for expand_dims: {type(a__			)}.'''			)

def 			lowerCAmelCase__					(     a__:						Optional[Any]			)    ->						Union[str, Any]:


							'''simple docstring'''





							if is_numpy_array(a__			):
														return np.size(a__			)
							elif is_torch_tensor(a__			):
														return array.numel()
							elif is_tf_tensor(a__			):
														import tensorflow as tf

														return tf.size(a__			)
							elif is_jax_tensor(a__			):
														return array.size
							else:
														raise ValueError(F'''Type not supported for expand_dims: {type(a__			)}.'''			)

def 			lowerCAmelCase__					(     a__:						str     ,    a__:						Any			)    ->						Tuple:


							'''simple docstring'''





							for key, value in auto_map.items():
														if isinstance(a__     ,    (tuple, list)			):
																					_UpperCAmelCase											=     [F'''{repo_id}--{v}''' if (v is not None and "--" not in v) else v for v in value]
														elif value is not None and "--" not in value:
																					_UpperCAmelCase											=     F'''{repo_id}--{value}'''

							return auto_map







def 			lowerCAmelCase__					(     a__:						Optional[Any]			)    ->						Optional[Any]:


							'''simple docstring'''





							for base_class in inspect.getmro(a__			):
														_UpperCAmelCase											=     base_class.__module__
														_UpperCAmelCase											=     base_class.__name__
														if module.startswith('tensorflow'			) or module.startswith('keras'			) or name == "TFPreTrainedModel":
																					return "tf"
														elif module.startswith('torch'			) or name == "PreTrainedModel":
																					return "pt"
														elif module.startswith('flax'			) or module.startswith('jax'			) or name == "FlaxPreTrainedModel":
																					return "flax"
							else:
														raise TypeError(F'''Could not infer framework from class {model_class}.'''			)




"""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 _lowerCAmelCase							( snake_case_      ):
   __UpperCAmelCase					:			List[str]				    =    '''openai/whisper-base'''
   __UpperCAmelCase					:			Any				    =    (
       '''This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the '''
       '''transcribed text.'''
   )
   __UpperCAmelCase					:			Tuple				    =    '''transcriber'''
   __UpperCAmelCase					:			Union[str, Any]				    =    WhisperProcessor
   __UpperCAmelCase					:			str				    =    WhisperForConditionalGeneration

   __UpperCAmelCase					:			int				    =    ['''audio''']
   __UpperCAmelCase					:			Optional[int]				    =    ['''text''']







   def 					lowerCamelCase						(      self		,      UpperCamelCase__		)      ->						Tuple:

       '''simple docstring'''




       return self.pre_processor(UpperCamelCase__		,      return_tensors="pt"		).input_features







   def 					lowerCamelCase						(      self		,      UpperCamelCase__		)      ->						int:

       '''simple docstring'''




       return self.model.generate(inputs=UpperCamelCase__		)







   def 					lowerCamelCase						(      self		,      UpperCamelCase__		)      ->						Optional[Any]:

       '''simple docstring'''




       return self.pre_processor.batch_decode(UpperCamelCase__		,      skip_special_tokens=UpperCamelCase__		)[0]





