
import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
					from .tokenization_nllb import NllbTokenizer
else:
					SCREAMING_SNAKE_CASE							:List[str]							 =				None


SCREAMING_SNAKE_CASE							:str							 =				logging.get_logger(__name__)


SCREAMING_SNAKE_CASE							:Union[str, Any]							 =				{'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

SCREAMING_SNAKE_CASE							:Dict							 =				{
    'vocab_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'
        ),
    },
}

SCREAMING_SNAKE_CASE							:List[Any]							 =				{
    'facebook/nllb-large-en-ro': 1024,
    'facebook/nllb-200-distilled-600M': 1024,
}

# fmt: off
SCREAMING_SNAKE_CASE							:int							 =				['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn']





class 							UpperCAmelCase      (  __SCREAMING_SNAKE_CASE  ):




	'''simple docstring'''





	snake_case_					    =     VOCAB_FILES_NAMES
	snake_case_					    =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	snake_case_					    =     PRETRAINED_VOCAB_FILES_MAP
	snake_case_					    =     ["input_ids", "attention_mask"]
	snake_case_					    =     NllbTokenizer

	snake_case_					    =     []
	snake_case_					    =     []






	def __init__(       self					: List[str]							,A					: Any=None							,A					: Tuple=None							,A					: Tuple="<s>"							,A					: Any="</s>"							,A					: Dict="</s>"							,A					: Tuple="<s>"							,A					: Any="<unk>"							,A					: Any="<pad>"							,A					: List[Any]="<mask>"							,A					: Optional[Any]=None							,A					: Optional[Any]=None							,A					: Optional[Any]=None							,A					: int=False							,**A					: int							,):
					# Mask token behave like a normal word, i.e. include the space before it
					__A   			= AddedToken(__lowerCamelCase							,lstrip=__lowerCamelCase							,rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase							,__lowerCamelCase ) else mask_token
					__A   			= legacy_behaviour
					super().__init__(
					    vocab_file=__lowerCamelCase							,tokenizer_file=__lowerCamelCase							,bos_token=__lowerCamelCase							,eos_token=__lowerCamelCase							,sep_token=__lowerCamelCase							,cls_token=__lowerCamelCase							,unk_token=__lowerCamelCase							,pad_token=__lowerCamelCase							,mask_token=__lowerCamelCase							,src_lang=__lowerCamelCase							,tgt_lang=__lowerCamelCase							,additional_special_tokens=__lowerCamelCase							,legacy_behaviour=__lowerCamelCase							,**__lowerCamelCase							,)

					__A   			= vocab_file
					__A   			= False if not self.vocab_file else True

					__A   			= FAIRSEQ_LANGUAGE_CODES.copy()

					if additional_special_tokens is not None:
									# Only add those special tokens if they are not already there.
									_additional_special_tokens.extend(
									    [t for t in additional_special_tokens if t not in _additional_special_tokens] )

					self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} )
					__A   			= {
					    lang_code: self.convert_tokens_to_ids(__lowerCamelCase ) for lang_code in FAIRSEQ_LANGUAGE_CODES
					}

					__A   			= src_lang if src_lang is not None else "eng_Latn"
					__A   			= self.convert_tokens_to_ids(self._src_lang )
					__A   			= tgt_lang
					self.set_src_lang_special_tokens(self._src_lang )






	@property
	def 				UpperCamelCase_  (       self					: str ):
					return self._src_lang






	@src_lang.setter
	def 				UpperCamelCase_  (       self					: Tuple							,A					: Optional[Any] ):
					__A   			= new_src_lang
					self.set_src_lang_special_tokens(self._src_lang )






	def 				UpperCamelCase_  (       self					: str							,A					: List[Any]							,A					: Any = None ):
					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 				UpperCamelCase_  (       self					: Tuple							,A					: List[Any]							,A					: Optional[int] = None ):
					__A   			= [self.sep_token_id]
					__A   			= [self.cls_token_id]

					if token_ids_a is None:
									return len(cls + token_ids_a + sep ) * [0]
					return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]






	def 				UpperCamelCase_  (       self					: List[Any]							,A					: List[Any]							,A					: Optional[int]							,A					: Tuple							,A					: List[str]							,**A					: Optional[Any] ):
					if src_lang is None or tgt_lang is None:
									raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
					__A   			= src_lang
					__A   			= self(__lowerCamelCase							,add_special_tokens=__lowerCamelCase							,return_tensors=__lowerCamelCase							,**__lowerCamelCase )
					__A   			= self.convert_tokens_to_ids(__lowerCamelCase )
					__A   			= tgt_lang_id
					return inputs






	def 				UpperCamelCase_  (       self					: Tuple							,A					: List[Any]							,A					: str = "eng_Latn"							,A					: Union[str, Any] = None							,A					: str = "fra_Latn"							,**A					: Dict							,):
					__A   			= src_lang
					__A   			= tgt_lang
					return super().prepare_seqaseq_batch(__lowerCamelCase							,__lowerCamelCase							,**__lowerCamelCase )






	def 				UpperCamelCase_  (       self					: Optional[Any] ):
					return self.set_src_lang_special_tokens(self.src_lang )






	def 				UpperCamelCase_  (       self					: Tuple ):
					return self.set_tgt_lang_special_tokens(self.tgt_lang )






	def 				UpperCamelCase_  (       self					: Optional[int]							,A					: Tuple ):
					__A   			= self.convert_tokens_to_ids(__lowerCamelCase )

					if self.legacy_behaviour:
									__A   			= []
									__A   			= [self.eos_token_id, self.cur_lang_code]
					else:
									__A   			= [self.cur_lang_code]
									__A   			= [self.eos_token_id]

					__A   			= self.convert_ids_to_tokens(self.prefix_tokens )
					__A   			= self.convert_ids_to_tokens(self.suffix_tokens )

					__A   			= processors.TemplateProcessing(
					    single=prefix_tokens_str + ["$A"] + suffix_tokens_str							,pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str							,special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,self.prefix_tokens + self.suffix_tokens ) )							,)






	def 				UpperCamelCase_  (       self					: Dict							,A					: Optional[int] ):
					__A   			= self.convert_tokens_to_ids(__lowerCamelCase )
					if self.legacy_behaviour:
									__A   			= []
									__A   			= [self.eos_token_id, self.cur_lang_code]
					else:
									__A   			= [self.cur_lang_code]
									__A   			= [self.eos_token_id]

					__A   			= self.convert_ids_to_tokens(self.prefix_tokens )
					__A   			= self.convert_ids_to_tokens(self.suffix_tokens )

					__A   			= processors.TemplateProcessing(
					    single=prefix_tokens_str + ["$A"] + suffix_tokens_str							,pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str							,special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,self.prefix_tokens + self.suffix_tokens ) )							,)







	def 				UpperCamelCase_  (       self					: int							,A					: str							,A					: Dict = None ):
					if not self.can_save_slow_tokenizer:
									raise ValueError(
									    "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
									    "tokenizer." )

					if not os.path.isdir(__lowerCamelCase ):
									logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' )
									return
					__A   			= os.path.join(
					    __lowerCamelCase							,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )

					if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ):
									copyfile(self.vocab_file							,__lowerCamelCase )

					return (out_vocab_file,)




