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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


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

__lowerCAmelCase					:			Any            =		"▁"

__lowerCAmelCase					:			Union[str, Any]            =		{"vocab_file": "sentencepiece.bpe.model"}

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

__lowerCAmelCase					:			Tuple            =		{
    "facebook/mbart-large-en-ro": 1_024,
    "facebook/mbart-large-cc25": 1_024,
}

# fmt: off
__lowerCAmelCase					:			str            =		["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 						__lowerCAmelCase	(	lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			Any        =    VOCAB_FILES_NAMES
      A__	:			Dict        =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      A__	:			Optional[int]        =    PRETRAINED_VOCAB_FILES_MAP
      A__	:			List[Any]        =    ['''input_ids''', '''attention_mask''']

      A__	:			List[int]        =    []
      A__	:			List[int]        =    []




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

          __lowercase		:			str	    =       {} if sp_model_kwargs is None else sp_model_kwargs

          super().__init__(
              bos_token=_snake_case				,       eos_token=_snake_case				,       unk_token=_snake_case				,       sep_token=_snake_case				,       cls_token=_snake_case				,       pad_token=_snake_case				,       mask_token=_snake_case				,       tokenizer_file=_snake_case				,       src_lang=_snake_case				,       tgt_lang=_snake_case				,       additional_special_tokens=_snake_case				,       sp_model_kwargs=self.sp_model_kwargs				,       **_snake_case				,       )

          __lowercase		:			int	    =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
          self.sp_model.Load(str(_snake_case				)				)
          __lowercase		:			Any	    =       vocab_file

          # Original fairseq vocab and spm vocab must be "aligned":
          # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
          # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
          # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
          # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

          # Mimic fairseq token-to-id alignment for the first 4 token
          __lowercase		:			Optional[Any]	    =       {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          __lowercase		:			List[Any]	    =       1

          __lowercase		:			Tuple	    =       len(self.sp_model				)
          __lowercase		:			int	    =       {
              code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_snake_case				)
          }
          __lowercase		:			str	    =       {v: k for k, v in self.lang_code_to_id.items()}
          __lowercase		:			Optional[Any]	    =       len(self.sp_model				) + len(self.lang_code_to_id				) + self.fairseq_offset

          self.fairseq_tokens_to_ids.update(self.lang_code_to_id				)
          __lowercase		:			List[str]	    =       {v: k for k, v in self.fairseq_tokens_to_ids.items()}
          __lowercase		:			Tuple	    =       list(self.lang_code_to_id.keys()				)

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

          __lowercase		:			str	    =       src_lang if src_lang is not None else '''en_XX'''
          __lowercase		:			Any	    =       self.lang_code_to_id[self._src_lang]
          __lowercase		:			Dict	    =       tgt_lang
          self.set_src_lang_special_tokens(self._src_lang				)




      def __getstate__(      self		:       Tuple				):
          __lowercase		:			List[str]	    =       self.__dict__.copy()
          __lowercase		:			Optional[Any]	    =       None
          __lowercase		:			Dict	    =       self.sp_model.serialized_model_proto()
          return state




      def __setstate__(      self		:       Union[str, Any]				,       _snake_case		:       List[Any]				):
          __lowercase		:			Tuple	    =       d

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

          __lowercase		:			List[str]	    =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)




      @property
      def 		snake_case_			(      self		:       Union[str, Any]				):
          return len(self.sp_model				) + len(self.lang_code_to_id				) + self.fairseq_offset + 1  # Plus 1 for the mask token




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




      @src_lang.setter
      def 		snake_case_			(      self		:       List[Any]				,       _snake_case		:       str				):
          __lowercase		:			Any	    =       new_src_lang
          self.set_src_lang_special_tokens(self._src_lang				)




      def 		snake_case_			(      self		:       int				,       _snake_case		:       List[int]				,       _snake_case		:       Optional[List[int]] = None				,       _snake_case		:       bool = False				):

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

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




      def 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       List[int]				,       _snake_case		:       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 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       List[int]				,       _snake_case		:       Optional[List[int]] = None				):
          __lowercase		:			Optional[int]	    =       [self.sep_token_id]
          __lowercase		:			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 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				,       _snake_case		:       str				,       _snake_case		:       Optional[str]				,       _snake_case		:       Optional[str]				,       **_snake_case		:       Union[str, 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'''				)
          __lowercase		:			str	    =       src_lang
          __lowercase		:			Optional[int]	    =       self(_snake_case				,       add_special_tokens=_snake_case				,       return_tensors=_snake_case				,       **_snake_case				)
          __lowercase		:			Optional[int]	    =       self.convert_tokens_to_ids(_snake_case				)
          __lowercase		:			List[Any]	    =       tgt_lang_id
          return inputs




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			List[str]	    =       {self.convert_ids_to_tokens(_snake_case				): i for i in range(self.vocab_size				)}
          vocab.update(self.added_tokens_encoder				)
          return vocab




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				):
          return self.sp_model.encode(_snake_case				,       out_type=_snake_case				)




      def 		snake_case_			(      self		:       Any				,       _snake_case		:       Optional[Any]				):
          if token in self.fairseq_tokens_to_ids:
              return self.fairseq_tokens_to_ids[token]
          __lowercase		:			int	    =       self.sp_model.PieceToId(_snake_case				)

          # Need to return unknown token if the SP model returned 0
          return spm_id + self.fairseq_offset if spm_id else self.unk_token_id




      def 		snake_case_			(      self		:       Union[str, Any]				,       _snake_case		:       Union[str, Any]				):
          if index in self.fairseq_ids_to_tokens:
              return self.fairseq_ids_to_tokens[index]
          return self.sp_model.IdToPiece(index - self.fairseq_offset				)




      def 		snake_case_			(      self		:       Dict				,       _snake_case		:       Tuple				):
          __lowercase		:			int	    =       ''''''.join(_snake_case				).replace(_snake_case				,       ''' '''				).strip()
          return out_string




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				,       _snake_case		:       Optional[str] = None				):
          if not os.path.isdir(_snake_case				):
              logger.error(F'Vocabulary path ({save_directory}) should be a directory'				)
              return
          __lowercase		:			List[str]	    =       os.path.join(
              _snake_case				,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']				)

          if os.path.abspath(self.vocab_file				) != os.path.abspath(_snake_case				) and os.path.isfile(self.vocab_file				):
              copyfile(self.vocab_file				,       _snake_case				)
          elif not os.path.isfile(self.vocab_file				):
              with open(_snake_case				,       '''wb'''				) as fi:
                  __lowercase		:			Optional[int]	    =       self.sp_model.serialized_model_proto()
                  fi.write(_snake_case				)

          return (out_vocab_file,)




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       List[str]				,       _snake_case		:       str = "en_XX"				,       _snake_case		:       Optional[List[str]] = None				,       _snake_case		:       str = "ro_RO"				,       **_snake_case		:       Union[str, Any]				,       ):
          __lowercase		:			Tuple	    =       src_lang
          __lowercase		:			Any	    =       tgt_lang
          return super().prepare_seqaseq_batch(_snake_case				,       _snake_case				,       **_snake_case				)




      def 		snake_case_			(      self		:       Any				):
          return self.set_src_lang_special_tokens(self.src_lang				)




      def 		snake_case_			(      self		:       int				):
          return self.set_tgt_lang_special_tokens(self.tgt_lang				)




      def 		snake_case_			(      self		:       Dict				,       _snake_case		:       Tuple				):
          __lowercase		:			List[str]	    =       self.lang_code_to_id[src_lang]
          __lowercase		:			Dict	    =       []
          __lowercase		:			List[Any]	    =       [self.eos_token_id, self.cur_lang_code]




      def 		snake_case_			(      self		:       str				,       _snake_case		:       str				):
          __lowercase		:			str	    =       self.lang_code_to_id[lang]
          __lowercase		:			Union[str, Any]	    =       []
          __lowercase		:			Union[str, Any]	    =       [self.eos_token_id, self.cur_lang_code]




import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
 import torch

 from transformers import AutoModelForCausalLM


@require_torch
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase		:			Optional[Any]	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				)
          __lowercase		:			Any	    =       AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				).to(_snake_case				)
          __lowercase		:			List[str]	    =       -1

          __lowercase		:			Optional[Any]	    =       ids_tensor((1, 5)				,       vocab_size=model.config.vocab_size				).to(_snake_case				)
          __lowercase		:			Tuple	    =       model.generate(_snake_case				,       max_new_tokens=10				,       do_sample=_snake_case				)
          __lowercase		:			Optional[int]	    =       tokenizer.decode(greedy_ids[0]				)

          with CaptureStdout() as cs:
              __lowercase		:			Optional[Any]	    =       TextStreamer(_snake_case				)
              model.generate(_snake_case				,       max_new_tokens=10				,       do_sample=_snake_case				,       streamer=_snake_case				)
          # The greedy text should be printed to stdout, except for the final "\n" in the streamer
          __lowercase		:			List[Any]	    =       cs.out[:-1]

          self.assertEqual(_snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			Optional[int]	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				)
          __lowercase		:			Optional[Any]	    =       AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				).to(_snake_case				)
          __lowercase		:			List[str]	    =       -1

          __lowercase		:			Tuple	    =       ids_tensor((1, 5)				,       vocab_size=model.config.vocab_size				).to(_snake_case				)
          __lowercase		:			List[Any]	    =       model.generate(_snake_case				,       max_new_tokens=10				,       do_sample=_snake_case				)
          __lowercase		:			Optional[Any]	    =       tokenizer.decode(greedy_ids[0]				)

          __lowercase		:			int	    =       TextIteratorStreamer(_snake_case				)
          __lowercase		:			int	    =       {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
          __lowercase		:			Optional[Any]	    =       Thread(target=model.generate				,       kwargs=_snake_case				)
          thread.start()
          __lowercase		:			Optional[int]	    =       ''''''
          for new_text in streamer:
              streamer_text += new_text

          self.assertEqual(_snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			Dict	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				)
          __lowercase		:			int	    =       AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				).to(_snake_case				)
          __lowercase		:			List[Any]	    =       -1

          __lowercase		:			List[Any]	    =       ids_tensor((1, 5)				,       vocab_size=model.config.vocab_size				).to(_snake_case				)
          __lowercase		:			str	    =       model.generate(_snake_case				,       max_new_tokens=10				,       do_sample=_snake_case				)
          __lowercase		:			List[Any]	    =       greedy_ids[:, input_ids.shape[1] :]
          __lowercase		:			Optional[Any]	    =       tokenizer.decode(new_greedy_ids[0]				)

          with CaptureStdout() as cs:
              __lowercase		:			int	    =       TextStreamer(_snake_case				,       skip_prompt=_snake_case				)
              model.generate(_snake_case				,       max_new_tokens=10				,       do_sample=_snake_case				,       streamer=_snake_case				)
          # The greedy text should be printed to stdout, except for the final "\n" in the streamer
          __lowercase		:			int	    =       cs.out[:-1]

          self.assertEqual(_snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       Any				):
          # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
          # with actual models -- the dummy models' tokenizers are not aligned with their models, and
          # `skip_special_tokens=True` has no effect on them
          __lowercase		:			Dict	    =       AutoTokenizer.from_pretrained('''distilgpt2'''				)
          __lowercase		:			List[str]	    =       AutoModelForCausalLM.from_pretrained('''distilgpt2'''				).to(_snake_case				)
          __lowercase		:			str	    =       -1

          __lowercase		:			Dict	    =       torch.ones((1, 5)				,       device=_snake_case				).long() * model.config.bos_token_id
          with CaptureStdout() as cs:
              __lowercase		:			Optional[Any]	    =       TextStreamer(_snake_case				,       skip_special_tokens=_snake_case				)
              model.generate(_snake_case				,       max_new_tokens=1				,       do_sample=_snake_case				,       streamer=_snake_case				)

          # The prompt contains a special token, so the streamer should not print it. As such, the output text, when
          # re-tokenized, must only contain one token
          __lowercase		:			Dict	    =       cs.out[:-1]  # Remove the final "\n"
          __lowercase		:			Any	    =       tokenizer(_snake_case				,       return_tensors='''pt'''				)
          self.assertEqual(streamer_text_tokenized.input_ids.shape				,       (1, 1)				)




      def 		snake_case_			(      self		:       Any				):
          __lowercase		:			List[str]	    =       AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				)
          __lowercase		:			Union[str, Any]	    =       AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''				).to(_snake_case				)
          __lowercase		:			Dict	    =       -1

          __lowercase		:			List[Any]	    =       ids_tensor((1, 5)				,       vocab_size=model.config.vocab_size				).to(_snake_case				)
          __lowercase		:			Tuple	    =       TextIteratorStreamer(_snake_case				,       timeout=0.0_01				)
          __lowercase		:			Tuple	    =       {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
          __lowercase		:			Optional[int]	    =       Thread(target=model.generate				,       kwargs=_snake_case				)
          thread.start()

          # The streamer will timeout after 0.001 seconds, so an exception will be raised
          with self.assertRaises(_snake_case				):
              __lowercase		:			List[Any]	    =       ''''''
              for new_text in streamer:
                  streamer_text += new_text


