'''simple docstring'''




import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
__UpperCAmelCase  							=logging.getLogger(__name__)

__UpperCAmelCase  							=int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

__UpperCAmelCase  							={
    "gpt2": (GPTaLMHeadModel, GPTaTokenizer),
    "ctrl": (CTRLLMHeadModel, CTRLTokenizer),
    "openai-gpt": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    "xlnet": (XLNetLMHeadModel, XLNetTokenizer),
    "transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    "xlm": (XLMWithLMHeadModel, XLMTokenizer),
    "gptj": (GPTJForCausalLM, AutoTokenizer),
    "bloom": (BloomForCausalLM, BloomTokenizerFast),
    "llama": (LlamaForCausalLM, LlamaTokenizer),
    "opt": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
__UpperCAmelCase  							="In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>"






def __lowerCAmelCase				(							UpperCamelCase__       )			->					Tuple:
    np.random.seed(args.seed       )
    torch.manual_seed(args.seed       )
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed       )






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					Optional[int]:
    if args.temperature > 0.7:
        logger.info('''CTRL typically works better with lower temperatures (and lower top_k).'''       )

    __lowerCamelCase						=						tokenizer.encode(UpperCamelCase__       ,						add_special_tokens=UpperCamelCase__       )
    if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()       ):
        logger.info('''WARNING! You are not starting your generation from a control code so you won\'t get good results'''       )
    return prompt_text






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					Optional[int]:
    # kwargs = {"language": None, "mask_token_id": None}

    # Set the language
    __lowerCamelCase						=						hasattr(model.config       ,						'''use_lang_emb'''       ) and model.config.use_lang_emb
    if hasattr(model.config       ,						'''lang2id'''       ) and use_lang_emb:
        __lowerCamelCase						=						model.config.langaid.keys()
        if args.xlm_language in available_languages:
            __lowerCamelCase						=						args.xlm_language
        else:
            __lowerCamelCase						=						None
            while language not in available_languages:
                __lowerCamelCase						=						input('''Using XLM. Select language in ''' + str(list(UpperCamelCase__       )       ) + ''' >>> '''       )

        __lowerCamelCase						=						model.config.langaid[language]
        # kwargs["language"] = tokenizer.lang2id[language]

    # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
    # XLM masked-language modeling (MLM) models need masked token
    # is_xlm_mlm = "mlm" in args.model_name_or_path
    # if is_xlm_mlm:
    #     kwargs["mask_token_id"] = tokenizer.mask_token_id

    return prompt_text






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					str:
    __lowerCamelCase						=						args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
    __lowerCamelCase						=						prefix + prompt_text
    return prompt_text






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					Optional[int]:
    __lowerCamelCase						=						args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
    __lowerCamelCase						=						prefix + prompt_text
    return prompt_text


__UpperCAmelCase  							={
    "ctrl": prepare_ctrl_input,
    "xlm": prepare_xlm_input,
    "xlnet": prepare_xlnet_input,
    "transfo-xl": prepare_transfoxl_input,
}






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					Tuple:
    if length < 0 and max_sequence_length > 0:
        __lowerCamelCase						=						max_sequence_length
    elif 0 < max_sequence_length < length:
        __lowerCamelCase						=						max_sequence_length  # No generation bigger than model size
    elif length < 0:
        __lowerCamelCase						=						MAX_LENGTH  # avoid infinite loop
    return length






