



'''simple docstring'''





import inspect
import json
import os
import tempfile
import unittest

from transformers.models.speech_to_text_a import SpeechaTextaTokenizer
from transformers.models.speech_to_text_a.tokenization_speech_to_text_a import VOCAB_FILES_NAMES

from ...test_tokenization_common import TokenizerTesterMixin






class       lowerCamelCase_					(       lowercase__     ,     unittest.TestCase  ):
  """simple docstring"""




  a_							      =SpeechaTextaTokenizer
  a_							      =False




  def 		_lowercase  (				self   :			Tuple     )      ->      List[Any]:
    super().setUp()

    __lowerCamelCase : str					 =				'<s> <pad> </s> <unk> here@@ a couple of@@ words for the he@@ re@@ vocab'.split(' '     )
    __lowerCamelCase : Any					 =				['he re</w> 123', 'here a 1456']
    __lowerCamelCase : Tuple					 =				dict(zip(_A    ,			range(len(_A     )     )     )     )

    __lowerCamelCase : str					 =				{'pad_token': '<pad>', 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>'}

    __lowerCamelCase : Optional[Any]					 =				tempfile.mkdtemp()
    __lowerCamelCase : Optional[int]					 =				os.path.join(self.tmpdirname    ,			VOCAB_FILES_NAMES['vocab_file']     )
    __lowerCamelCase : List[str]					 =				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(_A     ) + '\n'     )

    with open(self.merges_file    ,			'w'     ) as fp:
      fp.write('\n'.join(_A     )     )




  def 		_lowercase  (				self   :			Any     )      ->      Optional[int]:
    __lowerCamelCase : Union[str, Any]					 =				list(self.get_tokenizer().get_vocab().keys()     )

    self.assertEqual(vocab_keys[0]    ,			'<s>'     )
    self.assertEqual(vocab_keys[1]    ,			'<pad>'     )
    self.assertEqual(vocab_keys[-1]    ,			'vocab'     )
    self.assertEqual(len(_A     )    ,			14     )




  def 		_lowercase  (				self   :			List[Any]     )      ->      List[str]:
    self.assertEqual(self.get_tokenizer().vocab_size    ,			14     )




  def 		_lowercase  (				self   :			Optional[int]     )      ->      Tuple:
    __lowerCamelCase : Any					 =				SpeechaTextaTokenizer.from_pretrained(self.tmpdirname     )

    # make sure @@ is correctly concatenated
    __lowerCamelCase : List[Any]					 =				[4, 6, 8, 7, 10]  # ["here@@", "couple", "words", "of@@", "the"]
    __lowerCamelCase : Any					 =				tokenizer.decode(_A     )

    self.assertTrue(output_string == 'herecouple words ofthe'     )




  def 		_lowercase  (				self   :			List[str]     )      ->      str:
    __lowerCamelCase : int					 =				SpeechaTextaTokenizer.from_pretrained(self.tmpdirname     )

    with tempfile.TemporaryDirectory() as tmp_dirname:
      tokenizer.save_pretrained(_A     )
      os.remove(os.path.join(_A    ,			'merges.txt'     )     )

      # load tokenizer without merges file should not throw an error
      __lowerCamelCase : str					 =				SpeechaTextaTokenizer.from_pretrained(_A     )

    with tempfile.TemporaryDirectory() as tmp_dirname:
      # save tokenizer and load again
      tokenizer.save_pretrained(_A     )
      __lowerCamelCase : Optional[int]					 =				SpeechaTextaTokenizer.from_pretrained(_A     )

    self.assertIsNotNone(_A     )




  def 		_lowercase  (				self   :			Dict     )      ->      Union[str, Any]:
    if not self.test_slow_tokenizer:
      return

    __lowerCamelCase : Optional[Any]					 =				inspect.signature(self.tokenizer_class.__init__     )
    __lowerCamelCase : Optional[Any]					 =				self.get_tokenizer()

    for parameter_name, parameter in signature.parameters.items():
      if parameter.default != inspect.Parameter.empty and parameter_name != "merges_file":
        self.assertIn(_A    ,			tokenizer.init_kwargs     )











'''simple docstring'''





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_mbartaa import MBartaaTokenizer
else:
   _UpperCamelCase							       =		None


_UpperCamelCase							       =		logging.get_logger(__name__)

_UpperCamelCase							       =		{'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

_UpperCamelCase							       =		{
    'vocab_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/mbart-large-50-one-to-many-mmt': (
            'https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/tokenizer.json'
        ),
    },
}

_UpperCamelCase							       =		{
    'facebook/mbart-large-50-one-to-many-mmt': 1024,
}

