


from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

lowerCAmelCase       		=    TypeVar("""T""")
lowerCAmelCase       		=    TypeVar("""U""")




class 							lowerCamelCase   (  Generic[T, U] ):


	def __init__(    self				,     lowercase__				,     lowercase__):
							__UpperCAmelCase			:							Tuple	    =	key
							__UpperCAmelCase			:							Tuple	    =	val
							__UpperCAmelCase			:							DoubleLinkedListNode[T, U] | None	    =	None
							__UpperCAmelCase			:							DoubleLinkedListNode[T, U] | None	    =	None


	def __repr__(    self):
							return (
							    F"Node: key: {self.key}, val: {self.val}, "
							    F"has next: {bool(self.next)}, has prev: {bool(self.prev)}"
							)






class 							lowerCamelCase   (  Generic[T, U] ):


	def __init__(    self):
							__UpperCAmelCase			:							DoubleLinkedListNode[T, U]	    =	DoubleLinkedListNode(lowercase__				,     lowercase__)
							__UpperCAmelCase			:							DoubleLinkedListNode[T, U]	    =	DoubleLinkedListNode(lowercase__				,     lowercase__)
							__UpperCAmelCase    ,      __UpperCAmelCase			:							Optional[Any]	    =	self.rear, self.head


	def __repr__(    self):
							__UpperCAmelCase			:							List[Any]	    =	['''DoubleLinkedList''']
							__UpperCAmelCase			:							int	    =	self.head
							while node.next is not None:
													rep.append(str(lowercase__))
													__UpperCAmelCase			:							Optional[Any]	    =	node.next
							rep.append(str(self.rear))
							return ",\n    ".join(lowercase__)


	def  A(    self				,     lowercase__):
							__UpperCAmelCase			:							Optional[Any]	    =	self.rear.prev

							# All nodes other than self.head are guaranteed to have non-None previous
							assert previous is not None

							__UpperCAmelCase			:							Dict	    =	node
							__UpperCAmelCase			:							List[str]	    =	previous
							__UpperCAmelCase			:							Dict	    =	node
							__UpperCAmelCase			:							Dict	    =	self.rear


	def  A(    self				,     lowercase__):

							if node.prev is None or node.next is None:
													return None

							__UpperCAmelCase			:							int	    =	node.next
							__UpperCAmelCase			:							Optional[int]	    =	node.prev
							__UpperCAmelCase			:							Dict	    =	None
							__UpperCAmelCase			:							Union[str, Any]	    =	None
							return node






class 							lowerCamelCase   (  Generic[T, U] ):
	_lowerCAmelCase     :		dict[Callable[[T], U], LRUCache[T, U]]										=						{}


	def __init__(    self				,     lowercase__):
							__UpperCAmelCase			:							DoubleLinkedList[T, U]	    =	DoubleLinkedList()
							__UpperCAmelCase			:							Tuple	    =	capacity
							__UpperCAmelCase			:							str	    =	0
							__UpperCAmelCase			:							Union[str, Any]	    =	0
							__UpperCAmelCase			:							Dict	    =	0
							__UpperCAmelCase			:							dict[T, DoubleLinkedListNode[T, U]]	    =	{}


	def __repr__(    self):
							return (
							    F"CacheInfo(hits={self.hits}, misses={self.miss}, "
							    F"capacity={self.capacity}, current size={self.num_keys})"
							)


	def __contains__(    self				,     lowercase__):
							return key in self.cache


	def  A(    self				,     lowercase__):
							# Note: pythonic interface would throw KeyError rather than return None

							if key in self.cache:
													self.hits += 1
													__UpperCAmelCase			:							DoubleLinkedListNode[T, U]	    =	self.cache[key]
													__UpperCAmelCase			:							str	    =	self.list.remove(self.cache[key])
													assert node == value_node

													# node is guaranteed not None because it is in self.cache
													assert node is not None
													self.list.add(lowercase__)
													return node.val
							self.miss += 1
							return None


	def  A(    self				,     lowercase__				,     lowercase__):

							if key not in self.cache:
													if self.num_keys >= self.capacity:
																			# delete first node (oldest) when over capacity
																			__UpperCAmelCase			:							Tuple	    =	self.list.head.next

																			# guaranteed to have a non-None first node when num_keys > 0
																			# explain to type checker via assertions
																			assert first_node is not None
																			assert first_node.key is not None
																			assert (
																			    self.list.remove(lowercase__) is not None
																			)  # node guaranteed to be in list assert node.key is not None

																			del self.cache[first_node.key]
																			self.num_keys -= 1
													__UpperCAmelCase			:							Any	    =	DoubleLinkedListNode(lowercase__				,     lowercase__)
													self.list.add(self.cache[key])
													self.num_keys += 1

							else:
													# bump node to the end of the list, update value
													__UpperCAmelCase			:							Any	    =	self.list.remove(self.cache[key])
													assert node is not None  # node guaranteed to be in list
													__UpperCAmelCase			:							List[Any]	    =	value
													self.list.add(lowercase__)


	@classmethod
	def  A(    cls				,     lowercase__ = 1_2_8):

							def cache_decorator_inner(lowercase__) -> Callable[..., U]:
													def cache_decorator_wrapper(*lowercase__) -> U:
																			if func not in cls.decorator_function_to_instance_map:
																									__UpperCAmelCase			:							Optional[Any]	    =	LRUCache(lowercase__)

																			__UpperCAmelCase			:							int	    =	cls.decorator_function_to_instance_map[func].get(args[0])
																			if result is None:
																									__UpperCAmelCase			:							Dict	    =	func(*lowercase__)
																									cls.decorator_function_to_instance_map[func].put(args[0]				,     lowercase__)
																			return result

													def cache_info() -> LRUCache[T, U]:
																			return cls.decorator_function_to_instance_map[func]

													setattr(lowercase__				,     '''cache_info'''				,     lowercase__)  # noqa: B010

													return cache_decorator_wrapper

							return cache_decorator_inner