def __lowerCAmelCase				(							UpperCamelCase__       )			->					List[Any]:
    __lowerCamelCase						=						None
    if hasattr(UpperCamelCase__       ,						'''hidden_size'''       ):
        __lowerCamelCase						=						model_config.hidden_size
    elif hasattr(UpperCamelCase__       ,						'''n_embed'''       ):
        __lowerCamelCase						=						model_config.n_embed
    elif hasattr(UpperCamelCase__       ,						'''n_embd'''       ):
        __lowerCamelCase						=						model_config.n_embd

    __lowerCamelCase						=						None
    if hasattr(UpperCamelCase__       ,						'''num_attention_heads'''       ):
        __lowerCamelCase						=						model_config.num_attention_heads
    elif hasattr(UpperCamelCase__       ,						'''n_head'''       ):
        __lowerCamelCase						=						model_config.n_head

    if embedding_size is None or num_head is None or num_head == 0:
        raise ValueError('''Check the model config'''       )

    __lowerCamelCase						=						int(embedding_size / num_head       )
    if hasattr(UpperCamelCase__       ,						'''n_layer'''       ):
        __lowerCamelCase						=						model_config.n_layer
    elif hasattr(UpperCamelCase__       ,						'''num_hidden_layers'''       ):
        __lowerCamelCase						=						model_config.num_hidden_layers
    else:
        raise ValueError('''Number of hidden layers couldn\'t be determined from the model config'''       )

    return num_layer, num_head, num_embedding_size_per_head






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					Union[str, Any]:
    __lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase						=						sparse_model_config(model.config       )
    if model.config.model_type == "bloom":
        __lowerCamelCase						=						tuple(
            (
                torch.empty(int(num_attention_heads * batch_size       )       ,						UpperCamelCase__       ,						UpperCamelCase__       )
                .to(model.dtype       )
                .to(model.device       ),
                torch.empty(int(num_attention_heads * batch_size       )       ,						UpperCamelCase__       ,						UpperCamelCase__       )
                .to(model.dtype       )
                .to(model.device       ),
            )
            for _ in range(UpperCamelCase__       )       )
    else:
        __lowerCamelCase						=						tuple(
            (
                torch.empty(UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )
                .to(model.dtype       )
                .to(model.device       ),
                torch.empty(UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )
                .to(model.dtype       )
                .to(model.device       ),
            )
            for _ in range(UpperCamelCase__       )       )
    return past_key_values






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					str:
    __lowerCamelCase						=						len(UpperCamelCase__       )
    __lowerCamelCase						=						tokenizer.batch_encode_plus(UpperCamelCase__       ,						return_tensors='''pt'''       )
    __lowerCamelCase						=						dummy_input.to(model.device       )
    if model.config.use_cache:
        __lowerCamelCase						=						generate_past_key_values(UpperCamelCase__       ,						UpperCamelCase__       ,						1       )
    __lowerCamelCase						=						torch.cat(
        [
            torch.zeros(dummy_input['''attention_mask'''].shape[0]       ,						1       )
            .to(dummy_input['''attention_mask'''].dtype       )
            .to(model.device       ),
            dummy_input['''attention_mask'''],
        ]       ,						-1       ,						)
    return dummy_input




class 					a__   (     UpperCAmelCase__				):
     lowerCamelCase						:  Tuple							=("_optimized", "_default")






     def __init__(				self	:	Tuple						,       a	:	str						,       a	:	int					):





         """simple docstring"""



         __lowerCamelCase						=						optimized
         __lowerCamelCase						=						default






     def __call__(				self	:	Union[str, Any]						,       *a	:	int						,       **a	:	Optional[Any]					):





         """simple docstring"""



         if kwargs["past_key_values"] is None and self._default.config.use_cache:
             __lowerCamelCase						=						generate_past_key_values(self._default						,       kwargs['''input_ids'''].shape[0]						,       0					)
         kwargs.pop('''position_ids'''						,       a					)
         for k in list(kwargs.keys()					):
             if kwargs[k] is None or isinstance(kwargs[k]						,       a					):
                 kwargs.pop(a					)
         __lowerCamelCase						=						self._optimized(**a					)
         __lowerCamelCase						=						outputs[0]
         __lowerCamelCase						=						outputs[1]
         __lowerCamelCase						=						CausalLMOutputWithPast(
             loss=a						,       logits=a						,       past_key_values=a						,       hidden_states=a						,       attentions=a						,       )
         return fixed_output






     def __getattr__(				self	:	str						,       a	:	Optional[int]					):





         """simple docstring"""



         return getattr(self._default						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	List[Any]						,       a	:	Union[str, Any]=None						,       a	:	Any=None						,       a	:	List[str]=None						,       **a	:	Optional[Any]					):





         """simple docstring"""



         return self._default.prepare_inputs_for_generation(
             a						,       past_key_values=a						,       inputs_embeds=a						,       use_cache=a						,       **a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	str						,       a	:	Tuple[Tuple[torch.Tensor]]						,       a	:	torch.Tensor					):





         """simple docstring"""



         return self._default._reorder_cache(a						,       a					)






