





from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import pyarrow as pa


if TYPE_CHECKING:
      from .features import FeatureType







@dataclass
class    __snake_case	:
       lowerCAmelCase__						=					42
       lowerCAmelCase__						=					None
       # Automatically constructed
       lowerCAmelCase__						=					"dict"
       lowerCAmelCase__						=					None
       lowerCAmelCase__						=					field(default="""Translation"""       ,      init=__lowerCamelCase       ,      repr=__lowerCamelCase      )




       def __call__(  self			:   Optional[Any]		):
         return pa.struct({lang: pa.string() for lang in sorted(self.languages		)}		)






       def 							UpperCAmelCase__			(  self			:   Dict		):
         from .features import Value

         return {k: Value("""string"""		) for k in sorted(self.languages		)}







@dataclass
class    __snake_case	:
       lowerCAmelCase__						=					None
       lowerCAmelCase__						=					None
       lowerCAmelCase__						=					None
       # Automatically constructed
       lowerCAmelCase__						=					"dict"
       lowerCAmelCase__						=					None
       lowerCAmelCase__						=					field(default="""TranslationVariableLanguages"""       ,      init=__lowerCamelCase       ,      repr=__lowerCamelCase      )




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						Optional[Any]			  =						sorted(set(self.languages		)		) if self.languages else None
         __snake_case:						Optional[Any]			  =						len(self.languages		) if self.languages else None




       def __call__(  self			:   List[Any]		):
         return pa.struct({"""language""": pa.list_(pa.string()		), """translation""": pa.list_(pa.string()		)}		)




       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   Optional[int]		):
         __snake_case:						str			  =						set(self.languages		)
         if self.languages and set(__lowercase		) - lang_set:
           raise ValueError(
               f'''Some languages in example ({', '.join(sorted(set(__lowercase		) - lang_set		)		)}) are not in valid set ({', '.join(__lowercase		)}).'''		)

         # Convert dictionary into tuples, splitting out cases where there are
         # multiple translations for a single language.
         __snake_case:						Union[str, Any]			  =						[]
         for lang, text in translation_dict.items():
           if isinstance(__lowercase							,    __lowercase		):
             translation_tuples.append((lang, text)		)
           else:
             translation_tuples.extend([(lang, el) for el in text]		)

        # Ensure translations are in ascending order by language code.
         __snake_case:						int			  =						zip(*sorted(__lowercase		)		)

         return {"language": languages, "translation": translations}






       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         from .features import Sequence, Value

         return {
             "language": Sequence(Value("""string"""		)		),
             "translation": Sequence(Value("""string"""		)		),
         }













import math
import time

from transformers import Trainer, 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    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       def __init__(  self			:   str							,    *A			:   Dict							,    A			:   Optional[int]=None							,    A			:   Tuple=None							,    **A			:   Optional[int]		):
         super().__init__(*A							,    **A		)
         __snake_case:						List[Any]			  =						eval_examples
         __snake_case:						str			  =						post_process_function




       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   Dict=None							,    A			:   int=None							,    A			:   List[Any]=None							,    A			:   str = "eval"		):
         __snake_case:						int			  =						self.eval_dataset if eval_dataset is None else eval_dataset
         __snake_case:						Any			  =						self.get_eval_dataloader(A		)
         __snake_case:						Optional[Any]			  =						self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case:						Union[str, Any]			  =						self.compute_metrics
         __snake_case:						List[str]			  =						None
         __snake_case:						Tuple			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Tuple			  =						time.time()
         try:
           __snake_case:						Any			  =						eval_loop(
               A							,    description="""Evaluation"""							,    prediction_loss_only=True if compute_metrics is None else None							,    ignore_keys=A							,    metric_key_prefix=A							,    )
         finally:
           __snake_case:						Optional[int]			  =						compute_metrics
         __snake_case:						Union[str, Any]			  =						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(
                 A							,    A							,    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
           __snake_case:						List[str]			  =						self.post_process_function(A							,    A							,    output.predictions		)
           __snake_case:						List[Any]			  =						self.compute_metrics(A		)

           # Prefix all keys with metric_key_prefix + '_'
           for key in list(metrics.keys()		):
             if not key.startswith(f'''{metric_key_prefix}_'''		):
               __snake_case:						str			  =						metrics.pop(A		)
           metrics.update(output.metrics		)
         else:
           __snake_case:						List[Any]			  =						output.metrics

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

         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()		)

         __snake_case:						str			  =						self.callback_handler.on_evaluate(self.args							,    self.state							,    self.control							,    A		)
         return metrics






       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   List[Any]							,    A			:   List[str]							,    A			:   str=None							,    A			:   str = "test"		):
         __snake_case:						Optional[Any]			  =						self.get_test_dataloader(A		)

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case:						Optional[int]			  =						self.compute_metrics
         __snake_case:						List[Any]			  =						None
         __snake_case:						str			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Dict			  =						time.time()
         try:
           __snake_case:						str			  =						eval_loop(
               A							,    description="""Prediction"""							,    prediction_loss_only=True if compute_metrics is None else None							,    ignore_keys=A							,    metric_key_prefix=A							,    )
         finally:
           __snake_case:						List[Any]			  =						compute_metrics
         __snake_case:						Dict			  =						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(
                 A							,    A							,    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

         __snake_case:						Union[str, Any]			  =						self.post_process_function(A							,    A							,    output.predictions							,    """predict"""		)
         __snake_case:						str			  =						self.compute_metrics(A		)

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()		):
           if not key.startswith(f'''{metric_key_prefix}_'''		):
             __snake_case:						List[str]			  =						metrics.pop(A		)
         metrics.update(output.metrics		)
         return PredictionOutput(predictions=predictions.predictions							,    label_ids=predictions.label_ids							,    metrics=A		)