if __name__ == "__main__":
				import doctest

				doctest.testmod()





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:
				lowerCAmelCase       		=    None


lowerCAmelCase       		=    logging.get_logger(__name__)


lowerCAmelCase       		=    {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase       		=    {
    """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""",
    },
}

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

# fmt: off
lowerCAmelCase       		=    ["""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   (  _UpperCamelCase ):
	_lowerCAmelCase     :		List[str]										=						VOCAB_FILES_NAMES
	_lowerCAmelCase     :		Union[str, Any]										=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_lowerCAmelCase     :		str										=						PRETRAINED_VOCAB_FILES_MAP
	_lowerCAmelCase     :		Optional[int]										=						['''input_ids''', '''attention_mask''']
	_lowerCAmelCase     :		Optional[int]										=						MBartTokenizer

	_lowerCAmelCase     :		List[int]										=						[]
	_lowerCAmelCase     :		List[int]										=						[]


	def __init__(    self				,     lowercase__=None				,     lowercase__=None				,     lowercase__="<s>"				,     lowercase__="</s>"				,     lowercase__="</s>"				,     lowercase__="<s>"				,     lowercase__="<unk>"				,     lowercase__="<pad>"				,     lowercase__="<mask>"				,     lowercase__=None				,     lowercase__=None				,     lowercase__=None				,     **lowercase__				,     ):
							# Mask token behave like a normal word, i.e. include the space before it
							__UpperCAmelCase			:							Any	    =	AddedToken(lowercase__				,     lstrip=lowercase__				,     rstrip=lowercase__) if isinstance(lowercase__				,     lowercase__) else mask_token

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

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

							__UpperCAmelCase			:							str	    =	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})
							__UpperCAmelCase			:							Union[str, Any]	    =	{
							    lang_code: self.convert_tokens_to_ids(lowercase__) for lang_code in FAIRSEQ_LANGUAGE_CODES
							}

							__UpperCAmelCase			:							Any	    =	src_lang if src_lang is not None else '''en_XX'''
							__UpperCAmelCase			:							Optional[int]	    =	self.convert_tokens_to_ids(self._src_lang)
							__UpperCAmelCase			:							List[Any]	    =	tgt_lang
							self.set_src_lang_special_tokens(self._src_lang)


	@property
	def  A(    self):
							return self._src_lang


	@src_lang.setter
	def  A(    self				,     lowercase__):
							__UpperCAmelCase			:							List[str]	    =	new_src_lang
							self.set_src_lang_special_tokens(self._src_lang)


	def  A(    self				,     lowercase__				,     lowercase__ = 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  A(    self				,     lowercase__				,     lowercase__ = None):
							__UpperCAmelCase			:							Optional[int]	    =	[self.sep_token_id]
							__UpperCAmelCase			:							int	    =	[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  A(    self				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     **lowercase__):
							if src_lang is None or tgt_lang is None:
													raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''')
							__UpperCAmelCase			:							Optional[Any]	    =	src_lang
							__UpperCAmelCase			:							Union[str, Any]	    =	self(lowercase__				,     add_special_tokens=lowercase__				,     return_tensors=lowercase__				,     **lowercase__)
							__UpperCAmelCase			:							int	    =	self.convert_tokens_to_ids(lowercase__)
							__UpperCAmelCase			:							Tuple	    =	tgt_lang_id
							return inputs


	def  A(    self				,     lowercase__				,     lowercase__ = "en_XX"				,     lowercase__ = None				,     lowercase__ = "ro_RO"				,     **lowercase__				,     ):
							__UpperCAmelCase			:							Any	    =	src_lang
							__UpperCAmelCase			:							Tuple	    =	tgt_lang
							return super().prepare_seqaseq_batch(lowercase__				,     lowercase__				,     **lowercase__)


	def  A(    self):
							return self.set_src_lang_special_tokens(self.src_lang)


	def  A(    self):
							return self.set_tgt_lang_special_tokens(self.tgt_lang)


	def  A(    self				,     lowercase__):
							__UpperCAmelCase			:							Optional[Any]	    =	self.convert_tokens_to_ids(lowercase__)
							__UpperCAmelCase			:							Union[str, Any]	    =	[]
							__UpperCAmelCase			:							Dict	    =	[self.eos_token_id, self.cur_lang_code]

							__UpperCAmelCase			:							int	    =	self.convert_ids_to_tokens(self.prefix_tokens)
							__UpperCAmelCase			:							Dict	    =	self.convert_ids_to_tokens(self.suffix_tokens)

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

							__UpperCAmelCase			:							Tuple	    =	self.convert_ids_to_tokens(self.prefix_tokens)
							__UpperCAmelCase			:							Tuple	    =	self.convert_ids_to_tokens(self.suffix_tokens)

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

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

							return (out_vocab_file,)

