


"""simple docstring"""


import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer



class 	_a   (   __snake_case			):
    a_     :					Optional[Any]   							=     """Wav2Vec2FeatureExtractor"""
    a_     :					Tuple   							=     """AutoTokenizer"""
    def __init__(			self				:       List[Any]				,       SCREAMING_SNAKE_CASE__				:       str				,       SCREAMING_SNAKE_CASE__				:       Optional[Any]					):
          super().__init__(SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__					)
          lowerCamelCase__							     =		self.feature_extractor
          lowerCamelCase__							     =		False
    @classmethod
    def   _UpperCamelCase							(			cls				:       int				,       SCREAMING_SNAKE_CASE__				:       List[str]				,       **SCREAMING_SNAKE_CASE__				:       Optional[int]					):
          try:
                return super().from_pretrained(SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)
          except OSError:
                warnings.warn(
                    F'Loading a tokenizer inside {cls.__name__} from a config that does not'
                    ' include a `tokenizer_class` attribute is deprecated and will be '
                    'removed in v5. Please add `\'tokenizer_class\': \'Wav2Vec2CTCTokenizer\'`'
                    ' attribute to either your `config.json` or `tokenizer_config.json` '
                    'file to suppress this warning: '				,       SCREAMING_SNAKE_CASE__				,       )

                lowerCamelCase__							     =		WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)
                lowerCamelCase__							     =		WavaVecaCTCTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)

                return cls(feature_extractor=SCREAMING_SNAKE_CASE__				,       tokenizer=SCREAMING_SNAKE_CASE__					)
    def __call__(			self				:       Union[str, Any]				,       *SCREAMING_SNAKE_CASE__				:       Optional[Any]				,       **SCREAMING_SNAKE_CASE__				:       List[Any]					):
          # For backward compatibility
          if self._in_target_context_manager:
                return self.current_processor(*SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)

          if "raw_speech" in kwargs:
                warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'					)
                lowerCamelCase__							     =		kwargs.pop('raw_speech'					)
          else:
                lowerCamelCase__							     =		kwargs.pop('audio'				,       SCREAMING_SNAKE_CASE__					)
          lowerCamelCase__							     =		kwargs.pop('sampling_rate'				,       SCREAMING_SNAKE_CASE__					)
          lowerCamelCase__							     =		kwargs.pop('text'				,       SCREAMING_SNAKE_CASE__					)
          if len(SCREAMING_SNAKE_CASE__					) > 0:
                lowerCamelCase__							     =		args[0]
                lowerCamelCase__							     =		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__							     =		self.feature_extractor(SCREAMING_SNAKE_CASE__				,       *SCREAMING_SNAKE_CASE__				,       sampling_rate=SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)
          if text is not None:
                lowerCamelCase__							     =		self.tokenizer(SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)

          if text is None:
                return inputs
          elif audio is None:
                return encodings
          else:
                lowerCamelCase__							     =		encodings["""input_ids"""]
                return inputs
    def   _UpperCamelCase							(			self				:       List[str]				,       *SCREAMING_SNAKE_CASE__				:       Dict				,       **SCREAMING_SNAKE_CASE__				:       List[str]					):
          # For backward compatibility
          if self._in_target_context_manager:
                return self.current_processor.pad(*SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)

          lowerCamelCase__							     =		kwargs.pop('input_features'				,       SCREAMING_SNAKE_CASE__					)
          lowerCamelCase__							     =		kwargs.pop('labels'				,       SCREAMING_SNAKE_CASE__					)
          if len(SCREAMING_SNAKE_CASE__					) > 0:
                lowerCamelCase__							     =		args[0]
                lowerCamelCase__							     =		args[1:]

          if input_features is not None:
                lowerCamelCase__							     =		self.feature_extractor.pad(SCREAMING_SNAKE_CASE__				,       *SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)
          if labels is not None:
                lowerCamelCase__							     =		self.tokenizer.pad(SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)

          if labels is None:
                return input_features
          elif input_features is None:
                return labels
          else:
                lowerCamelCase__							     =		labels["""input_ids"""]
                return input_features
    def   _UpperCamelCase							(			self				:       List[Any]				,       *SCREAMING_SNAKE_CASE__				:       Optional[Any]				,       **SCREAMING_SNAKE_CASE__				:       Tuple					):
          return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)
    def   _UpperCamelCase							(			self				:       int				,       *SCREAMING_SNAKE_CASE__				:       str				,       **SCREAMING_SNAKE_CASE__				:       Tuple					):
          return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__				,       **SCREAMING_SNAKE_CASE__					)


    @contextmanager
    def   _UpperCamelCase							(			self				:       Dict					):
          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__							     =		True
          lowerCamelCase__							     =		self.tokenizer
          yield
          lowerCamelCase__							     =		self.feature_extractor
          lowerCamelCase__							     =		False











