



'''simple docstring'''





import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


_UpperCamelCase							       =		threading.Lock()
_UpperCamelCase							       =		None

_UpperCamelCase							       =		{
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'critical': logging.CRITICAL,
}

_UpperCamelCase							       =		logging.WARNING

_UpperCamelCase							       =		True

def  a_  (							)   ->   Union[str, Any]:
  __lowerCamelCase : Union[str, Any]					 =				os.getenv('DIFFUSERS_VERBOSITY' ,_lowerCAmelCase )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          F'Unknown option DIFFUSERS_VERBOSITY={env_level_str}, '
          F'has to be one of: { ", ".join(log_levels.keys() ) }' )
  return _default_log_level

def  a_  (							)   ->   str:
  return __name__.split('.' )[0]

def  a_  (							)   ->   logging.Logger:
  return logging.getLogger(_get_library_name() )

def  a_  (							)   ->   None:
  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    __lowerCamelCase : Tuple					 =				logging.StreamHandler()  # Set sys.stderr as stream.
    __lowerCamelCase : List[Any]					 =				sys.stderr.flush

    # Apply our default configuration to the library root logger.
    __lowerCamelCase : int					 =				_get_library_root_logger()
    library_root_logger.addHandler(_default_handler )
    library_root_logger.setLevel(_get_default_logging_level() )
    __lowerCamelCase : Tuple					 =				False

def  a_  (							)   ->   None:
  global _default_handler

  with _lock:
    if not _default_handler:
      return

    __lowerCamelCase : Any					 =				_get_library_root_logger()
    library_root_logger.removeHandler(_default_handler )
    library_root_logger.setLevel(logging.NOTSET )
    __lowerCamelCase : Any					 =				None

def  a_  (							)   ->   Optional[Any]:
  return log_levels

def  a_  (							_lowerCAmelCase = None )   ->   logging.Logger:

  if name is None:
    __lowerCamelCase : int					 =				_get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(_lowerCAmelCase )

def  a_  (							)   ->   int:
  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()

def  a_  (							_lowerCAmelCase )   ->   None:
  _configure_library_root_logger()
  _get_library_root_logger().setLevel(_lowerCAmelCase )

def  a_  (							)   ->   Optional[Any]:
  return set_verbosity(_lowerCAmelCase )

def  a_  (							)   ->   str:
  return set_verbosity(_lowerCAmelCase )

def  a_  (							)   ->   Optional[Any]:
  return set_verbosity(_lowerCAmelCase )

def  a_  (							)   ->   List[Any]:
  return set_verbosity(_lowerCAmelCase )

def  a_  (							)   ->   None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler )

def  a_  (							)   ->   None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler )

def  a_  (							_lowerCAmelCase )   ->   None:
  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(_lowerCAmelCase )

def  a_  (							_lowerCAmelCase )   ->   None:
  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(_lowerCAmelCase )

def  a_  (							)   ->   None:
  _configure_library_root_logger()
  __lowerCamelCase : int					 =				False

def  a_  (							)   ->   None:
  _configure_library_root_logger()
  __lowerCamelCase : Any					 =				True

def  a_  (							)   ->   None:
  __lowerCamelCase : Dict					 =				_get_library_root_logger().handlers

  for handler in handlers:
    __lowerCamelCase : Tuple					 =				logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s' )
    handler.setFormatter(_lowerCAmelCase )

def  a_  (							)   ->   None:
  __lowerCamelCase : Dict					 =				_get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(_lowerCAmelCase )

def  a_  (							self ,*_lowerCAmelCase ,**_lowerCAmelCase )   ->   Dict:
  __lowerCamelCase : int					 =				os.getenv('DIFFUSERS_NO_ADVISORY_WARNINGS' ,_lowerCAmelCase )
  if no_advisory_warnings:
    return
  self.warning(*_lowerCAmelCase ,**_lowerCAmelCase )


_UpperCamelCase							       =		warning_advice






class       lowerCamelCase_					:
  """simple docstring"""




  def __init__(				self   :			str    ,			*_a   :			Any    ,			**_a   :			Dict     )      ->      str:  # pylint: disable=unused-argument
    __lowerCamelCase : int					 =				args[0] if args else None




  def __iter__(				self   :			int     )      ->      int:
    return iter(self._iterator     )




  def __getattr__(				self   :			Tuple    ,			_a   :			str     )      ->      Union[str, Any]:

    def empty_fn(*_a   :			Optional[Any]    ,			**_a   :			Optional[Any]     ):  # pylint: disable=unused-argument
      return

    return empty_fn




  def __enter__(				self   :			Optional[int]     )      ->      Union[str, Any]:
    return self




  def __exit__(				self   :			List[str]    ,			_a   :			str    ,			_a   :			int    ,			_a   :			int     )      ->      int:
    return






class       lowerCamelCase_					:
  """simple docstring"""




  def __call__(				self   :			Any    ,			*_a   :			Optional[Any]    ,			**_a   :			Optional[int]     )      ->      Dict:
    if _tqdm_active:
      return tqdm_lib.tqdm(*_a    ,			**_a     )
    else:
      return EmptyTqdm(*_a    ,			**_a     )




  def 		_lowercase  (				self   :			Union[str, Any]    ,			*_a   :			int    ,			**_a   :			Tuple     )      ->      Dict:
    __lowerCamelCase : Any					 =				None
    if _tqdm_active:
      return tqdm_lib.tqdm.set_lock(*_a    ,			**_a     )




  def 		_lowercase  (				self   :			Dict     )      ->      int:
    if _tqdm_active:
      return tqdm_lib.tqdm.get_lock()




_UpperCamelCase							       =		_tqdm_cls()

def  a_  (							)   ->   bool:
  global _tqdm_active
  return bool(_tqdm_active )

def  a_  (							)   ->   Union[str, Any]:
  global _tqdm_active
  __lowerCamelCase : List[str]					 =				True


def  a_  (							)   ->   Tuple:
  global _tqdm_active
  __lowerCamelCase : int					 =				False











'''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,)