def __lowerCAmelCase				(							)			->					List[Any]:
    __lowerCamelCase						=						argparse.ArgumentParser()
    parser.add_argument(
        '''--model_type'''       ,						default=UpperCamelCase__       ,						type=UpperCamelCase__       ,						required=UpperCamelCase__       ,						help='''Model type selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys()       )       ,						)
    parser.add_argument(
        '''--model_name_or_path'''       ,						default=UpperCamelCase__       ,						type=UpperCamelCase__       ,						required=UpperCamelCase__       ,						help='''Path to pre-trained model or shortcut name selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys()       )       ,						)

    parser.add_argument('''--prompt'''       ,						type=UpperCamelCase__       ,						default=''''''       )
    parser.add_argument('''--length'''       ,						type=UpperCamelCase__       ,						default=20       )
    parser.add_argument('''--stop_token'''       ,						type=UpperCamelCase__       ,						default=UpperCamelCase__       ,						help='''Token at which text generation is stopped'''       )

    parser.add_argument(
        '''--temperature'''       ,						type=UpperCamelCase__       ,						default=1.0       ,						help='''temperature of 1.0 has no effect, lower tend toward greedy sampling'''       ,						)
    parser.add_argument(
        '''--repetition_penalty'''       ,						type=UpperCamelCase__       ,						default=1.0       ,						help='''primarily useful for CTRL model; in that case, use 1.2'''       )
    parser.add_argument('''--k'''       ,						type=UpperCamelCase__       ,						default=0       )
    parser.add_argument('''--p'''       ,						type=UpperCamelCase__       ,						default=0.9       )

    parser.add_argument('''--prefix'''       ,						type=UpperCamelCase__       ,						default=''''''       ,						help='''Text added prior to input.'''       )
    parser.add_argument('''--padding_text'''       ,						type=UpperCamelCase__       ,						default=''''''       ,						help='''Deprecated, the use of `--prefix` is preferred.'''       )
    parser.add_argument('''--xlm_language'''       ,						type=UpperCamelCase__       ,						default=''''''       ,						help='''Optional language when used with the XLM model.'''       )

    parser.add_argument('''--seed'''       ,						type=UpperCamelCase__       ,						default=42       ,						help='''random seed for initialization'''       )
    parser.add_argument('''--no_cuda'''       ,						action='''store_true'''       ,						help='''Avoid using CUDA when available'''       )
    parser.add_argument('''--num_return_sequences'''       ,						type=UpperCamelCase__       ,						default=1       ,						help='''The number of samples to generate.'''       )
    parser.add_argument(
        '''--fp16'''       ,						action='''store_true'''       ,						help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''       ,						)
    parser.add_argument('''--jit'''       ,						action='''store_true'''       ,						help='''Whether or not to use jit trace to accelerate inference'''       )
    __lowerCamelCase						=						parser.parse_args()

    __lowerCamelCase						=						torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''       )
    __lowerCamelCase						=						0 if args.no_cuda else torch.cuda.device_count()

    logger.warning(f"""device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}"""       )

    set_seed(UpperCamelCase__       )

    # Initialize the model and tokenizer
    try:
        __lowerCamelCase						=						args.model_type.lower()
        __lowerCamelCase			,						__lowerCamelCase						=						MODEL_CLASSES[args.model_type]
    except KeyError:
        raise KeyError('''the model {} you specified is not supported. You are welcome to add it and open a PR :)'''       )

    __lowerCamelCase						=						tokenizer_class.from_pretrained(args.model_name_or_path       )
    if tokenizer.pad_token is None:
        __lowerCamelCase						=						tokenizer.eos_token
    __lowerCamelCase						=						model_class.from_pretrained(args.model_name_or_path       )
    model.to(args.device       )

    if args.fpaa:
        model.half()
    __lowerCamelCase						=						getattr(model.config       ,						'''max_position_embeddings'''       ,						0       )
    __lowerCamelCase						=						adjust_length_to_model(args.length       ,						max_sequence_length=UpperCamelCase__       )
    logger.info(UpperCamelCase__       )

    __lowerCamelCase						=						args.prompt if args.prompt else input('''Model prompt >>> '''       )

    # Different models need different input formatting and/or extra arguments
    __lowerCamelCase						=						args.model_type in PREPROCESSING_FUNCTIONS.keys()
    if requires_preprocessing:
        __lowerCamelCase						=						PREPROCESSING_FUNCTIONS.get(args.model_type       )
        __lowerCamelCase						=						prepare_input(UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )

        if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
            __lowerCamelCase						=						{'''add_space_before_punct_symbol''': True}
        else:
            __lowerCamelCase						=						{}

        __lowerCamelCase						=						tokenizer.encode(
            UpperCamelCase__       ,						add_special_tokens=UpperCamelCase__       ,						return_tensors='''pt'''       ,						**UpperCamelCase__       )
    else:
        __lowerCamelCase						=						args.prefix if args.prefix else args.padding_text
        __lowerCamelCase						=						tokenizer.encode(prefix + prompt_text       ,						add_special_tokens=UpperCamelCase__       ,						return_tensors='''pt'''       )
    __lowerCamelCase						=						encoded_prompt.to(args.device       )

    if encoded_prompt.size()[-1] == 0:
        __lowerCamelCase						=						None
    else:
        __lowerCamelCase						=						encoded_prompt

    if args.jit:
        __lowerCamelCase						=						['''enable jit''']
        __lowerCamelCase						=						prepare_jit_inputs(UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )
        torch._C._jit_set_texpr_fuser_enabled(UpperCamelCase__       )
        __lowerCamelCase						=						False
        if hasattr(UpperCamelCase__       ,						'''forward'''       ):
            __lowerCamelCase						=						inspect.signature(model.forward       )
        else:
            __lowerCamelCase						=						inspect.signature(model.__call__       )
        __lowerCamelCase						=						tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(UpperCamelCase__       ,						UpperCamelCase__       ) is not None       )
        __lowerCamelCase						=						torch.jit.trace(UpperCamelCase__       ,						UpperCamelCase__       ,						strict=UpperCamelCase__       )
        __lowerCamelCase						=						torch.jit.freeze(traced_model.eval()       )
        traced_model(*UpperCamelCase__       )
        traced_model(*UpperCamelCase__       )

        __lowerCamelCase						=						_ModelFallbackWrapper(UpperCamelCase__       ,						UpperCamelCase__       )

    __lowerCamelCase						=						model.generate(
        input_ids=UpperCamelCase__       ,						max_length=args.length + len(encoded_prompt[0]       )       ,						temperature=args.temperature       ,						top_k=args.k       ,						top_p=args.p       ,						repetition_penalty=args.repetition_penalty       ,						do_sample=UpperCamelCase__       ,						num_return_sequences=args.num_return_sequences       ,						)

    # Remove the batch dimension when returning multiple sequences
    if len(output_sequences.shape       ) > 2:
        output_sequences.squeeze_()

    __lowerCamelCase						=						[]

    for generated_sequence_idx, generated_sequence in enumerate(UpperCamelCase__       ):
        print(f"""=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="""       )
        __lowerCamelCase						=						generated_sequence.tolist()

        # Decode text
        __lowerCamelCase						=						tokenizer.decode(UpperCamelCase__       ,						clean_up_tokenization_spaces=UpperCamelCase__       )

        # Remove all text after the stop token
        __lowerCamelCase						=						text[: text.find(args.stop_token       ) if args.stop_token else None]

        # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
        __lowerCamelCase						=						(
            prompt_text + text[len(tokenizer.decode(encoded_prompt[0]       ,						clean_up_tokenization_spaces=UpperCamelCase__       )       ) :]
        )

        generated_sequences.append(UpperCamelCase__       )
        print(UpperCamelCase__       )

    return generated_sequences


