






'''simple docstring'''

import functools
import gc
import inspect

import torch

from .imports import is_npu_available, is_xpu_available
def     __lowercase  (*_lowercase     )   ->     int:


     """simple docstring"""
     if not isinstance(_lowercase,						_lowercase     ):
          __lowerCamelCase						:       Optional[Any]				   =				list(_lowercase     )
     for i in range(len(_lowercase     )     ):
          __lowerCamelCase						:       Optional[int]				   =				None
     gc.collect()
     if is_xpu_available():
          torch.xpu.empty_cache()
     elif is_npu_available():
          torch.npu.empty_cache()
     else:
          torch.cuda.empty_cache()
     return objects
def     __lowercase  (_lowercase     )   ->     bool:


     """simple docstring"""
     __lowerCamelCase						:       Tuple				   =				[
         """CUDA out of memory.""",  # CUDA OOM
         """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""",  # CUDNN SNAFU
         """DefaultCPUAllocator: can't allocate memory""",  # CPU OOM
     ]
     if isinstance(_lowercase,						_lowercase     ) and len(exception.args     ) == 1:
          return any(err in exception.args[0] for err in _statements     )
     return False
def     __lowercase  (_lowercase = None,						_lowercase = 128     )   ->     Dict:


     """simple docstring"""
     if function is None:
          return functools.partial(_lowercase,						starting_batch_size=_lowercase     )

     __lowerCamelCase						:       Optional[Any]				   =				starting_batch_size

     def decorator(*_lowercase,						**_lowercase     ):
          nonlocal batch_size
          gc.collect()
          if is_xpu_available():
               torch.xpu.empty_cache()
          elif is_npu_available():
               torch.npu.empty_cache()
          else:
               torch.cuda.empty_cache()
          __lowerCamelCase						:       Union[str, Any]				   =				list(inspect.signature(_lowercase     ).parameters.keys()     )
          # Guard against user error
          if len(_lowercase     ) < (len(_lowercase     ) + 1):
               __lowerCamelCase						:       Dict				   =				""", """.join([f"{arg}={value}" for arg, value in zip(params[1:],						args[1:]     )]     )
               raise TypeError(
                   f"Batch size was passed into `{function.__name__}` as the first argument when called."
                   f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`"     )
          while True:
               if batch_size == 0:
                    raise RuntimeError("""No executable batch size found, reached zero."""     )
               try:
                    return function(_lowercase,						*_lowercase,						**_lowercase     )
               except Exception as e:
                    if should_reduce_batch_size(_lowercase     ):
                         gc.collect()
                         if is_xpu_available():
                              torch.xpu.empty_cache()
                         elif is_npu_available():
                              torch.npu.empty_cache()
                         else:
                              torch.cuda.empty_cache()
                         batch_size //= 2
                    else:
                         raise

     return decorator











'''simple docstring'''

from ...processing_utils import ProcessorMixin







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     List[Any]   		=			'SpeechT5FeatureExtractor'
       snake_case__    :     Union[str, Any]   		=			'SpeechT5Tokenizer'




       def __init__(					self      : Union[str, Any]	,    A__      : str	,    A__      : Tuple					):


            """simple docstring"""







            super().__init__(A__	,    A__					)




       def __call__(					self      : List[Any]	,    *A__      : Any	,    **A__      : Optional[int]					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				kwargs.pop("""audio"""	,    A__					)
            __lowerCamelCase						:       Any				   =				kwargs.pop("""text"""	,    A__					)
            __lowerCamelCase						:       Union[str, Any]				   =				kwargs.pop("""text_target"""	,    A__					)
            __lowerCamelCase						:       Union[str, Any]				   =				kwargs.pop("""audio_target"""	,    A__					)
            __lowerCamelCase						:       Any				   =				kwargs.pop("""sampling_rate"""	,    A__					)

            if audio is not None and text is not None:
                 raise ValueError(
                     """Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?"""					)
            if audio_target is not None and text_target is not None:
                 raise ValueError(
                     """Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?"""					)
            if audio is None and audio_target is None and text is None and text_target is None:
                 raise ValueError(
                     """You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process."""					)

            if audio is not None:
                 __lowerCamelCase						:       Optional[int]				   =				self.feature_extractor(A__	,    *A__	,    sampling_rate=A__	,    **A__					)
            elif text is not None:
                 __lowerCamelCase						:       Optional[int]				   =				self.tokenizer(A__	,    **A__					)
            else:
                 __lowerCamelCase						:       Tuple				   =				None

            if audio_target is not None:
                 __lowerCamelCase						:       Optional[int]				   =				self.feature_extractor(audio_target=A__	,    *A__	,    sampling_rate=A__	,    **A__					)
                 __lowerCamelCase						:       Union[str, Any]				   =				targets["""input_values"""]
            elif text_target is not None:
                 __lowerCamelCase						:       Tuple				   =				self.tokenizer(A__	,    **A__					)
                 __lowerCamelCase						:       List[str]				   =				targets["""input_ids"""]
            else:
                 __lowerCamelCase						:       Dict				   =				None

            if inputs is None:
                 return targets

            if targets is not None:
                 __lowerCamelCase						:       str				   =				labels

                 __lowerCamelCase						:       int				   =				targets.get("""attention_mask"""					)
                 if decoder_attention_mask is not None:
                      __lowerCamelCase						:       Optional[int]				   =				decoder_attention_mask

            return inputs




       def 					a_					(					self      : Any	,    *A__      : Union[str, Any]	,    **A__      : List[str]					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				kwargs.pop("""input_values"""	,    A__					)
            __lowerCamelCase						:       List[Any]				   =				kwargs.pop("""input_ids"""	,    A__					)
            __lowerCamelCase						:       List[Any]				   =				kwargs.pop("""labels"""	,    A__					)

            if input_values is not None and input_ids is not None:
                 raise ValueError("""Cannot process both `input_values` and `input_ids` inputs."""					)
            if input_values is None and input_ids is None and labels is None:
                 raise ValueError(
                     """You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded."""					)

            if input_values is not None:
                 __lowerCamelCase						:       List[Any]				   =				self.feature_extractor.pad(A__	,    *A__	,    **A__					)
            elif input_ids is not None:
                 __lowerCamelCase						:       Any				   =				self.tokenizer.pad(A__	,    **A__					)
            else:
                 __lowerCamelCase						:       Any				   =				None

            if labels is not None:
                 if "input_ids" in labels or (isinstance(A__	,    A__					) and "input_ids" in labels[0]):
                      __lowerCamelCase						:       List[Any]				   =				self.tokenizer.pad(A__	,    **A__					)
                      __lowerCamelCase						:       Tuple				   =				targets["""input_ids"""]
                 else:
                      __lowerCamelCase						:       Optional[int]				   =				self.feature_extractor.feature_size
                      __lowerCamelCase						:       Any				   =				self.feature_extractor.num_mel_bins
                      __lowerCamelCase						:       List[str]				   =				self.feature_extractor.pad(A__	,    *A__	,    **A__					)
                      __lowerCamelCase						:       Dict				   =				feature_size_hack
                      __lowerCamelCase						:       List[Any]				   =				targets["""input_values"""]
            else:
                 __lowerCamelCase						:       Optional[int]				   =				None

            if inputs is None:
                 return targets

            if targets is not None:
                 __lowerCamelCase						:       Dict				   =				labels

                 __lowerCamelCase						:       List[str]				   =				targets.get("""attention_mask"""					)
                 if decoder_attention_mask is not None:
                      __lowerCamelCase						:       int				   =				decoder_attention_mask

            return inputs




       def 					a_					(					self      : Optional[Any]	,    *A__      : List[Any]	,    **A__      : Optional[int]					):


            """simple docstring"""







            return self.tokenizer.batch_decode(*A__	,    **A__					)




       def 					a_					(					self      : Any	,    *A__      : int	,    **A__      : Dict					):


            """simple docstring"""







            return self.tokenizer.decode(*A__	,    **A__					)