import json
import os
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase__      		= logging.get_logger(__name__)


lowerCAmelCase__      		= {
    'vocab_file': 'vocab.json',
    'tokenizer_config_file': 'tokenizer_config.json',
    'merges_file': 'merges.txt',
}

lowerCAmelCase__      		= {
    'vocab_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json'
        ),
    },
    'tokenizer_config_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json'
        ),
    },
    'merges_file': {
        'facebook/s2t-wav2vec2-large-en-de': (
            'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt'
        ),
    },
}

lowerCAmelCase__      		= '</w>'
lowerCAmelCase__      		= '@@ '
def 							_UpperCAmelCase				(UpperCamelCase__     :  Optional[Any]						):
       _A      :       Optional[int]				    = set()
       _A      :       Optional[Any]				    = word[0]
       for char in word[1:]:
              pairs.add((prev_char, char)						)
              _A      :       List[Any]				    = char
       return pairs


# Speech2Text2 has no max input length
lowerCAmelCase__      		= {'facebook/s2t-wav2vec2-large-en-de': 10_24}







class      lowerCAmelCase__       (				a):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE  			= VOCAB_FILES_NAMES
     __SCREAMING_SNAKE_CASE  			= PRETRAINED_VOCAB_FILES_MAP
     __SCREAMING_SNAKE_CASE  			= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __SCREAMING_SNAKE_CASE  			= ["input_ids", "attention_mask"]


     def __init__(						self ,						__lowerCamelCase ,						__lowerCamelCase="<s>" ,						__lowerCamelCase="<pad>" ,						__lowerCamelCase="</s>" ,						__lowerCamelCase="<unk>" ,						__lowerCamelCase=False ,						__lowerCamelCase=None ,						**__lowerCamelCase ,						)			->				Optional[Any]:
            super().__init__(
                unk_token=__lowerCamelCase ,						bos_token=__lowerCamelCase ,						eos_token=__lowerCamelCase ,						pad_token=__lowerCamelCase ,						do_lower_case=__lowerCamelCase ,						**__lowerCamelCase ,						)

            _A      :       Dict				    = do_lower_case

            with open(__lowerCamelCase ,						encoding="utf-8") as vocab_handle:
                   _A      :       Optional[int]				    = json.load(__lowerCamelCase)
            _A      :       Optional[Any]				    = {v: k for k, v in self.encoder.items()}

            if merges_file is None:
                   logger.info(F"No merges files provided. {self.__class__.__name__} can only be used for decoding.")

                   _A      :       Optional[Any]				    = None
                   _A      :       Tuple				    = None
            else:
                   with open(__lowerCamelCase ,						encoding="utf-8") as merges_handle:
                          _A      :       Optional[int]				    = merges_handle.read().split("\n")[:-1]

                   _A      :       Union[str, Any]				    = [tuple(merge.split()[:2]) for merge in merges]
                   _A      :       Optional[int]				    = dict(zip(__lowerCamelCase ,						range(len(__lowerCamelCase))))
                   _A      :       List[Any]				    = {}


     @property
     def  _lowerCamelCase (						self)			->				int:
            return len(self.decoder)


     def  _lowerCamelCase (						self)			->				Dict:
            return dict(self.encoder ,						**self.added_tokens_encoder)


     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				Dict:
            _A      :       Tuple				    = tuple(token[:-1]) + (token[-1] + BPE_TOKEN_MERGES,)
            if token in self.cache:
                   return self.cache[token]
            _A      :       int				    = get_pairs(__lowerCamelCase)

            if not pairs:
                   return token

            while True:
                   _A      :       Any				    = min(__lowerCamelCase ,						key=lambda __lowerCamelCase: self.bpe_ranks.get(__lowerCamelCase ,						float("inf")))
                   if bigram not in self.bpe_ranks:
                          break
                   _A    ,			_A      :       Optional[int]				    = bigram
                   _A      :       int				    = []
                   _A      :       str				    = 0
                   while i < len(__lowerCamelCase):
                          try:
                                 _A      :       str				    = word.index(__lowerCamelCase ,						__lowerCamelCase)
                          except ValueError:
                                 new_word.extend(word[i:])
                                 break
                          else:
                                 new_word.extend(word[i:j])
                                 _A      :       str				    = j

                          if word[i] == first and i < len(__lowerCamelCase) - 1 and word[i + 1] == second:
                                 new_word.append(first + second)
                                 i += 2
                          else:
                                 new_word.append(word[i])
                                 i += 1
                   _A      :       List[str]				    = tuple(__lowerCamelCase)
                   _A      :       List[str]				    = new_word
                   if len(__lowerCamelCase) == 1:
                          break
                   else:
                          _A      :       List[Any]				    = get_pairs(__lowerCamelCase)
            _A      :       Tuple				    = " ".join(__lowerCamelCase)
            if word == "\n  " + BPE_TOKEN_MERGES:
                   _A      :       List[str]				    = "\n" + BPE_TOKEN_MERGES

            if word.endswith(__lowerCamelCase):
                   _A      :       int				    = word.replace(__lowerCamelCase ,						"")

            _A      :       int				    = word.replace(" " ,						__lowerCamelCase)
            _A      :       Union[str, Any]				    = word
            return word


     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				Optional[Any]:

            if self.bpe_ranks is None:
                   raise ValueError(
                       "This tokenizer was instantiated without a `merges.txt` file, so"
                       " that it can only be used for decoding, not for encoding."
                       "Make sure to provide `merges.txt` file at instantiation to enable "
                       "encoding.")

            if self.do_lower_case:
                   _A      :       List[Any]				    = text.lower()

            _A      :       Optional[int]				    = text.split()

            _A      :       List[str]				    = []
            for token in text:
                   if token:
                          split_tokens.extend(list(self.bpe(__lowerCamelCase).split(" ")))

            return split_tokens


     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				int:
            return self.encoder.get(__lowerCamelCase ,						self.encoder.get(self.unk_token))


     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				str:
            _A      :       List[str]				    = self.decoder.get(__lowerCamelCase ,						self.unk_token)
            return result


     def  _lowerCamelCase (						self ,						__lowerCamelCase)			->				str:
            _A      :       str				    = " ".join(__lowerCamelCase)

            # make sure @@ tokens are concatenated
            _A      :       int				    = "".join(string.split(__lowerCamelCase))

            return string


     def  _lowerCamelCase (						self ,						__lowerCamelCase ,						__lowerCamelCase = None)			->				Tuple[str]:
            if not os.path.isdir(__lowerCamelCase):
                   logger.error(F"Vocabulary path ({save_directory}) should be a directory")
                   return
            _A      :       Any				    = os.path.join(
                __lowerCamelCase ,						(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"])
            _A      :       Any				    = os.path.join(
                __lowerCamelCase ,						(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"])

            with open(__lowerCamelCase ,						"w" ,						encoding="utf-8") as f:
                   f.write(json.dumps(self.encoder ,						indent=2 ,						sort_keys=__lowerCamelCase ,						ensure_ascii=__lowerCamelCase) + "\n")

            _A      :       Union[str, Any]				    = 0
            if self.bpe_ranks is None:
                   return (vocab_file,)

            with open(__lowerCamelCase ,						"w" ,						encoding="utf-8") as writer:
                   for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,						key=lambda __lowerCamelCase: kv[1]):
                          if index != token_index:
                                 logger.warning(
                                     F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
                                     " Please check that the tokenizer is not corrupted!")
                                 _A      :       Optional[int]				    = token_index
                          writer.write(" ".join(__lowerCamelCase) + "\n")
                          index += 1

            return (vocab_file, merges_file)