"""simple docstring"""







from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
				import torch

if is_torch_tpu_available(check_device=False):
				import torch_xla.core.xla_model as xm


_lowerCAmelCase            =	logging.get_logger(__name__)


@dataclass
class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : str												=		[
						    """no_inference""",
						    """no_cuda""",
						    """no_tpu""",
						    """no_speed""",
						    """no_memory""",
						    """no_env_print""",
						    """no_multi_process""",
						]






						def __init__(		self  :Union[str, Any]			, **__magic_name__  :int				)      ->Any:
										for deprecated_arg in self.deprecated_args:
														if deprecated_arg in kwargs:
																		lowercase    :      int       = deprecated_arg[3:]
																		setattr(self			, __magic_name__			, not kwargs.pop(__magic_name__				)				)
																		logger.warning(
																		    f"""{deprecated_arg} is depreciated. Please use --no_{positive_arg} or"""
																		    f""" {positive_arg}={kwargs[positive_arg]}"""				)

										lowercase    :      List[str]       = kwargs.pop("""torchscript"""			, self.torchscript				)
										lowercase    :      Any       = kwargs.pop("""torch_xla_tpu_print_metrics"""			, self.torch_xla_tpu_print_metrics				)
										lowercase    :      Union[str, Any]       = kwargs.pop("""fp16_opt_level"""			, self.fpaa_opt_level				)
										super().__init__(**__magic_name__				)

						_SCREAMING_SNAKE_CASE  : bool												=		field(default=__snake_case						,						metadata={"""help""": """Trace the models using torchscript"""}     )
						_SCREAMING_SNAKE_CASE  : bool												=		field(default=__snake_case						,						metadata={"""help""": """Print Xla/PyTorch tpu metrics"""}     )
						_SCREAMING_SNAKE_CASE  : str												=		field(
						    default="""O1"""						,						metadata={
						        """help""": (
						            """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. """
						            """See details at https://nvidia.github.io/apex/amp.html"""
						        )
						    }						,						)






						@cached_property
						def      __snake_case      (		self  :Optional[int]				)      ->Tuple["torch.device", int]:
										requires_backends(self			, ["""torch"""]				)
										logger.info("""PyTorch: setting up devices"""				)
										if not self.cuda:
														lowercase    :      Optional[Any]       = torch.device("""cpu"""				)
														lowercase    :      int       = 0
										elif is_torch_tpu_available():
														lowercase    :      Any       = xm.xla_device()
														lowercase    :      List[str]       = 0
										else:
														lowercase    :      int       = torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""				)
														lowercase    :      Any       = torch.cuda.device_count()
										return device, n_gpu






						@property
						def      __snake_case      (		self  :Optional[int]				)      ->Union[str, Any]:
										return is_torch_tpu_available() and self.tpu






						@property
						def      __snake_case      (		self  :Optional[int]				)      ->int:
										requires_backends(self			, ["""torch"""]				)
										# TODO(PVP): currently only single GPU is supported
										return torch.cuda.current_device()






						@property
						def      __snake_case      (		self  :Optional[int]				)      ->"torch.device":
										requires_backends(self			, ["""torch"""]				)
										return self._setup_devices[0]






						@property
						def      __snake_case      (		self  :Optional[Any]				)      ->str:
										requires_backends(self			, ["""torch"""]				)
										return self._setup_devices[1]






						@property
						def      __snake_case      (		self  :int				)      ->List[str]:
										return self.n_gpu > 0
