





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": 1024,
}

# 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        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







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

 lowercase_		=      []
 lowercase_		=      []

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Optional[Any]	,			UpperCAmelCase_    :       List[Any]=None	,			UpperCAmelCase_    :       Tuple=None	,			UpperCAmelCase_    :       int="<s>"	,			UpperCAmelCase_    :       Dict="</s>"	,			UpperCAmelCase_    :       Any="</s>"	,			UpperCAmelCase_    :       str="<pad>"	,			UpperCAmelCase_    :       Optional[Any]="<unk>"	,			UpperCAmelCase_    :       str="m2m100"	,			UpperCAmelCase_    :       Optional[Dict[str, Any]] = None	,			UpperCAmelCase_    :       List[str]=8	,			**UpperCAmelCase_    :       List[Any]	,			)	->None:



   '''simple docstring'''



   lowerCamelCase__:				Tuple        ={} if sp_model_kwargs is None else sp_model_kwargs

   lowerCamelCase__:				int        =language_codes
   lowerCamelCase__:				Any        =FAIRSEQ_LANGUAGE_CODES[language_codes]
   lowerCamelCase__:				Optional[Any]        ={lang_code: F"""__{lang_code}__""" for lang_code in fairseq_language_code}

   lowerCamelCase__:				str        =kwargs.get("additional_special_tokens"	,			[])
   kwargs["additional_special_tokens"] += [
       self.get_lang_token(UpperCAmelCase_)
       for lang_code in fairseq_language_code
       if self.get_lang_token(UpperCAmelCase_) not in kwargs["additional_special_tokens"]
   ]

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

   lowerCamelCase__:				Optional[Any]        =vocab_file
   lowerCamelCase__:				Any        =load_json(UpperCAmelCase_)
   lowerCamelCase__:				int        ={v: k for k, v in self.encoder.items()}
   lowerCamelCase__:				Optional[int]        =spm_file
   lowerCamelCase__:				int        =load_spm(UpperCAmelCase_	,			self.sp_model_kwargs)

   lowerCamelCase__:				List[Any]        =len(self.encoder)

   lowerCamelCase__:				Tuple        ={
       self.get_lang_token(UpperCAmelCase_): self.encoder_size + i for i, lang_code in enumerate(UpperCAmelCase_)
   }
   lowerCamelCase__:				Optional[int]        ={lang_code: self.encoder_size + i for i, lang_code in enumerate(UpperCAmelCase_)}
   lowerCamelCase__:				List[Any]        ={v: k for k, v in self.lang_token_to_id.items()}

   lowerCamelCase__:				int        =src_lang if src_lang is not None else "en"
   lowerCamelCase__:				List[Any]        =tgt_lang
   lowerCamelCase__:				Union[str, Any]        =self.get_lang_id(self._src_lang)
   self.set_src_lang_special_tokens(self._src_lang)

   lowerCamelCase__:				Tuple        =num_madeup_words

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->int:



   '''simple docstring'''



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

 @property
 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->str:



   '''simple docstring'''



   return self._src_lang

 @src_lang.setter
 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any]	,			UpperCAmelCase_    :       str)	->None:



   '''simple docstring'''



   lowerCamelCase__:				str        =new_src_lang
   self.set_src_lang_special_tokens(self._src_lang)

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       str)	->List[str]:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			UpperCAmelCase_    :       List[str])	->List[Any]:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			UpperCAmelCase_    :       int)	->str:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       List[Any])	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =[]
   lowerCamelCase__:				Dict        =""
   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(UpperCAmelCase_) + token
       lowerCamelCase__:				Union[str, Any]        =[]
     else:
       current_sub_tokens.append(UpperCAmelCase_)
   out_string += self.sp_model.decode(UpperCAmelCase_)
   return out_string.strip()

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       List[int]	,			UpperCAmelCase_    :       Optional[List[int]] = None	,			UpperCAmelCase_    :       bool = False)	->List[int]:



   '''simple docstring'''



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

   lowerCamelCase__:				Any        =[1] * len(self.prefix_tokens)
   lowerCamelCase__:				Union[str, Any]        =[1] * len(self.suffix_tokens)
   if token_ids_a is None:
     return prefix_ones + ([0] * len(UpperCAmelCase_)) + suffix_ones
   return prefix_ones + ([0] * len(UpperCAmelCase_)) + ([0] * len(UpperCAmelCase_)) + suffix_ones

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       List[int]	,			UpperCAmelCase_    :       Optional[List[int]] = None)	->List[int]:



   '''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 							SCREAMING_SNAKE_CASE_ (self    :       Optional[Any])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        ={self.convert_ids_to_tokens(UpperCAmelCase_): i for i in range(self.vocab_size)}
   vocab.update(self.added_tokens_encoder)
   return vocab

 def __getstate__(self    :       List[Any])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =self.__dict__.copy()
   lowerCamelCase__:				Dict        =None
   return state

 def __setstate__(self    :       List[str]	,			UpperCAmelCase_    :       Dict)	->None:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =d

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

   lowerCamelCase__:				Dict        =load_spm(self.spm_file	,			self.sp_model_kwargs)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       Optional[str] = None)	->Tuple[str]:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =Path(UpperCAmelCase_)
   if not save_dir.is_dir():
     raise OSError(F"""{save_directory} should be a directory""")
   lowerCamelCase__:				List[Any]        =save_dir / (
       (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
   )
   lowerCamelCase__:				int        =save_dir / (
       (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
   )

   save_json(self.encoder	,			UpperCAmelCase_)

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

   return (str(UpperCAmelCase_), str(UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       str = "en"	,			UpperCAmelCase_    :       Optional[List[str]] = None	,			UpperCAmelCase_    :       str = "ro"	,			**UpperCAmelCase_    :       List[str]	,			)	->BatchEncoding:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =src_lang
   lowerCamelCase__:				Optional[Any]        =tgt_lang
   self.set_src_lang_special_tokens(self.src_lang)
   return super().prepare_seqaseq_batch(UpperCAmelCase_	,			UpperCAmelCase_	,			**UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Optional[str]	,			UpperCAmelCase_    :       Optional[str]	,			**UpperCAmelCase_    :       Optional[int])	->List[str]:



   '''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")
   lowerCamelCase__:				int        =src_lang
   lowerCamelCase__:				str        =self(UpperCAmelCase_	,			add_special_tokens=UpperCAmelCase_	,			**UpperCAmelCase_)
   lowerCamelCase__:				int        =self.get_lang_id(UpperCAmelCase_)
   lowerCamelCase__:				List[Any]        =tgt_lang_id
   return inputs

 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->Tuple:



   '''simple docstring'''



   self.set_src_lang_special_tokens(self.src_lang)

 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->Optional[int]:



   '''simple docstring'''



   self.set_tgt_lang_special_tokens(self.tgt_lang)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       str)	->None:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =self.get_lang_token(UpperCAmelCase_)
   lowerCamelCase__:				str        =self.lang_token_to_id[lang_token]
   lowerCamelCase__:				str        =[self.cur_lang_id]
   lowerCamelCase__:				Union[str, Any]        =[self.eos_token_id]

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			UpperCAmelCase_    :       str)	->None:



   '''simple docstring'''



   lowerCamelCase__:				Optional[Any]        =self.get_lang_token(UpperCAmelCase_)
   lowerCamelCase__:				Tuple        =self.lang_token_to_id[lang_token]
   lowerCamelCase__:				List[Any]        =[self.cur_lang_id]
   lowerCamelCase__:				Optional[Any]        =[self.eos_token_id]

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       str)	->str:



   '''simple docstring'''



   return self.lang_code_to_token[lang]







 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       str)	->int:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =self.get_lang_token(UpperCAmelCase_)
   return self.lang_token_to_id[lang_token]





