
import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging


_A		     =    logging.get_logger(__name__)

_A		     =    '''▁'''

_A		     =    {
    '''vocab_file''': '''vocab.json''',
    '''spm_file''': '''sentencepiece.bpe.model''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

_A		     =    {
    '''vocab_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''',
    },
    '''spm_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''',
    },
    '''tokenizer_config_file''': {
        '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''',
        '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''',
    },
}

_A		     =    {
    '''facebook/m2m100_418M''': 1_024,
}

# fmt: off
_A		     =    {
    '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''],
    '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de''']
}

class 						lowercase_				(				__SCREAMING_SNAKE_CASE ):
 A__  : Union[str, Any]      					=			VOCAB_FILES_NAMES
 A__  : List[str]      					=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 A__  : Optional[int]      					=			PRETRAINED_VOCAB_FILES_MAP
 A__  : Dict      					=			['''input_ids''', '''attention_mask''']

 A__  : List[int]      					=			[]
 A__  : List[int]      					=			[]

 def __init__(					self   ,		__UpperCamelCase   ,		__UpperCamelCase   ,		__UpperCamelCase=None   ,		__UpperCamelCase=None   ,		__UpperCamelCase="<s>"   ,		__UpperCamelCase="</s>"   ,		__UpperCamelCase="</s>"   ,		__UpperCamelCase="<pad>"   ,		__UpperCamelCase="<unk>"   ,		__UpperCamelCase="m2m100"   ,		__UpperCamelCase = None   ,		__UpperCamelCase=8   ,		**__UpperCamelCase   ,		):




        """simple docstring"""


        UpperCamelCase_											=				{} if sp_model_kwargs is None else sp_model_kwargs

        UpperCamelCase_											=				language_codes
        UpperCamelCase_											=				FAIRSEQ_LANGUAGE_CODES[language_codes]
        UpperCamelCase_											=				{lang_code: f'''__{lang_code}__''' for lang_code in fairseq_language_code}

        UpperCamelCase_											=				kwargs.get("""additional_special_tokens"""   ,		[]   )
        kwargs["additional_special_tokens"] += [
            self.get_lang_token(__lowerCAmelCase   )
            for lang_code in fairseq_language_code
            if self.get_lang_token(__lowerCAmelCase   ) not in kwargs["additional_special_tokens"]
        ]

        super().__init__(
            src_lang=__lowerCAmelCase   ,		tgt_lang=__lowerCAmelCase   ,		bos_token=__lowerCAmelCase   ,		eos_token=__lowerCAmelCase   ,		sep_token=__lowerCAmelCase   ,		unk_token=__lowerCAmelCase   ,		pad_token=__lowerCAmelCase   ,		language_codes=__lowerCAmelCase   ,		sp_model_kwargs=self.sp_model_kwargs   ,		num_madeup_words=__lowerCAmelCase   ,		**__lowerCAmelCase   ,		)

        UpperCamelCase_											=				vocab_file
        UpperCamelCase_											=				load_json(__lowerCAmelCase   )
        UpperCamelCase_											=				{v: k for k, v in self.encoder.items()}
        UpperCamelCase_											=				spm_file
        UpperCamelCase_											=				load_spm(__lowerCAmelCase   ,		self.sp_model_kwargs   )

        UpperCamelCase_											=				len(self.encoder   )

        UpperCamelCase_											=				{
            self.get_lang_token(__lowerCAmelCase   ): self.encoder_size + i for i, lang_code in enumerate(__lowerCAmelCase   )
        }
        UpperCamelCase_											=				{lang_code: self.encoder_size + i for i, lang_code in enumerate(__lowerCAmelCase   )}
        UpperCamelCase_											=				{v: k for k, v in self.lang_token_to_id.items()}

        UpperCamelCase_											=				src_lang if src_lang is not None else """en"""
        UpperCamelCase_											=				tgt_lang
        UpperCamelCase_											=				self.get_lang_id(self._src_lang   )
        self.set_src_lang_special_tokens(self._src_lang   )

        UpperCamelCase_											=				num_madeup_words

 @property
 def lowerCamelCase_ (					self   ):




        """simple docstring"""


        return len(self.encoder   ) + len(self.lang_token_to_id   )

 @property
 def lowerCamelCase_ (					self   ):




        """simple docstring"""


        return self._src_lang

 @src_lang.setter
 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				new_src_lang
        self.set_src_lang_special_tokens(self._src_lang   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        return self.sp_model.encode(__lowerCAmelCase   ,		out_type=__lowerCAmelCase   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        if token in self.lang_token_to_id:
               return self.lang_token_to_id[token]
        return self.encoder.get(__lowerCAmelCase   ,		self.encoder[self.unk_token]   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        if index in self.id_to_lang_token:
               return self.id_to_lang_token[index]
        return self.decoder.get(__lowerCAmelCase   ,		self.unk_token   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				[]
        UpperCamelCase_											=				""""""
        for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                      out_string += self.sp_model.decode(__lowerCAmelCase   ) + token
                      UpperCamelCase_											=				[]
               else:
                      current_sub_tokens.append(__lowerCAmelCase   )
        out_string += self.sp_model.decode(__lowerCAmelCase   )
        return out_string.strip()

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ,		__UpperCamelCase = None   ,		__UpperCamelCase = False   ):




        """simple docstring"""


        if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=__lowerCAmelCase   ,		token_ids_a=__lowerCAmelCase   ,		already_has_special_tokens=__lowerCAmelCase   )

        UpperCamelCase_											=				[1] * len(self.prefix_tokens   )
        UpperCamelCase_											=				[1] * len(self.suffix_tokens   )
        if token_ids_a is None:
               return prefix_ones + ([0] * len(__lowerCAmelCase   )) + suffix_ones
        return prefix_ones + ([0] * len(__lowerCAmelCase   )) + ([0] * len(__lowerCAmelCase   )) + suffix_ones

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ,		__UpperCamelCase = None   ):




        """simple docstring"""


        if token_ids_a is None:
               return self.prefix_tokens + token_ids_a + self.suffix_tokens
        # We don't expect to process pairs, but leave the pair logic for API consistency
        return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens

 def lowerCamelCase_ (					self   ):




        """simple docstring"""


        UpperCamelCase_											=				{self.convert_ids_to_tokens(__lowerCAmelCase   ): i for i in range(self.vocab_size   )}
        vocab.update(self.added_tokens_encoder   )
        return vocab

 def __getstate__(					self   ):




        """simple docstring"""


        UpperCamelCase_											=				self.__dict__.copy()
        UpperCamelCase_											=				None
        return state

 def __setstate__(					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				d

        # for backward compatibility
        if not hasattr(self   ,		"""sp_model_kwargs"""   ):
               UpperCamelCase_											=				{}

        UpperCamelCase_											=				load_spm(self.spm_file   ,		self.sp_model_kwargs   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ,		__UpperCamelCase = None   ):




        """simple docstring"""


        UpperCamelCase_											=				Path(__lowerCAmelCase   )
        if not save_dir.is_dir():
               raise OSError(f'''{save_directory} should be a directory'''   )
        UpperCamelCase_											=				save_dir / (
            (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
        )
        UpperCamelCase_											=				save_dir / (
            (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
        )

        save_json(self.encoder   ,		__lowerCAmelCase   )

        if os.path.abspath(self.spm_file   ) != os.path.abspath(__lowerCAmelCase   ) and os.path.isfile(self.spm_file   ):
               copyfile(self.spm_file   ,		__lowerCAmelCase   )
        elif not os.path.isfile(self.spm_file   ):
               with open(__lowerCAmelCase   ,		"""wb"""   ) as fi:
                      UpperCamelCase_											=				self.sp_model.serialized_model_proto()
                      fi.write(__lowerCAmelCase   )

        return (str(__lowerCAmelCase   ), str(__lowerCAmelCase   ))

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ,		__UpperCamelCase = "en"   ,		__UpperCamelCase = None   ,		__UpperCamelCase = "ro"   ,		**__UpperCamelCase   ,		):




        """simple docstring"""


        UpperCamelCase_											=				src_lang
        UpperCamelCase_											=				tgt_lang
        self.set_src_lang_special_tokens(self.src_lang   )
        return super().prepare_seqaseq_batch(__lowerCAmelCase   ,		__lowerCAmelCase   ,		**__lowerCAmelCase   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ,		__UpperCamelCase   ,		__UpperCamelCase   ,		**__UpperCamelCase   ):




        """simple docstring"""


        if src_lang is None or tgt_lang is None:
               raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""   )
        UpperCamelCase_											=				src_lang
        UpperCamelCase_											=				self(__lowerCAmelCase   ,		add_special_tokens=__lowerCAmelCase   ,		**__lowerCAmelCase   )
        UpperCamelCase_											=				self.get_lang_id(__lowerCAmelCase   )
        UpperCamelCase_											=				tgt_lang_id
        return inputs

 def lowerCamelCase_ (					self   ):




        """simple docstring"""


        self.set_src_lang_special_tokens(self.src_lang   )

 def lowerCamelCase_ (					self   ):




        """simple docstring"""


        self.set_tgt_lang_special_tokens(self.tgt_lang   )

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				self.get_lang_token(__lowerCAmelCase   )
        UpperCamelCase_											=				self.lang_token_to_id[lang_token]
        UpperCamelCase_											=				[self.cur_lang_id]
        UpperCamelCase_											=				[self.eos_token_id]

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				self.get_lang_token(__lowerCAmelCase   )
        UpperCamelCase_											=				self.lang_token_to_id[lang_token]
        UpperCamelCase_											=				[self.cur_lang_id]
        UpperCamelCase_											=				[self.eos_token_id]

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        return self.lang_code_to_token[lang]

 def lowerCamelCase_ (					self   ,		__UpperCamelCase   ):




        """simple docstring"""


        UpperCamelCase_											=				self.get_lang_token(__lowerCAmelCase   )
        return self.lang_token_to_id[lang_token]




def  lowerCamelCase__ (  a__     :     str		,					a__     :     Dict[str, Any]   )						->		sentencepiece.SentencePieceProcessor:
       UpperCamelCase_											=				sentencepiece.SentencePieceProcessor(**__a   )
       spm.Load(str(__a   )   )
       return spm




def  lowerCamelCase__ (  a__     :     str   )						->		Union[Dict, List]:

       with open(__a		,					"""r"""   ) as f:
              return json.load(__a   )







def  lowerCamelCase__ (  a__     :     List[Any]		,					a__     :     str   )						->		None:

       with open(__a		,					"""w"""   ) as f:
              json.dump(__a		,					__a		,					indent=2   )










import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


A    :					Dict =      logging.get_logger(__name__)







def    __lowerCamelCase					(							__a   :int=None    ,     __a   :Optional[Any]=None    )		->				int:






		"""simple docstring"""

		return field(default_factory=lambda: default    ,     metadata=__a    )






@dataclass
class   A			:
			'''simple docstring'''




			__lowerCamelCase	:       List[str]							=    list_field(
			    default=[]   ,     metadata={
			        '''help''': (
			            '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version'''
			            ''' of all available models'''
			        )
			    }   ,     )

			__lowerCamelCase	:       List[int]							=    list_field(
			    default=[8]   ,     metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''}    )

			__lowerCamelCase	:       List[int]							=    list_field(
			    default=[8, 32, 128, 512]   ,     metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''}   ,     )

			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''}   ,     )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''}   ,     )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Use FP16 to accelerate inference.'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Benchmark training of model'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Verbose memory tracing'''}    )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''}   ,     )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={
			        '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory'''
			    }   ,     )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Trace memory line by line'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Save result to a CSV file'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Save all print statements in a log file'''}    )
			__lowerCamelCase	:       bool							=    field(default=SCREAMING_SNAKE_CASE   ,     metadata={'''help''': '''Whether to print environment information'''}    )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={
			        '''help''': (
			            '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use'''
			            ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled'''
			            ''' for debugging / testing and on TPU.'''
			        )
			    }   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''inference_time_{round(time()    )}.csv'''   ,     metadata={'''help''': '''CSV filename used if saving time results to csv.'''}   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''inference_memory_{round(time()    )}.csv'''   ,     metadata={'''help''': '''CSV filename used if saving memory results to csv.'''}   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''train_time_{round(time()    )}.csv'''   ,     metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''}   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''train_memory_{round(time()    )}.csv'''   ,     metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''}   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''env_info_{round(time()    )}.csv'''   ,     metadata={'''help''': '''CSV filename used if saving environment information.'''}   ,     )
			__lowerCamelCase	:       str							=    field(
			    default=F'''log_{round(time()    )}.csv'''   ,     metadata={'''help''': '''Log filename used if print statements are saved in log.'''}   ,     )
			__lowerCamelCase	:       int							=    field(default=3   ,     metadata={'''help''': '''Times an experiment will be run.'''}    )
			__lowerCamelCase	:       bool							=    field(
			    default=SCREAMING_SNAKE_CASE   ,     metadata={
			        '''help''': (
			            '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain'''
			            ''' model weights.'''
			        )
			    }   ,     )






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







					"""simple docstring"""






					warnings.warn(
					    f'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
					    """ are deprecated in general and it is advised to use external Benchmarking libraries """
					    """ to benchmark Transformer models."""							,	__lowerCAmelCase							,	)






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







					"""simple docstring"""






					return json.dumps(dataclasses.asdict(self   )							,	indent=2   )






			@property
			def    a_       (			self   :    Tuple   )	->	List[str]:







					"""simple docstring"""






					if len(self.models   ) <= 0:
							raise ValueError(
							    """Please make sure you provide at least one model name / model identifier, *e.g.* `--models"""
							    """ bert-base-cased` or `args.models = ['bert-base-cased']."""   )
					return self.models







			@property
			def    a_       (			self   :    Union[str, Any]   )	->	Optional[Any]:







					"""simple docstring"""






					if not self.multi_process:
							return False
					elif self.is_tpu:
							logger.info("""Multiprocessing is currently not possible on TPU."""   )
							return False
					else:
							return True