if __name__ == "__main__":
  main()

'''simple docstring'''




import json
import os
import re
import warnings
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


__UpperCAmelCase  							=logging.get_logger(__name__)

__UpperCAmelCase  							={
    "source_spm": "source.spm",
    "target_spm": "target.spm",
    "vocab": "vocab.json",
    "target_vocab_file": "target_vocab.json",
    "tokenizer_config_file": "tokenizer_config.json",
}

__UpperCAmelCase  							={
    "source_spm": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm"
    },
    "target_spm": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm"
    },
    "vocab": {
        "Helsinki-NLP/opus-mt-en-de": "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json"
    },
    "tokenizer_config_file": {
        "Helsinki-NLP/opus-mt-en-de": (
            "https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json"
        )
    },
}

__UpperCAmelCase  							={"Helsinki-NLP/opus-mt-en-de": 5_1_2}
__UpperCAmelCase  							={}




class 					a__   (     UpperCAmelCase__				):
     lowerCamelCase						:  str							=VOCAB_FILES_NAMES
     lowerCamelCase						:  Union[str, Any]							=PRETRAINED_VOCAB_FILES_MAP
     lowerCamelCase						:  Optional[int]							=PRETRAINED_INIT_CONFIGURATION
     lowerCamelCase						:  str							=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCamelCase						:  Union[str, Any]							=["input_ids", "attention_mask"]
     lowerCamelCase						:  List[Any]							=re.compile(">>.+<<"				)  # type: re.Pattern






     def __init__(				self	:	Dict						,       a	:	Tuple						,       a	:	List[Any]						,       a	:	int						,       a	:	Any=None						,       a	:	str=None						,       a	:	int=None						,       a	:	Optional[int]="<unk>"						,       a	:	Optional[int]="</s>"						,       a	:	Optional[int]="<pad>"						,       a	:	Dict=5_12						,       a	:	Optional[Dict[str, Any]] = None						,       a	:	Optional[int]=False						,       **a	:	List[Any]						,       ):





         """simple docstring"""



         __lowerCamelCase						=						{} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
             source_lang=a						,       target_lang=a						,       unk_token=a						,       eos_token=a						,       pad_token=a						,       model_max_length=a						,       sp_model_kwargs=self.sp_model_kwargs						,       target_vocab_file=a						,       separate_vocabs=a						,       **a						,       )
         assert Path(a					).exists(), f"""cannot find spm source {source_spm}"""

         __lowerCamelCase						=						separate_vocabs
         __lowerCamelCase						=						load_json(a					)
         if self.unk_token not in self.encoder:
             raise KeyError('''<unk> token must be in vocab'''					)
         assert self.pad_token in self.encoder

         if separate_vocabs:
             __lowerCamelCase						=						load_json(a					)
             __lowerCamelCase						=						{v: k for k, v in self.target_encoder.items()}
             __lowerCamelCase						=						[]
         else:
             __lowerCamelCase						=						{v: k for k, v in self.encoder.items()}
             __lowerCamelCase						=						[k for k in self.encoder if k.startswith('''>>'''					) and k.endswith('''<<'''					)]

         __lowerCamelCase						=						source_lang
         __lowerCamelCase						=						target_lang
         __lowerCamelCase						=						[source_spm, target_spm]

         # load SentencePiece model for pre-processing
         __lowerCamelCase						=						load_spm(a						,       self.sp_model_kwargs					)
         __lowerCamelCase						=						load_spm(a						,       self.sp_model_kwargs					)
         __lowerCamelCase						=						self.spm_source
         __lowerCamelCase						=						self.encoder

         # Multilingual target side: default to using first supported language code.

         self._setup_normalizer()






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



         try:
             from sacremoses import MosesPunctNormalizer

             __lowerCamelCase						=						MosesPunctNormalizer(self.source_lang					).normalize
         except (ImportError, FileNotFoundError):
             warnings.warn('''Recommended: pip install sacremoses.'''					)
             __lowerCamelCase						=						lambda a					: x






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	str					):





         """simple docstring"""



         return self.punc_normalizer(a					) if x else ""






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	Any					):





         """simple docstring"""



         return self.current_encoder.get(a						,       self.current_encoder[self.unk_token]					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	str					):





         """simple docstring"""



         __lowerCamelCase						=						self.language_code_re.match(a					)
         __lowerCamelCase						=						[match.group(0					)] if match else []
         return code, self.language_code_re.sub(''''''						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	str					):





         """simple docstring"""



         __lowerCamelCase			,						__lowerCamelCase						=						self.remove_language_code(a					)
         __lowerCamelCase						=						self.current_spm.encode(a						,       out_type=a					)
         return code + pieces






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	int					):





         """simple docstring"""



         return self.decoder.get(a						,       self.unk_token					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]						,       a	:	Optional[Any]						,       **a	:	Dict					):





         """simple docstring"""



         return super().batch_decode(a						,       **a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Union[str, Any]						,       a	:	int						,       **a	:	int					):





         """simple docstring"""



         return super().decode(a						,       **a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	List[str]					):





         """simple docstring"""



         __lowerCamelCase						=						self.spm_source if self._decode_use_source_tokenizer else self.spm_target
         __lowerCamelCase						=						[]
         __lowerCamelCase						=						''''''
         for token in tokens:
             # make sure that special tokens are not decoded using sentencepiece model
             if token in self.all_special_tokens:
                 out_string += sp_model.decode_pieces(a					) + token + " "
                 __lowerCamelCase						=						[]
             else:
                 current_sub_tokens.append(a					)
         out_string += sp_model.decode_pieces(a					)
         return out_string.strip()






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	Union[str, Any]						,       a	:	Tuple=None					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



         __lowerCamelCase						=						self.spm_source
         __lowerCamelCase						=						self.encoder






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]					):





         """simple docstring"""



         __lowerCamelCase						=						self.spm_target
         if self.separate_vocabs:
             __lowerCamelCase						=						self.target_encoder






     @property
     def      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """simple docstring"""



         return len(self.encoder					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any						,       a	:	str						,       a	:	Optional[str] = None					):





         """simple docstring"""



         if not os.path.isdir(a					):
             logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""					)
             return
         __lowerCamelCase						=						[]

         if self.separate_vocabs:
             __lowerCamelCase						=						os.path.join(
                 a						,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab''']						,       )
             __lowerCamelCase						=						os.path.join(
                 a						,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''target_vocab_file''']						,       )
             save_json(self.encoder						,       a					)
             save_json(self.target_encoder						,       a					)
             saved_files.append(a					)
             saved_files.append(a					)
         else:
             __lowerCamelCase						=						os.path.join(
                 a						,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab''']					)
             save_json(self.encoder						,       a					)
             saved_files.append(a					)

         for spm_save_filename, spm_orig_path, spm_model in zip(
             [VOCAB_FILES_NAMES['''source_spm'''], VOCAB_FILES_NAMES['''target_spm''']]						,       self.spm_files						,       [self.spm_source, self.spm_target]						,       ):
             __lowerCamelCase						=						os.path.join(
                 a						,       (filename_prefix + '''-''' if filename_prefix else '''''') + spm_save_filename					)
             if os.path.abspath(a					) != os.path.abspath(a					) and os.path.isfile(a					):
                 copyfile(a						,       a					)
                 saved_files.append(a					)
             elif not os.path.isfile(a					):
                 with open(a						,       '''wb'''					) as fi:
                     __lowerCamelCase						=						spm_model.serialized_model_proto()
                     fi.write(a					)
                 saved_files.append(a					)

         return tuple(a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



         return self.get_src_vocab()






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



         return dict(self.encoder						,       **self.added_tokens_encoder					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



         return dict(self.target_encoder						,       **self.added_tokens_decoder					)






     def __getstate__(				self	:	str					):





         """simple docstring"""



         __lowerCamelCase						=						self.__dict__.copy()
         state.update(
             {k: None for k in ['''spm_source''', '''spm_target''', '''current_spm''', '''punc_normalizer''', '''target_vocab_file''']}					)
         return state






     def __setstate__(				self	:	Tuple						,       a	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						d

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

         __lowerCamelCase			,						__lowerCamelCase						=						(load_spm(a						,       self.sp_model_kwargs					) for f in self.spm_files)
         __lowerCamelCase						=						self.spm_source
         self._setup_normalizer()






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]						,       *a	:	Tuple						,       **a	:	int					):





         """simple docstring"""



         return 1






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	Optional[Any]					):





         """simple docstring"""



         __lowerCamelCase						=						set(self.all_special_ids					)  # call it once instead of inside list comp
         all_special_ids.remove(self.unk_token_id					)  # <unk> is only sometimes special
         return [1 if x in all_special_ids else 0 for x in seq]






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]						,       a	:	List						,       a	:	Optional[List] = None						,       a	:	bool = False					):





         """simple docstring"""



         if already_has_special_tokens:
             return self._special_token_mask(a					)
         elif token_ids_a is None:
             return self._special_token_mask(a					) + [1]
         else:
             return self._special_token_mask(token_ids_a + token_ids_a					) + [1]






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					sentencepiece.SentencePieceProcessor:
    __lowerCamelCase						=						sentencepiece.SentencePieceProcessor(**UpperCamelCase__       )
    spm.Load(UpperCamelCase__       )
    return spm






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					None:
    with open(UpperCamelCase__       ,						'''w'''       ) as f:
        json.dump(UpperCamelCase__       ,						UpperCamelCase__       ,						indent=2       )






def __lowerCAmelCase				(							UpperCamelCase__       )			->					Union[Dict, List]:
    with open(UpperCamelCase__       ,						'''r'''       ) as f:
        return json.load(UpperCamelCase__       )