def 					lowerCAmelCase_			(	__a     ,   __a		)					->		sentencepiece.SentencePieceProcessor:







  """simple docstring"""





  lowerCamelCase__:				Optional[Any]        =sentencepiece.SentencePieceProcessor(**__a		)
  spm.Load(str(__a		)		)
  return spm





def 					lowerCAmelCase_			(	__a		)					->		Union[Dict, List]:







  """simple docstring"""





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






def 					lowerCAmelCase_			(	__a     ,   __a		)					->		None:







  """simple docstring"""





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








import json
import os
import unittest

from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ,							unittest.TestCase   ):







 '''simple docstring'''
 lowercase_		=      CTRLTokenizer
 lowercase_		=      False
 lowercase_		=      False

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



   '''simple docstring'''



   super().setUp()

   # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
   lowerCamelCase__:				Optional[Any]        =["adapt", "re@@", "a@@", "apt", "c@@", "t", "<unk>"]
   lowerCamelCase__:				Optional[Any]        =dict(zip(UpperCAmelCase_	,			range(len(UpperCAmelCase_))))
   lowerCamelCase__:				Union[str, Any]        =["#version: 0.2", "a p", "ap t</w>", "r e", "a d", "ad apt</w>", ""]
   lowerCamelCase__:				Union[str, Any]        ={"unk_token": "<unk>"}

   lowerCamelCase__:				Union[str, Any]        =os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES["vocab_file"])
   lowerCamelCase__:				Optional[Any]        =os.path.join(self.tmpdirname	,			VOCAB_FILES_NAMES["merges_file"])
   with open(self.vocab_file	,			"w"	,			encoding="utf-8") as fp:
     fp.write(json.dumps(UpperCAmelCase_) + "\n")
   with open(self.merges_file	,			"w"	,			encoding="utf-8") as fp:
     fp.write("\n".join(UpperCAmelCase_))

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			**UpperCAmelCase_    :       str)	->List[Any]:



   '''simple docstring'''



   kwargs.update(self.special_tokens_map)
   return CTRLTokenizer.from_pretrained(self.tmpdirname	,			**UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       Optional[int])	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				int        ="adapt react readapt apt"
   lowerCamelCase__:				int        ="adapt react readapt apt"
   return input_text, output_text







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



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =CTRLTokenizer(self.vocab_file	,			self.merges_file	,			**self.special_tokens_map)
   lowerCamelCase__:				Union[str, Any]        ="adapt react readapt apt"
   lowerCamelCase__:				Tuple        ="adapt re@@ a@@ c@@ t re@@ adapt apt".split()
   lowerCamelCase__:				Dict        =tokenizer.tokenize(UpperCAmelCase_)
   self.assertListEqual(UpperCAmelCase_	,			UpperCAmelCase_)

   lowerCamelCase__:				Optional[int]        =tokens + [tokenizer.unk_token]

   lowerCamelCase__:				List[str]        =[0, 1, 2, 4, 5, 1, 0, 3, 6]
   self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_)	,			UpperCAmelCase_)

