




'''simple docstring'''


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 PreTrainedTokenizer
from ...utils import logging


_lowercase  =			logging.get_logger(__name__)

_lowercase  =			"""▁"""

_lowercase  =			{
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
}

_lowercase  =			{
    """vocab_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
        ),
    },
    """spm_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
        )
    },
}

_lowercase  =			{
    """facebook/s2t-small-librispeech-asr""": 10_24,
}

_lowercase  =			["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]

_lowercase  =			{"""mustc""": MUSTC_LANGS}
class 						a_				(			UpperCAmelCase__						):
	lowercase_       :     List[str]			  =      VOCAB_FILES_NAMES
	lowercase_       :     int			  =      PRETRAINED_VOCAB_FILES_MAP
	lowercase_       :     int			  =      MAX_MODEL_INPUT_SIZES
	lowercase_       :     Optional[int]			  =      ['''input_ids''', '''attention_mask''']

	lowercase_       :     List[int]			  =      []




	def __init__(       self     :  Optional[Any]       ,		__lowerCAmelCase     :  List[Any]       ,		__lowerCAmelCase     :  Optional[int]       ,		__lowerCAmelCase     :  Tuple="<s>"       ,		__lowerCAmelCase     :  List[Any]="</s>"       ,		__lowerCAmelCase     :  Optional[Any]="<pad>"       ,		__lowerCAmelCase     :  Optional[int]="<unk>"       ,		__lowerCAmelCase     :  Tuple=False       ,		__lowerCAmelCase     :  int=False       ,		__lowerCAmelCase     :  Optional[Any]=None       ,		__lowerCAmelCase     :  Optional[Any]=None       ,		__lowerCAmelCase     :  Optional[Dict[str, Any]] = None       ,		**__lowerCAmelCase     :  Union[str, Any]       ,		):
							__snake_case						 =   {} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    bos_token=__lowerCAmelCase       ,		eos_token=__lowerCAmelCase       ,		unk_token=__lowerCAmelCase       ,		pad_token=__lowerCAmelCase       ,		do_upper_case=__lowerCAmelCase       ,		do_lower_case=__lowerCAmelCase       ,		tgt_lang=__lowerCAmelCase       ,		lang_codes=__lowerCAmelCase       ,		sp_model_kwargs=self.sp_model_kwargs       ,		**__lowerCAmelCase       ,		)
							__snake_case						 =   do_upper_case
							__snake_case						 =   do_lower_case

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

							if lang_codes is not None:
													__snake_case						 =   lang_codes
													__snake_case						 =   LANGUAGES[lang_codes]
													__snake_case						 =   [F'<lang:{lang}>' for lang in self.langs]
													__snake_case						 =   {lang: self.sp_model.PieceToId(F'<lang:{lang}>'      ) for lang in self.langs}

													__snake_case						 =   self.lang_tokens
													__snake_case						 =   tgt_lang if tgt_lang is not None else self.langs[0]

													self.set_tgt_lang_special_tokens(self._tgt_lang      )
							else:
													__snake_case						 =   {}




	@property
	def   lowercase__   (       self     :  List[Any]      ):
							return len(self.encoder      )




	@property
	def   lowercase__   (       self     :  int      ):
							return self._tgt_lang




	@tgt_lang.setter
	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  Dict      ):
							__snake_case						 =   new_tgt_lang
							self.set_tgt_lang_special_tokens(__lowerCAmelCase      )




	def   lowercase__   (       self     :  Dict       ,		__lowerCAmelCase     :  str      ):
							__snake_case						 =   self.lang_code_to_id[tgt_lang]
							__snake_case						 =   [lang_code_id]




	def   lowercase__   (       self     :  Tuple       ,		__lowerCAmelCase     :  str      ):
							return self.sp_model.encode(__lowerCAmelCase       ,		out_type=__lowerCAmelCase      )




	def   lowercase__   (       self     :  Optional[Any]       ,		__lowerCAmelCase     :  Optional[Any]      ):
							return self.encoder.get(__lowerCAmelCase       ,		self.encoder[self.unk_token]      )




	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  int      ):
							return self.decoder.get(__lowerCAmelCase       ,		self.unk_token      )




	def   lowercase__   (       self     :  Tuple       ,		__lowerCAmelCase     :  List[str]      ):
							__snake_case						 =   []
							__snake_case						 =   ''
							for token in tokens:
													# make sure that special tokens are not decoded using sentencepiece model
													if token in self.all_special_tokens:
																			__snake_case						 =   self.sp_model.decode(__lowerCAmelCase      )
																			out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
																			__snake_case						 =   []
													else:
																			current_sub_tokens.append(__lowerCAmelCase      )
							__snake_case						 =   self.sp_model.decode(__lowerCAmelCase      )
							out_string += decoded.upper() if self.do_upper_case else decoded
							return out_string.strip()




	def   lowercase__   (       self     :  Optional[Any]       ,		__lowerCAmelCase     :  Optional[Any]       ,		__lowerCAmelCase     :  List[str]=None      ):
							if token_ids_a is None:
													return self.prefix_tokens + token_ids_a + [self.eos_token_id]
							# 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.eos_token_id]




	def   lowercase__   (       self     :  Optional[Any]       ,		__lowerCAmelCase     :  List[int]       ,		__lowerCAmelCase     :  Optional[List[int]] = None       ,		__lowerCAmelCase     :  bool = False      ):

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

							__snake_case						 =   [1] * len(self.prefix_tokens      )
							__snake_case						 =   [1]
							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   lowercase__   (       self     :  Dict      ):
							__snake_case						 =   self.encoder.copy()
							vocab.update(self.added_tokens_encoder      )
							return vocab




	def __getstate__(       self     :  Tuple      ):
							__snake_case						 =   self.__dict__.copy()
							__snake_case						 =   None
							return state




	def __setstate__(       self     :  Union[str, Any]       ,		__lowerCAmelCase     :  Dict      ):
							__snake_case						 =   d

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

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




	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  str       ,		__lowerCAmelCase     :  Optional[str] = None      ):
							__snake_case						 =   Path(__lowerCAmelCase      )
							assert save_dir.is_dir(), F'{save_directory} should be a directory'
							__snake_case						 =   save_dir / (
							    (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file']
							)
							__snake_case						 =   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:
																			__snake_case						 =   self.sp_model.serialized_model_proto()
																			fi.write(__lowerCAmelCase      )

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





def 						lowerCamelCase__   (				a    ,	a							):
						__snake_case						 =   sentencepiece.SentencePieceProcessor(**a							)
						spm.Load(str(a							)							)
						return spm
def 						lowerCamelCase__   (				a							):
						with open(a    ,	'r'							) as f:
												return json.load(a							)






def 						lowerCamelCase__   (				a    ,	a							):
						with open(a    ,	'w'							) as f:
												json.dump(a    ,	a    ,	indent=2							)







'''simple docstring'''


import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_electra import ElectraTokenizer


_lowercase  =			{"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

_lowercase  =			{
    """vocab_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-generator""": """https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt""",
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """google/electra-small-generator""": (
            """https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-generator""": (
            """https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-generator""": (
            """https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json"""
        ),
        """google/electra-small-discriminator""": (
            """https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-base-discriminator""": (
            """https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json"""
        ),
        """google/electra-large-discriminator""": (
            """https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json"""
        ),
    },
}

_lowercase  =			{
    """google/electra-small-generator""": 5_12,
    """google/electra-base-generator""": 5_12,
    """google/electra-large-generator""": 5_12,
    """google/electra-small-discriminator""": 5_12,
    """google/electra-base-discriminator""": 5_12,
    """google/electra-large-discriminator""": 5_12,
}

_lowercase  =			{
    """google/electra-small-generator""": {"""do_lower_case""": True},
    """google/electra-base-generator""": {"""do_lower_case""": True},
    """google/electra-large-generator""": {"""do_lower_case""": True},
    """google/electra-small-discriminator""": {"""do_lower_case""": True},
    """google/electra-base-discriminator""": {"""do_lower_case""": True},
    """google/electra-large-discriminator""": {"""do_lower_case""": True},
}
class 						a_				(			UpperCAmelCase__						):
	lowercase_       :     Tuple			  =      VOCAB_FILES_NAMES
	lowercase_       :     Optional[int]			  =      PRETRAINED_VOCAB_FILES_MAP
	lowercase_       :     int			  =      PRETRAINED_INIT_CONFIGURATION
	lowercase_       :     str			  =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowercase_       :     List[Any]			  =      ElectraTokenizer




	def __init__(       self     :  Optional[Any]       ,		__lowerCAmelCase     :  Optional[Any]=None       ,		__lowerCAmelCase     :  str=None       ,		__lowerCAmelCase     :  Union[str, Any]=True       ,		__lowerCAmelCase     :  int="[UNK]"       ,		__lowerCAmelCase     :  str="[SEP]"       ,		__lowerCAmelCase     :  Optional[Any]="[PAD]"       ,		__lowerCAmelCase     :  Optional[Any]="[CLS]"       ,		__lowerCAmelCase     :  str="[MASK]"       ,		__lowerCAmelCase     :  List[Any]=True       ,		__lowerCAmelCase     :  Optional[int]=None       ,		**__lowerCAmelCase     :  List[Any]       ,		):
							super().__init__(
							    __lowerCAmelCase       ,		tokenizer_file=__lowerCAmelCase       ,		do_lower_case=__lowerCAmelCase       ,		unk_token=__lowerCAmelCase       ,		sep_token=__lowerCAmelCase       ,		pad_token=__lowerCAmelCase       ,		cls_token=__lowerCAmelCase       ,		mask_token=__lowerCAmelCase       ,		tokenize_chinese_chars=__lowerCAmelCase       ,		strip_accents=__lowerCAmelCase       ,		**__lowerCAmelCase       ,		)

							__snake_case						 =   json.loads(self.backend_tokenizer.normalizer.__getstate__()      )
							if (
							    normalizer_state.get('lowercase'       ,		__lowerCAmelCase      ) != do_lower_case
							    or normalizer_state.get('strip_accents'       ,		__lowerCAmelCase      ) != strip_accents
							    or normalizer_state.get('handle_chinese_chars'       ,		__lowerCAmelCase      ) != tokenize_chinese_chars
							):
													__snake_case						 =   getattr(__lowerCAmelCase       ,		normalizer_state.pop('type'      )      )
													__snake_case						 =   do_lower_case
													__snake_case						 =   strip_accents
													__snake_case						 =   tokenize_chinese_chars
													__snake_case						 =   normalizer_class(**__lowerCAmelCase      )

							__snake_case						 =   do_lower_case




	def   lowercase__   (       self     :  Union[str, Any]       ,		__lowerCAmelCase     :  str       ,		__lowerCAmelCase     :  Tuple=None      ):
							__snake_case						 =   [self.cls_token_id] + token_ids_a + [self.sep_token_id]

							if token_ids_a:
													output += token_ids_a + [self.sep_token_id]

							return output




	def   lowercase__   (       self     :  Any       ,		__lowerCAmelCase     :  List[int]       ,		__lowerCAmelCase     :  Optional[List[int]] = None      ):
							__snake_case						 =   [self.sep_token_id]
							__snake_case						 =   [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      ) * [0] + len(token_ids_a + sep      ) * [1]




	def   lowercase__   (       self     :  List[Any]       ,		__lowerCAmelCase     :  str       ,		__lowerCAmelCase     :  Optional[str] = None      ):
							__snake_case						 =   self._tokenizer.model.save(__lowerCAmelCase       ,		name=__lowerCAmelCase      )
							return tuple(__lowerCAmelCase      )

