



import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin






class 		lowercase						(			_snake_case):






	"""simple docstring"""


	a__				: Any		       =							"Speech2TextFeatureExtractor"
	a__				: List[Any]		       =							"Speech2TextTokenizer"




	def __init__(     self     :						int						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						List[str]					)      ->			List[Any]:
							super().__init__(UpperCamelCase__						,  UpperCamelCase__					)
							UpperCAmelCase_=       self.feature_extractor
							UpperCAmelCase_=       False




	def __call__(     self     :						str						,  *__UpperCAmelCase     :						Union[str, Any]						,  **__UpperCAmelCase     :						Union[str, Any]					)      ->			Optional[Any]:
							# For backward compatibility
							if self._in_target_context_manager:
													return self.current_processor(*UpperCamelCase__						,  **UpperCamelCase__					)

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

							if text is None:
													return inputs
							elif audio is None:
													return encodings
							else:
													UpperCAmelCase_=       encodings["""input_ids"""]
													return inputs




	def   _SCREAMING_SNAKE_CASE		(     self     :						List[Any]						,  *__UpperCAmelCase     :						List[str]						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[Any]:
							return self.tokenizer.batch_decode(*UpperCamelCase__						,  **UpperCamelCase__					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Any						,  *__UpperCAmelCase     :						Tuple						,  **__UpperCAmelCase     :						int					)      ->			List[str]:
							return self.tokenizer.decode(*UpperCamelCase__						,  **UpperCamelCase__					)




	@contextmanager
	def   _SCREAMING_SNAKE_CASE		(     self     :						Any					)      ->			int:
							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."""					)
							UpperCAmelCase_=       True
							UpperCAmelCase_=       self.tokenizer
							yield
							UpperCAmelCase_=       self.feature_extractor
							UpperCAmelCase_=       False









import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


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






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						Any						,  *__UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]=None						,  __UpperCAmelCase     :						Optional[int]=None						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[int]:
							super().__init__(*__UpperCAmelCase						,  **__UpperCAmelCase					)
							UpperCAmelCase_=       eval_examples
							UpperCAmelCase_=       post_process_function




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple						,  __UpperCAmelCase     :						Optional[Dataset] = None						,  __UpperCAmelCase     :						Optional[Any]=None						,  __UpperCAmelCase     :						Optional[List[str]] = None						,  __UpperCAmelCase     :						str = "eval"						,  **__UpperCAmelCase     :						Any						,  )      ->			Dict[str, float]:
							UpperCAmelCase_=       gen_kwargs.copy()
							UpperCAmelCase_=       (
							    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length"""					) is not None else self.args.generation_max_length
							)
							UpperCAmelCase_=       (
							    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams"""					) is not None else self.args.generation_num_beams
							)
							UpperCAmelCase_=       gen_kwargs

							UpperCAmelCase_=       self.eval_dataset if eval_dataset is None else eval_dataset
							UpperCAmelCase_=       self.get_eval_dataloader(__UpperCAmelCase					)
							UpperCAmelCase_=       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Evaluation"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics
							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()					):
																			if not key.startswith(F"""{metric_key_prefix}_"""					):
																									UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)

													metrics.update(output.metrics					)
							else:
													UpperCAmelCase_=       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(__UpperCAmelCase					)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()					)

							UpperCAmelCase_=       self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  __UpperCAmelCase					)
							return metrics




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[int]=None						,  __UpperCAmelCase     :						str = "test"						,  **__UpperCAmelCase     :						List[str]					)      ->			Tuple:
							UpperCAmelCase_=       gen_kwargs.copy()

							UpperCAmelCase_=       self.get_test_dataloader(__UpperCAmelCase					)

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Prediction"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics

							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  """predict"""					)
							UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()					):
													if not key.startswith(F"""{metric_key_prefix}_"""					):
																			UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)
							metrics.update(output.metrics					)
							return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=__UpperCAmelCase					)




