



"""simple docstring"""





import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowerCamelCase       	=						logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-classification/requirements.txt""")

lowerCamelCase       	=						list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
lowerCamelCase       	=						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def        a__     (				lowerCAmelCase__				):
      with open(lowerCAmelCase__     ,      "rb"				) as f:
            UpperCAmelCase_      			=							Image.open(lowerCAmelCase__				)
            return im.convert("RGB"				)
@dataclass
class 				lowercase__       :







       '''simple docstring'''


       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={
               '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
           }    , )
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}				)
       UpperCamelCase						=					field(default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''A folder containing the training data.'''}				)
       UpperCamelCase						=					field(default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''A folder containing the validation data.'''}				)
       UpperCamelCase						=					field(
           default=0.1_5    , metadata={'''help''': '''Percent to split off of train for validation.'''}				)
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={
               '''help''': (
                   '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                   '''value if set.'''
               )
           }    , )
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={
               '''help''': (
                   '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                   '''value if set.'''
               )
           }    , )



       def 					lowercase__    (							self      :  Tuple   )			->						List[str]:


             '''simple docstring'''




             if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
                   raise ValueError(
                       "You must specify either a dataset name from the hub or a train and/or validation directory."   )



@dataclass
class 				lowercase__       :







       '''simple docstring'''


       UpperCamelCase						=					field(
           default='''google/vit-base-patch16-224-in21k'''    , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}    , )
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(SCREAMING_SNAKE_CASE				)}    , )
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}				)
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}				)
       UpperCamelCase						=					field(
           default='''main'''    , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}    , )
       UpperCamelCase						=					field(default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''Name or path of preprocessor config.'''}				)
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={
               '''help''': (
                   '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                   '''with private models).'''
               )
           }    , )
       UpperCamelCase						=					field(
           default=SCREAMING_SNAKE_CASE    , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}    , )



def        a__     (				lowerCAmelCase__				):
      UpperCAmelCase_      			=							torch.stack([example["pixel_values"] for example in examples]				)
      UpperCAmelCase_      			=							torch.tensor([example["labels"] for example in examples]				)
      return {"pixel_values": pixel_values, "labels": labels}
def        a__     (				):
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.

      UpperCAmelCase_      			=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
      if len(sys.argv				) == 2 and sys.argv[1].endswith(".json"				):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            UpperCAmelCase_			,   UpperCAmelCase_			,   UpperCAmelCase_      			=							parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
      else:
            UpperCAmelCase_			,   UpperCAmelCase_			,   UpperCAmelCase_      			=							parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry("run_image_classification"     ,      lowerCAmelCase__     ,      lowerCAmelCase__				)

      # Setup logging
      logging.basicConfig(
          format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"     ,      datefmt="%m/%d/%Y %H:%M:%S"     ,      handlers=[logging.StreamHandler(sys.stdout				)]     ,      )

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      UpperCAmelCase_      			=							training_args.get_process_log_level()
      logger.setLevel(lowerCAmelCase__				)
      transformers.utils.logging.set_verbosity(lowerCAmelCase__				)
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # Log on each process the small summary:
      logger.warning(
          f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
          + f"""distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}"""				)
      logger.info(f"""Training/evaluation parameters {training_args}"""				)

      # Detecting last checkpoint.
      UpperCAmelCase_      			=							None
      if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
            UpperCAmelCase_      			=							get_last_checkpoint(training_args.output_dir				)
            if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
                  raise ValueError(
                      f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                      "Use --overwrite_output_dir to overcome."				)
            elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
                  logger.info(
                      f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                      "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."				)

    # Set seed before initializing model.
      set_seed(training_args.seed				)

      # Initialize our dataset and prepare it for the 'image-classification' task.
      if data_args.dataset_name is not None:
            UpperCAmelCase_      			=							load_dataset(
                data_args.dataset_name     ,      data_args.dataset_config_name     ,      cache_dir=model_args.cache_dir     ,      task="image-classification"     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )
      else:
            UpperCAmelCase_      			=							{}
            if data_args.train_dir is not None:
                  UpperCAmelCase_      			=							os.path.join(data_args.train_dir     ,      "**"				)
            if data_args.validation_dir is not None:
                  UpperCAmelCase_      			=							os.path.join(data_args.validation_dir     ,      "**"				)
            UpperCAmelCase_      			=							load_dataset(
                "imagefolder"     ,      data_files=lowerCAmelCase__     ,      cache_dir=model_args.cache_dir     ,      task="image-classification"     ,      )

      # If we don't have a validation split, split off a percentage of train as validation.
      UpperCAmelCase_      			=							None if "validation" in dataset.keys() else data_args.train_val_split
      if isinstance(data_args.train_val_split     ,      lowerCAmelCase__				) and data_args.train_val_split > 0.0:
            UpperCAmelCase_      			=							dataset["train"].train_test_split(data_args.train_val_split				)
            UpperCAmelCase_      			=							split["train"]
            UpperCAmelCase_      			=							split["test"]

      # Prepare label mappings.
      # We'll include these in the model's config to get human readable labels in the Inference API.
      UpperCAmelCase_      			=							dataset["train"].features["labels"].names
      UpperCAmelCase_			,   UpperCAmelCase_      			=							{}, {}
      for i, label in enumerate(lowerCAmelCase__				):
            UpperCAmelCase_      			=							str(lowerCAmelCase__				)
            UpperCAmelCase_      			=							label

      # Load the accuracy metric from the datasets package
      UpperCAmelCase_      			=							evaluate.load("accuracy"				)

      # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      def compute_metrics(lowerCAmelCase__				):
            return metric.compute(predictions=np.argmax(p.predictions     ,      axis=1				)     ,      references=p.label_ids				)

      UpperCAmelCase_      			=							AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path     ,      num_labels=len(lowerCAmelCase__				)     ,      labelaid=lowerCAmelCase__     ,      idalabel=lowerCAmelCase__     ,      finetuning_task="image-classification"     ,      cache_dir=model_args.cache_dir     ,      revision=model_args.model_revision     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )
      UpperCAmelCase_      			=							AutoModelForImageClassification.from_pretrained(
          model_args.model_name_or_path     ,      from_tf=bool(".ckpt" in model_args.model_name_or_path				)     ,      config=lowerCAmelCase__     ,      cache_dir=model_args.cache_dir     ,      revision=model_args.model_revision     ,      use_auth_token=True if model_args.use_auth_token else None     ,      ignore_mismatched_sizes=model_args.ignore_mismatched_sizes     ,      )
      UpperCAmelCase_      			=							AutoImageProcessor.from_pretrained(
          model_args.image_processor_name or model_args.model_name_or_path     ,      cache_dir=model_args.cache_dir     ,      revision=model_args.model_revision     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )

      # Define torchvision transforms to be applied to each image.
      if "shortest_edge" in image_processor.size:
            UpperCAmelCase_      			=							image_processor.size["shortest_edge"]
      else:
            UpperCAmelCase_      			=							(image_processor.size["height"], image_processor.size["width"])
      UpperCAmelCase_      			=							Normalize(mean=image_processor.image_mean     ,      std=image_processor.image_std				)
      UpperCAmelCase_      			=							Compose(
          [
              RandomResizedCrop(lowerCAmelCase__				),
              RandomHorizontalFlip(),
              ToTensor(),
              normalize,
          ]				)
      UpperCAmelCase_      			=							Compose(
          [
              Resize(lowerCAmelCase__				),
              CenterCrop(lowerCAmelCase__				),
              ToTensor(),
              normalize,
          ]				)

      def train_transforms(lowerCAmelCase__				):
            UpperCAmelCase_      			=							[
                _train_transforms(pil_img.convert("RGB"				)				) for pil_img in example_batch["image"]
            ]
            return example_batch

      def val_transforms(lowerCAmelCase__				):
            UpperCAmelCase_      			=							[_val_transforms(pil_img.convert("RGB"				)				) for pil_img in example_batch["image"]]
            return example_batch

      if training_args.do_train:
            if "train" not in dataset:
                  raise ValueError("--do_train requires a train dataset"				)
            if data_args.max_train_samples is not None:
                  UpperCAmelCase_      			=							(
                      dataset["train"].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
                  )
            # Set the training transforms
            dataset["train"].set_transform(lowerCAmelCase__				)

      if training_args.do_eval:
            if "validation" not in dataset:
                  raise ValueError("--do_eval requires a validation dataset"				)
            if data_args.max_eval_samples is not None:
                  UpperCAmelCase_      			=							(
                      dataset["validation"].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
                  )
            # Set the validation transforms
            dataset["validation"].set_transform(lowerCAmelCase__				)

      # Initalize our trainer
      UpperCAmelCase_      			=							Trainer(
          model=lowerCAmelCase__     ,      args=lowerCAmelCase__     ,      train_dataset=dataset["train"] if training_args.do_train else None     ,      eval_dataset=dataset["validation"] if training_args.do_eval else None     ,      compute_metrics=lowerCAmelCase__     ,      tokenizer=lowerCAmelCase__     ,      data_collator=lowerCAmelCase__     ,      )

      # Training
      if training_args.do_train:
            UpperCAmelCase_      			=							None
            if training_args.resume_from_checkpoint is not None:
                  UpperCAmelCase_      			=							training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  UpperCAmelCase_      			=							last_checkpoint
            UpperCAmelCase_      			=							trainer.train(resume_from_checkpoint=lowerCAmelCase__				)
            trainer.save_model()
            trainer.log_metrics("train"     ,      train_result.metrics				)
            trainer.save_metrics("train"     ,      train_result.metrics				)
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            UpperCAmelCase_      			=							trainer.evaluate()
            trainer.log_metrics("eval"     ,      lowerCAmelCase__				)
            trainer.save_metrics("eval"     ,      lowerCAmelCase__				)

      # Write model card and (optionally) push to hub
      UpperCAmelCase_      			=							{
          "finetuned_from": model_args.model_name_or_path,
          "tasks": "image-classification",
          "dataset": data_args.dataset_name,
          "tags": ["image-classification", "vision"],
      }
      if training_args.push_to_hub:
            trainer.push_to_hub(**lowerCAmelCase__				)
      else:
            trainer.create_model_card(**lowerCAmelCase__				)


if __name__ == "__main__":
  main()









"""simple docstring"""





import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


lowerCamelCase       	=						get_tests_dir("""fixtures/test_sentencepiece.model""")


if is_torch_available():
  from transformers.models.mbart.modeling_mbart import shift_tokens_right

lowerCamelCase       	=						250_004
lowerCamelCase       	=						250_020
@require_sentencepiece
@require_tokenizers
class 				lowercase__       (   SCREAMING_SNAKE_CASE    , unittest.TestCase				):







       '''simple docstring'''


       UpperCamelCase						=					MBartTokenizer
       UpperCamelCase						=					MBartTokenizerFast
       UpperCamelCase						=					True
       UpperCamelCase						=					True



       def 					lowercase__    (							self      :  int   )			->						Union[str, Any]:


             '''simple docstring'''




             super().setUp()

             # We have a SentencePiece fixture for testing
             UpperCAmelCase_      			=							MBartTokenizer(_UpperCAmelCase		,    keep_accents=_UpperCAmelCase   )
             tokenizer.save_pretrained(self.tmpdirname   )



       def 					lowercase__    (							self      :  Any   )			->						int:


             '''simple docstring'''




             UpperCAmelCase_      			=							MBartTokenizer(_UpperCAmelCase		,    keep_accents=_UpperCAmelCase   )

             UpperCAmelCase_      			=							tokenizer.tokenize("This is a test"   )
             self.assertListEqual(_UpperCAmelCase		,    ["▁This", "▁is", "▁a", "▁t", "est"]   )

             self.assertListEqual(
                 tokenizer.convert_tokens_to_ids(_UpperCAmelCase   )		,    [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]		,    )

             UpperCAmelCase_      			=							tokenizer.tokenize("I was born in 92000, and this is falsé."   )
             self.assertListEqual(
                 _UpperCAmelCase		,    [
                     SPIECE_UNDERLINE + "I",
                     SPIECE_UNDERLINE + "was",
                     SPIECE_UNDERLINE + "b",
                     "or",
                     "n",
                     SPIECE_UNDERLINE + "in",
                     SPIECE_UNDERLINE + "",
                     "9",
                     "2",
                     "0",
                     "0",
                     "0",
                     ",",
                     SPIECE_UNDERLINE + "and",
                     SPIECE_UNDERLINE + "this",
                     SPIECE_UNDERLINE + "is",
                     SPIECE_UNDERLINE + "f",
                     "al",
                     "s",
                     "é",
                     ".",
                 ]		,    )
             UpperCAmelCase_      			=							tokenizer.convert_tokens_to_ids(_UpperCAmelCase   )
             self.assertListEqual(
                 _UpperCAmelCase		,    [
                     value + tokenizer.fairseq_offset
                     for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
                     #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
                 ]		,    )

             UpperCAmelCase_      			=							tokenizer.convert_ids_to_tokens(_UpperCAmelCase   )
             self.assertListEqual(
                 _UpperCAmelCase		,    [
                     SPIECE_UNDERLINE + "I",
                     SPIECE_UNDERLINE + "was",
                     SPIECE_UNDERLINE + "b",
                     "or",
                     "n",
                     SPIECE_UNDERLINE + "in",
                     SPIECE_UNDERLINE + "",
                     "<unk>",
                     "2",
                     "0",
                     "0",
                     "0",
                     ",",
                     SPIECE_UNDERLINE + "and",
                     SPIECE_UNDERLINE + "this",
                     SPIECE_UNDERLINE + "is",
                     SPIECE_UNDERLINE + "f",
                     "al",
                     "s",
                     "<unk>",
                     ".",
                 ]		,    )







       def 					lowercase__    (							self      :  Optional[Any]   )			->						Dict:


             '''simple docstring'''




             if not self.test_slow_tokenizer:
                   # as we don't have a slow version, we can't compare the outputs between slow and fast versions
                   return

             UpperCAmelCase_      			=							(self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {})
             for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                   with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""   ):
                         UpperCAmelCase_      			=							self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase		,    **_UpperCAmelCase   )
                         UpperCAmelCase_      			=							self.tokenizer_class.from_pretrained(_UpperCAmelCase		,    **_UpperCAmelCase   )

                         UpperCAmelCase_      			=							tempfile.mkdtemp()

                         UpperCAmelCase_      			=							tokenizer_r.save_pretrained(_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.save_pretrained(_UpperCAmelCase   )

                         # Checks it save with the same files + the tokenizer.json file for the fast one
                         self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files   )   )
                         UpperCAmelCase_      			=							tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f   )
                         self.assertSequenceEqual(_UpperCAmelCase		,    _UpperCAmelCase   )

                         # Checks everything loads correctly in the same way
                         UpperCAmelCase_      			=							tokenizer_r.from_pretrained(_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.from_pretrained(_UpperCAmelCase   )

                         # Check special tokens are set accordingly on Rust and Python
                         for key in tokenizer_pp.special_tokens_map:
                               self.assertTrue(hasattr(_UpperCAmelCase		,    _UpperCAmelCase   )   )
                               # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
                               # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

                         shutil.rmtree(_UpperCAmelCase   )

                         # Save tokenizer rust, legacy_format=True
                         UpperCAmelCase_      			=							tempfile.mkdtemp()

                         UpperCAmelCase_      			=							tokenizer_r.save_pretrained(_UpperCAmelCase		,    legacy_format=_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.save_pretrained(_UpperCAmelCase   )

                         # Checks it save with the same files
                         self.assertSequenceEqual(_UpperCAmelCase		,    _UpperCAmelCase   )

                         # Checks everything loads correctly in the same way
                         UpperCAmelCase_      			=							tokenizer_r.from_pretrained(_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.from_pretrained(_UpperCAmelCase   )

                         # Check special tokens are set accordingly on Rust and Python
                         for key in tokenizer_pp.special_tokens_map:
                               self.assertTrue(hasattr(_UpperCAmelCase		,    _UpperCAmelCase   )   )

                         shutil.rmtree(_UpperCAmelCase   )

                         # Save tokenizer rust, legacy_format=False
                         UpperCAmelCase_      			=							tempfile.mkdtemp()

                         UpperCAmelCase_      			=							tokenizer_r.save_pretrained(_UpperCAmelCase		,    legacy_format=_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.save_pretrained(_UpperCAmelCase   )

                         # Checks it saved the tokenizer.json file
                         self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files   )   )

                         # Checks everything loads correctly in the same way
                         UpperCAmelCase_      			=							tokenizer_r.from_pretrained(_UpperCAmelCase   )
                         UpperCAmelCase_      			=							tokenizer_p.from_pretrained(_UpperCAmelCase   )

                         # Check special tokens are set accordingly on Rust and Python
                         for key in tokenizer_pp.special_tokens_map:
                               self.assertTrue(hasattr(_UpperCAmelCase		,    _UpperCAmelCase   )   )

                         shutil.rmtree(_UpperCAmelCase   )



@require_torch
@require_sentencepiece
@require_tokenizers
class 				lowercase__       (   unittest.TestCase				):







       '''simple docstring'''


       UpperCamelCase						=					'''facebook/mbart-large-en-ro'''
       UpperCamelCase						=					[
           ''' UN Chief Says There Is No Military Solution in Syria''',
           ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''',
       ]
       UpperCamelCase						=					[
           '''Şeful ONU declară că nu există o soluţie militară în Siria''',
           '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei'''
           ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'''
           ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''',
       ]
       UpperCamelCase						=					[82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE]



       @classmethod
       def 					lowercase__    (							cls      :  Optional[Any]   )			->						List[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							MBartTokenizer.from_pretrained(
                 cls.checkpoint_name		,    src_lang="en_XX"		,    tgt_lang="ro_RO"   )
             UpperCAmelCase_      			=							1
             return cls



       def 					lowercase__    (							self      :  List[Any]   )			->						Union[str, Any]:


             '''simple docstring'''




             self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"]		,    250001   )
             self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"]		,    250004   )
             self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"]		,    250020   )



       def 					lowercase__    (							self      :  Any   )			->						Tuple:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.tokenizer.batch_encode_plus(self.src_text   ).input_ids[0]
             self.assertListEqual(self.expected_src_tokens		,    _UpperCAmelCase   )



       def 					lowercase__    (							self      :  Any   )			->						str:


             '''simple docstring'''




             self.assertIn(_UpperCAmelCase		,    self.tokenizer.all_special_ids   )
             UpperCAmelCase_      			=							[RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2]
             UpperCAmelCase_      			=							self.tokenizer.decode(_UpperCAmelCase		,    skip_special_tokens=_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.tokenizer.decode(generated_ids[1:]		,    skip_special_tokens=_UpperCAmelCase   )
             self.assertEqual(_UpperCAmelCase		,    _UpperCAmelCase   )
             self.assertNotIn(self.tokenizer.eos_token		,    _UpperCAmelCase   )



       def 					lowercase__    (							self      :  Tuple   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							["this is gunna be a long sentence " * 20]
             assert isinstance(src_text[0]		,    _UpperCAmelCase   )
             UpperCAmelCase_      			=							10
             UpperCAmelCase_      			=							self.tokenizer(_UpperCAmelCase		,    max_length=_UpperCAmelCase		,    truncation=_UpperCAmelCase   ).input_ids[0]
             self.assertEqual(ids[-2]		,    2   )
             self.assertEqual(ids[-1]		,    _UpperCAmelCase   )
             self.assertEqual(len(_UpperCAmelCase   )		,    _UpperCAmelCase   )



       def 					lowercase__    (							self      :  int   )			->						int:


             '''simple docstring'''




             self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"]   )		,    [250026, 250001]   )



       def 					lowercase__    (							self      :  Any   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							tempfile.mkdtemp()
             UpperCAmelCase_      			=							self.tokenizer.fairseq_tokens_to_ids
             self.tokenizer.save_pretrained(_UpperCAmelCase   )
             UpperCAmelCase_      			=							MBartTokenizer.from_pretrained(_UpperCAmelCase   )
             self.assertDictEqual(new_tok.fairseq_tokens_to_ids		,    _UpperCAmelCase   )



       @require_torch
       def 					lowercase__    (							self      :  List[Any]   )			->						int:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.tokenizer(self.src_text		,    text_target=self.tgt_text		,    padding=_UpperCAmelCase		,    return_tensors="pt"   )
             UpperCAmelCase_      			=							shift_tokens_right(batch["labels"]		,    self.tokenizer.pad_token_id   )

             # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
             assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
             assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
             assert batch.decoder_input_ids[1][-1] == 2
             assert batch.labels[1][-2:].tolist() == [2, RO_CODE]



       @require_torch
       def 					lowercase__    (							self      :  Any   )			->						Optional[int]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.tokenizer(
                 self.src_text		,    text_target=self.tgt_text		,    padding=_UpperCAmelCase		,    truncation=_UpperCAmelCase		,    max_length=len(self.expected_src_tokens   )		,    return_tensors="pt"		,    )

             UpperCAmelCase_      			=							shift_tokens_right(batch["labels"]		,    self.tokenizer.pad_token_id   )

             self.assertIsInstance(_UpperCAmelCase		,    _UpperCAmelCase   )

             self.assertEqual((2, 14)		,    batch.input_ids.shape   )
             self.assertEqual((2, 14)		,    batch.attention_mask.shape   )
             UpperCAmelCase_      			=							batch.input_ids.tolist()[0]
             self.assertListEqual(self.expected_src_tokens		,    _UpperCAmelCase   )
             self.assertEqual(2		,    batch.decoder_input_ids[0, -1]   )  # EOS
             # Test that special tokens are reset
             self.assertEqual(self.tokenizer.prefix_tokens		,    []   )
             self.assertEqual(self.tokenizer.suffix_tokens		,    [self.tokenizer.eos_token_id, EN_CODE]   )



       def 					lowercase__    (							self      :  Union[str, Any]   )			->						Union[str, Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.tokenizer(self.src_text		,    padding=_UpperCAmelCase		,    truncation=_UpperCAmelCase		,    max_length=3		,    return_tensors="pt"   )
             UpperCAmelCase_      			=							self.tokenizer(
                 text_target=self.tgt_text		,    padding=_UpperCAmelCase		,    truncation=_UpperCAmelCase		,    max_length=10		,    return_tensors="pt"   )
             UpperCAmelCase_      			=							targets["input_ids"]
             UpperCAmelCase_      			=							shift_tokens_right(_UpperCAmelCase		,    self.tokenizer.pad_token_id   )

             self.assertEqual(batch.input_ids.shape[1]		,    3   )
             self.assertEqual(batch.decoder_input_ids.shape[1]		,    10   )







       @require_torch
       def 					lowercase__    (							self      :  Optional[int]   )			->						Any:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.tokenizer._build_translation_inputs(
                 "A test"		,    return_tensors="pt"		,    src_lang="en_XX"		,    tgt_lang="ar_AR"   )

             self.assertEqual(
                 nested_simplify(_UpperCAmelCase   )		,    {
                     # A, test, EOS, en_XX
                     "input_ids": [[62, 3034, 2, 250004]],
                     "attention_mask": [[1, 1, 1, 1]],
                     # ar_AR
                     "forced_bos_token_id": 250001,
                 }		,    )