# fmt: off
_UpperCamelCase							       =		['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', 'af_ZA', 'az_AZ', 'bn_IN', 'fa_IR', 'he_IL', 'hr_HR', 'id_ID', 'ka_GE', 'km_KH', 'mk_MK', 'ml_IN', 'mn_MN', 'mr_IN', 'pl_PL', 'ps_AF', 'pt_XX', 'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH', 'tl_XX', 'uk_UA', 'ur_PK', 'xh_ZA', 'gl_ES', 'sl_SI']






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  a_							      =VOCAB_FILES_NAMES
  a_							      =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_							      =PRETRAINED_VOCAB_FILES_MAP
  a_							      =["""input_ids""", """attention_mask"""]
  a_							      =MBartaaTokenizer

  a_							      =[]
  a_							      =[]




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

    __lowerCamelCase : Tuple					 =				kwargs.get('additional_special_tokens'    ,			[]     )
    kwargs["additional_special_tokens"] += [
        code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
    ]

    super().__init__(
        _a    ,			src_lang=_a    ,			tgt_lang=_a    ,			tokenizer_file=_a    ,			eos_token=_a    ,			sep_token=_a    ,			cls_token=_a    ,			unk_token=_a    ,			pad_token=_a    ,			mask_token=_a    ,			**_a    ,			)

    __lowerCamelCase : Optional[int]					 =				vocab_file
    __lowerCamelCase : Optional[Any]					 =				False if not self.vocab_file else True

    __lowerCamelCase : Dict					 =				{
        lang_code: self.convert_tokens_to_ids(_a     ) for lang_code in FAIRSEQ_LANGUAGE_CODES
    }

    __lowerCamelCase : Dict					 =				src_lang if src_lang is not None else 'en_XX'
    __lowerCamelCase : int					 =				tgt_lang
    __lowerCamelCase : Optional[int]					 =				self.lang_code_to_id[self._src_lang]
    self.set_src_lang_special_tokens(self._src_lang     )




  @property
  def 		_lowercase  (				self   :			Dict     )      ->      str:
    return self._src_lang




  @src_lang.setter
  def 		_lowercase  (				self   :			str    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : Dict					 =				new_src_lang
    self.set_src_lang_special_tokens(self._src_lang     )




  def 		_lowercase  (				self   :			Optional[int]    ,			_a   :			List[int]    ,			_a   :			Optional[List[int]] = None     )      ->      List[int]:
    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 		_lowercase  (				self   :			Dict    ,			_a   :			List[str]    ,			_a   :			str = "en_XX"    ,			_a   :			Optional[List[str]] = None    ,			_a   :			str = "ro_RO"    ,			**_a   :			List[str]    ,			)      ->      BatchEncoding:
    __lowerCamelCase : Union[str, Any]					 =				src_lang
    __lowerCamelCase : Any					 =				tgt_lang
    return super().prepare_seqaseq_batch(_a    ,			_a    ,			**_a     )




  def 		_lowercase  (				self   :			Tuple     )      ->      Union[str, Any]:
    return self.set_src_lang_special_tokens(self.src_lang     )




  def 		_lowercase  (				self   :			int     )      ->      Optional[Any]:
    return self.set_tgt_lang_special_tokens(self.tgt_lang     )




  def 		_lowercase  (				self   :			int    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : int					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : List[str]					 =				[self.cur_lang_code_id]
    __lowerCamelCase : Any					 =				[self.eos_token_id]

    __lowerCamelCase : int					 =				self.convert_ids_to_tokens(self.prefix_tokens     )
    __lowerCamelCase : Tuple					 =				self.convert_ids_to_tokens(self.suffix_tokens     )

    __lowerCamelCase : str					 =				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 		_lowercase  (				self   :			str    ,			_a   :			str     )      ->      None:
    __lowerCamelCase : Optional[int]					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : Tuple					 =				[self.cur_lang_code_id]
    __lowerCamelCase : Tuple					 =				[self.eos_token_id]

    __lowerCamelCase : List[Any]					 =				self.convert_ids_to_tokens(self.prefix_tokens     )
    __lowerCamelCase : Union[str, Any]					 =				self.convert_ids_to_tokens(self.suffix_tokens     )

    __lowerCamelCase : 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 		_lowercase  (				self   :			Tuple    ,			_a   :			Any    ,			_a   :			str    ,			_a   :			Optional[str]    ,			_a   :			Optional[str]    ,			**_a   :			List[Any]     )      ->      Optional[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'     )
    __lowerCamelCase : Union[str, Any]					 =				src_lang
    __lowerCamelCase : List[Any]					 =				self(_a    ,			add_special_tokens=_a    ,			return_tensors=_a    ,			**_a     )
    __lowerCamelCase : Optional[int]					 =				self.convert_tokens_to_ids(_a     )
    __lowerCamelCase : Dict					 =				tgt_lang_id
    return inputs




  def 		_lowercase  (				self   :			Any    ,			_a   :			str    ,			_a   :			Optional[str] = None     )      ->      Tuple[str]:
    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
    __lowerCamelCase : List[str]					 =				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,)






