





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_mbart import MBartTokenizer
else:
      __UpperCAmelCase	:       Optional[int]    	=							None


__UpperCAmelCase	:       Dict    	=							logging.get_logger(__name__)


__UpperCAmelCase	:       List[Any]    	=							{"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}

__UpperCAmelCase	:       Tuple    	=							{
    "vocab_file": {
        "facebook/mbart-large-en-ro": (
            "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
        ),
        "facebook/mbart-large-cc25": (
            "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
        ),
    },
    "tokenizer_file": {
        "facebook/mbart-large-en-ro": "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json",
        "facebook/mbart-large-cc25": "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json",
    },
}

__UpperCAmelCase	:       List[str]    	=							{
    "facebook/mbart-large-en-ro": 1_024,
    "facebook/mbart-large-cc25": 1_024,
}

# fmt: off
__UpperCAmelCase	:       Dict    	=							["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]







class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					VOCAB_FILES_NAMES
       lowerCAmelCase__						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase__						=					PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase__						=					["""input_ids""", """attention_mask"""]
       lowerCAmelCase__						=					MBartTokenizer

       lowerCAmelCase__						=					[]
       lowerCAmelCase__						=					[]




       def __init__(  self			:   Dict							,    A			:   Optional[int]=None							,    A			:   Optional[Any]=None							,    A			:   Tuple="<s>"							,    A			:   Tuple="</s>"							,    A			:   Optional[int]="</s>"							,    A			:   List[Any]="<s>"							,    A			:   Tuple="<unk>"							,    A			:   Tuple="<pad>"							,    A			:   List[str]="<mask>"							,    A			:   int=None							,    A			:   Tuple=None							,    A			:   Any=None							,    **A			:   Union[str, Any]							,    ):
         # Mask token behave like a normal word, i.e. include the space before it
         __snake_case:						Optional[int]			  =						AddedToken(A							,    lstrip=A							,    rstrip=A		) if isinstance(A							,    A		) else mask_token

         super().__init__(
             vocab_file=A							,    tokenizer_file=A							,    bos_token=A							,    eos_token=A							,    sep_token=A							,    cls_token=A							,    unk_token=A							,    pad_token=A							,    mask_token=A							,    src_lang=A							,    tgt_lang=A							,    additional_special_tokens=A							,    **A							,    )

         __snake_case:						Tuple			  =						vocab_file
         __snake_case:						Optional[Any]			  =						False if not self.vocab_file else True

         __snake_case:						Any			  =						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}		)
         __snake_case:						Tuple			  =						{
             lang_code: self.convert_tokens_to_ids(A		) for lang_code in FAIRSEQ_LANGUAGE_CODES
         }

         __snake_case:						Dict			  =						src_lang if src_lang is not None else """en_XX"""
         __snake_case:						List[str]			  =						self.convert_tokens_to_ids(self._src_lang		)
         __snake_case:						Any			  =						tgt_lang
         self.set_src_lang_special_tokens(self._src_lang		)




       @property
       def 							UpperCAmelCase__			(  self			:   Tuple		):
         return self._src_lang




       @src_lang.setter
       def 							UpperCAmelCase__			(  self			:   int							,    A			:   str		):
         __snake_case:						Dict			  =						new_src_lang
         self.set_src_lang_special_tokens(self._src_lang		)




       def 							UpperCAmelCase__			(  self			:   str							,    A			:   List[int]							,    A			:   Optional[List[int]] = 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			:   Optional[int]							,    A			:   List[int]							,    A			:   Optional[List[int]] = None		):
         __snake_case:						Any			  =						[self.sep_token_id]
         __snake_case:						Any			  =						[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			:   Optional[Any]							,    A			:   str							,    A			:   Optional[str]							,    A			:   Optional[str]							,    **A			:   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"""		)
         __snake_case:						str			  =						src_lang
         __snake_case:						Optional[Any]			  =						self(A							,    add_special_tokens=A							,    return_tensors=A							,    **A		)
         __snake_case:						List[Any]			  =						self.convert_tokens_to_ids(A		)
         __snake_case:						str			  =						tgt_lang_id
         return inputs




       def 							UpperCAmelCase__			(  self			:   Optional[int]							,    A			:   List[str]							,    A			:   str = "en_XX"							,    A			:   Optional[List[str]] = None							,    A			:   str = "ro_RO"							,    **A			:   Tuple							,    ):
         __snake_case:						str			  =						src_lang
         __snake_case:						List[str]			  =						tgt_lang
         return super().prepare_seqaseq_batch(A							,    A							,    **A		)




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         return self.set_src_lang_special_tokens(self.src_lang		)




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         return self.set_tgt_lang_special_tokens(self.tgt_lang		)




       def 							UpperCAmelCase__			(  self			:   str							,    A			:   List[str]		):
         __snake_case:						int			  =						self.convert_tokens_to_ids(A		)
         __snake_case:						List[Any]			  =						[]
         __snake_case:						str			  =						[self.eos_token_id, self.cur_lang_code]

         __snake_case:						Any			  =						self.convert_ids_to_tokens(self.prefix_tokens		)
         __snake_case:						Dict			  =						self.convert_ids_to_tokens(self.suffix_tokens		)

         __snake_case:						Any			  =						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			:   str		):
         __snake_case:						Any			  =						self.convert_tokens_to_ids(A		)
         __snake_case:						List[str]			  =						[]
         __snake_case:						Optional[int]			  =						[self.eos_token_id, self.cur_lang_code]

         __snake_case:						int			  =						self.convert_ids_to_tokens(self.prefix_tokens		)
         __snake_case:						List[Any]			  =						self.convert_ids_to_tokens(self.suffix_tokens		)

         __snake_case:						Any			  =						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			:   str							,    A			:   Optional[str] = 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(A		):
           logger.error(f'''Vocabulary path ({save_directory}) should be a directory.'''		)
           return
         __snake_case:						Optional[int]			  =						os.path.join(
             A							,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]		)

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

         return (out_vocab_file,)













import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase	:       Optional[Any]    	=							logging.get_logger(__name__)

__UpperCAmelCase	:       Union[str, Any]    	=							{
    "asapp/sew-d-tiny-100k": "https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}







class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					"""sew-d"""




       def __init__(  self			:   Dict							,    A			:   Any=32							,    A			:   Dict=768							,    A			:   Optional[Any]=12							,    A			:   Union[str, Any]=12							,    A			:   Union[str, Any]=3_072							,    A			:   Optional[Any]=2							,    A			:   Union[str, Any]=512							,    A			:   List[Any]=256							,    A			:   Dict=True							,    A			:   Union[str, Any]=True							,    A			:   Optional[int]=("p2c", "c2p")							,    A			:   str="layer_norm"							,    A			:   Dict="gelu_python"							,    A			:   Tuple=0.1							,    A			:   Any=0.1							,    A			:   Tuple=0.1							,    A			:   Optional[int]=0.0							,    A			:   Any=0.1							,    A			:   Any=0.02							,    A			:   Dict=1E-7							,    A			:   str=1E-5							,    A			:   int="group"							,    A			:   int="gelu"							,    A			:   str=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)							,    A			:   Union[str, Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)							,    A			:   List[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)							,    A			:   Optional[int]=False							,    A			:   int=128							,    A			:   int=16							,    A			:   Optional[Any]=True							,    A			:   List[Any]=0.05							,    A			:   Any=10							,    A			:   Dict=2							,    A			:   List[Any]=0.0							,    A			:   Union[str, Any]=10							,    A			:   int=0							,    A			:   List[Any]="mean"							,    A			:   Union[str, Any]=False							,    A			:   Any=False							,    A			:   Optional[int]=256							,    A			:   List[Any]=0							,    A			:   Any=1							,    A			:   List[Any]=2							,    **A			:   List[Any]							,    ):
         super().__init__(**A							,    pad_token_id=A							,    bos_token_id=A							,    eos_token_id=A		)
         __snake_case:						Optional[int]			  =						hidden_size
         __snake_case:						str			  =						feat_extract_norm
         __snake_case:						int			  =						feat_extract_activation
         __snake_case:						str			  =						list(A		)
         __snake_case:						Any			  =						list(A		)
         __snake_case:						str			  =						list(A		)
         __snake_case:						Union[str, Any]			  =						conv_bias
         __snake_case:						int			  =						num_conv_pos_embeddings
         __snake_case:						str			  =						num_conv_pos_embedding_groups
         __snake_case:						List[Any]			  =						len(self.conv_dim		)
         __snake_case:						List[str]			  =						num_hidden_layers
         __snake_case:						Union[str, Any]			  =						intermediate_size
         __snake_case:						Dict			  =						squeeze_factor
         __snake_case:						List[Any]			  =						max_position_embeddings
         __snake_case:						List[Any]			  =						position_buckets
         __snake_case:						List[str]			  =						share_att_key
         __snake_case:						int			  =						relative_attention
         __snake_case:						Union[str, Any]			  =						norm_rel_ebd
         __snake_case:						List[str]			  =						list(A		)
         __snake_case:						Tuple			  =						hidden_act
         __snake_case:						List[Any]			  =						num_attention_heads
         __snake_case:						str			  =						hidden_dropout
         __snake_case:						int			  =						attention_dropout
         __snake_case:						Dict			  =						activation_dropout
         __snake_case:						Any			  =						feat_proj_dropout
         __snake_case:						int			  =						final_dropout
         __snake_case:						List[Any]			  =						layer_norm_eps
         __snake_case:						List[str]			  =						feature_layer_norm_eps
         __snake_case:						List[Any]			  =						initializer_range
         __snake_case:						List[Any]			  =						vocab_size

         if (
             (len(self.conv_stride		) != self.num_feat_extract_layers)
             or (len(self.conv_kernel		) != self.num_feat_extract_layers)
             or (len(self.conv_dim		) != self.num_feat_extract_layers)
         ):
           raise ValueError(
               """Configuration for convolutional layers is incorrect."""
               """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
               f'''but is `len(config.conv_dim) = {len(self.conv_dim		)}`, `len(config.conv_stride)'''
               f'''= {len(self.conv_stride		)}`, `len(config.conv_kernel) = {len(self.conv_kernel		)}`.'''		)

         # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
         __snake_case:						List[Any]			  =						apply_spec_augment
         __snake_case:						List[Any]			  =						mask_time_prob
         __snake_case:						str			  =						mask_time_length
         __snake_case:						List[str]			  =						mask_time_min_masks
         __snake_case:						str			  =						mask_feature_prob
         __snake_case:						Optional[int]			  =						mask_feature_length
         __snake_case:						Dict			  =						mask_feature_min_masks

         # ctc loss
         __snake_case:						Any			  =						ctc_loss_reduction
         __snake_case:						str			  =						ctc_zero_infinity

         # sequence classification
         __snake_case:						Optional[Any]			  =						use_weighted_layer_sum
         __snake_case:						List[Any]			  =						classifier_proj_size






       @property
       def 							UpperCAmelCase__			(  self			:   int		):
         return functools.reduce(operator.mul							,    self.conv_stride							,    1		)






