



"""simple docstring"""







import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
							import faiss
@require_faiss
class        __A       (	A_    ):







		'''simple docstring'''





		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		str:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			tempfile.mkdtemp()
				lowercase__   :    Tuple				=			8

				# DPR tok
				lowercase__   :    Optional[int]				=			[
				    '''[UNK]''',
				    '''[CLS]''',
				    '''[SEP]''',
				    '''[PAD]''',
				    '''[MASK]''',
				    '''want''',
				    '''##want''',
				    '''##ed''',
				    '''wa''',
				    '''un''',
				    '''runn''',
				    '''##ing''',
				    ''',''',
				    '''low''',
				    '''lowest''',
				]
				lowercase__   :    List[Any]				=			os.path.join(self.tmpdirname			,'''dpr_tokenizer'''						)
				os.makedirs(_snake_case			,exist_ok=_snake_case						)
				lowercase__   :    Dict				=			os.path.join(_snake_case			,DPR_VOCAB_FILES_NAMES['''vocab_file''']						)
				with open(self.vocab_file			,'''w'''			,encoding='''utf-8'''						) as vocab_writer:
						vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]						)						)

				# BART tok
				lowercase__   :    List[str]				=			[
				    '''l''',
				    '''o''',
				    '''w''',
				    '''e''',
				    '''r''',
				    '''s''',
				    '''t''',
				    '''i''',
				    '''d''',
				    '''n''',
				    '''\u0120''',
				    '''\u0120l''',
				    '''\u0120n''',
				    '''\u0120lo''',
				    '''\u0120low''',
				    '''er''',
				    '''\u0120lowest''',
				    '''\u0120newer''',
				    '''\u0120wider''',
				    '''<unk>''',
				]
				lowercase__   :    Union[str, Any]				=			dict(zip(_snake_case			,range(len(_snake_case						)						)						)						)
				lowercase__   :    Dict				=			['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
				lowercase__   :    List[Any]				=			{'''unk_token''': '''<unk>'''}

				lowercase__   :    Optional[int]				=			os.path.join(self.tmpdirname			,'''bart_tokenizer'''						)
				os.makedirs(_snake_case			,exist_ok=_snake_case						)
				lowercase__   :    Optional[Any]				=			os.path.join(_snake_case			,BART_VOCAB_FILES_NAMES['''vocab_file''']						)
				lowercase__   :    Dict				=			os.path.join(_snake_case			,BART_VOCAB_FILES_NAMES['''merges_file''']						)
				with open(self.vocab_file			,'''w'''			,encoding='''utf-8'''						) as fp:
						fp.write(json.dumps(_snake_case						) + '''\n'''						)
				with open(self.merges_file			,'''w'''			,encoding='''utf-8'''						) as fp:
						fp.write('''\n'''.join(_snake_case						)						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		DPRQuestionEncoderTokenizer:






				"""simple docstring"""



				return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname			,'''dpr_tokenizer'''						)						)







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		DPRContextEncoderTokenizer:






				"""simple docstring"""



				return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname			,'''dpr_tokenizer'''						)						)







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		BartTokenizer:






				"""simple docstring"""



				return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname			,'''bart_tokenizer'''						)						)







		def 					UpperCAmelCase    (	self						:  Any						)					->		List[Any]:






				"""simple docstring"""



				shutil.rmtree(self.tmpdirname						)







		def 					UpperCAmelCase    (	self						:  str						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Any				=			Dataset.from_dict(
				    {
				        '''id''': ['''0''', '''1'''],
				        '''text''': ['''foo''', '''bar'''],
				        '''title''': ['''Foo''', '''Bar'''],
				        '''embeddings''': [np.ones(self.retrieval_vector_size						), 2 * np.ones(self.retrieval_vector_size						)],
				    }						)
				dataset.add_faiss_index('''embeddings'''			,string_factory='''Flat'''			,metric_type=faiss.METRIC_INNER_PRODUCT						)
				return dataset







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    int				=			self.get_dummy_dataset()
				lowercase__   :    Dict				=			RagConfig(
				    retrieval_vector_size=self.retrieval_vector_size			,question_encoder=DPRConfig().to_dict()			,generator=BartConfig().to_dict()			,)
				with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
						lowercase__   :    str				=			dataset
						lowercase__   :    List[Any]				=			RagRetriever(
						    _snake_case			,question_encoder_tokenizer=self.get_dpr_tokenizer()			,generator_tokenizer=self.get_bart_tokenizer()			,)
				return retriever







		def 					UpperCAmelCase    (	self						:  int			,_snake_case						:  bool						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			self.get_dummy_dataset()
				lowercase__   :    Optional[int]				=			RagConfig(
				    retrieval_vector_size=self.retrieval_vector_size			,question_encoder=DPRConfig().to_dict()			,generator=BartConfig().to_dict()			,index_name='''custom'''			,)
				if from_disk:
						lowercase__   :    List[str]				=			os.path.join(self.tmpdirname			,'''dataset'''						)
						lowercase__   :    Any				=			os.path.join(self.tmpdirname			,'''index.faiss'''						)
						dataset.get_index('''embeddings'''						).save(os.path.join(self.tmpdirname			,'''index.faiss'''						)						)
						dataset.drop_index('''embeddings'''						)
						dataset.save_to_disk(os.path.join(self.tmpdirname			,'''dataset'''						)						)
						del dataset
						lowercase__   :    List[str]				=			RagRetriever(
						    _snake_case			,question_encoder_tokenizer=self.get_dpr_tokenizer()			,generator_tokenizer=self.get_bart_tokenizer()			,)
				else:
						lowercase__   :    str				=			RagRetriever(
						    _snake_case			,question_encoder_tokenizer=self.get_dpr_tokenizer()			,generator_tokenizer=self.get_bart_tokenizer()			,index=CustomHFIndex(config.retrieval_vector_size			,_snake_case						)			,)
				return retriever







		def 					UpperCAmelCase    (	self						:  Dict						)					->		int:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			Dataset.from_dict(
				    {
				        '''id''': ['''0''', '''1'''],
				        '''text''': ['''foo''', '''bar'''],
				        '''title''': ['''Foo''', '''Bar'''],
				        '''embeddings''': [np.ones(self.retrieval_vector_size + 1						), 2 * np.ones(self.retrieval_vector_size + 1						)],
				    }						)
				dataset.add_faiss_index('''embeddings'''			,string_factory='''Flat'''			,metric_type=faiss.METRIC_INNER_PRODUCT						)

				lowercase__   :    str				=			os.path.join(self.tmpdirname			,'''hf_bert_base.hnswSQ8_correct_phi_128.c_index'''						)
				dataset.save_faiss_index('''embeddings'''			,index_file_name + '''.index.dpr'''						)
				pickle.dump(dataset['''id''']			,open(index_file_name + '''.index_meta.dpr'''			,'''wb'''						)						)

				lowercase__   :    Union[str, Any]				=			os.path.join(self.tmpdirname			,'''psgs_w100.tsv.pkl'''						)
				lowercase__   :    Optional[Any]				=			{sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset}
				pickle.dump(_snake_case			,open(_snake_case			,'''wb'''						)						)

				lowercase__   :    Dict				=			RagConfig(
				    retrieval_vector_size=self.retrieval_vector_size			,question_encoder=DPRConfig().to_dict()			,generator=BartConfig().to_dict()			,index_name='''legacy'''			,index_path=self.tmpdirname			,)
				lowercase__   :    List[str]				=			RagRetriever(
				    _snake_case			,question_encoder_tokenizer=self.get_dpr_tokenizer()			,generator_tokenizer=self.get_bart_tokenizer()						)
				return retriever







		def 					UpperCAmelCase    (	self						:  Dict						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Dict				=			1
				lowercase__   :    Tuple				=			self.get_dummy_canonical_hf_index_retriever()
				lowercase__   :    Dict				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__		,			lowercase__		,			lowercase__   :    Union[str, Any]				=			retriever.retrieve(_snake_case			,n_docs=_snake_case						)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertEqual(len(_snake_case						)			,2						)
				self.assertEqual(sorted(doc_dicts[0]						)			,['''embeddings''', '''id''', '''text''', '''title''']						)
				self.assertEqual(len(doc_dicts[0]['''id''']						)			,_snake_case						)
				self.assertEqual(doc_dicts[0]['''id'''][0]			,'''1'''						)  # max inner product is reached with second doc
				self.assertEqual(doc_dicts[1]['''id'''][0]			,'''0'''						)  # max inner product is reached with first doc
				self.assertListEqual(doc_ids.tolist()			,[[1], [0]]						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    int				=			self.get_dummy_canonical_hf_index_retriever()
				with tempfile.TemporaryDirectory() as tmp_dirname:
						with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
								lowercase__   :    Optional[Any]				=			self.get_dummy_dataset()
								retriever.save_pretrained(_snake_case						)
								lowercase__   :    Optional[int]				=			RagRetriever.from_pretrained(_snake_case						)
								self.assertIsInstance(_snake_case			,_snake_case						)
								lowercase__   :    Dict				=			np.array(
								    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
								lowercase__   :    int				=			retriever.retrieve(_snake_case			,n_docs=1						)
								self.assertTrue(out is not None						)







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Optional[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			1
				lowercase__   :    str				=			self.get_dummy_custom_hf_index_retriever(from_disk=_snake_case						)
				lowercase__   :    int				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__		,			lowercase__		,			lowercase__   :    Dict				=			retriever.retrieve(_snake_case			,n_docs=_snake_case						)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertEqual(len(_snake_case						)			,2						)
				self.assertEqual(sorted(doc_dicts[0]						)			,['''embeddings''', '''id''', '''text''', '''title''']						)
				self.assertEqual(len(doc_dicts[0]['''id''']						)			,_snake_case						)
				self.assertEqual(doc_dicts[0]['''id'''][0]			,'''1'''						)  # max inner product is reached with second doc
				self.assertEqual(doc_dicts[1]['''id'''][0]			,'''0'''						)  # max inner product is reached with first doc
				self.assertListEqual(doc_ids.tolist()			,[[1], [0]]						)







		def 					UpperCAmelCase    (	self						:  str						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			self.get_dummy_custom_hf_index_retriever(from_disk=_snake_case						)
				with tempfile.TemporaryDirectory() as tmp_dirname:
						retriever.save_pretrained(_snake_case						)
						lowercase__   :    Optional[int]				=			RagRetriever.from_pretrained(_snake_case						)
						self.assertIsInstance(_snake_case			,_snake_case						)
						lowercase__   :    Dict				=			np.array(
						    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
						lowercase__   :    str				=			retriever.retrieve(_snake_case			,n_docs=1						)
						self.assertTrue(out is not None						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[Any]:






				"""simple docstring"""



				lowercase__   :    Any				=			1
				lowercase__   :    List[str]				=			self.get_dummy_custom_hf_index_retriever(from_disk=_snake_case						)
				lowercase__   :    Optional[int]				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__		,			lowercase__		,			lowercase__   :    List[str]				=			retriever.retrieve(_snake_case			,n_docs=_snake_case						)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertEqual(len(_snake_case						)			,2						)
				self.assertEqual(sorted(doc_dicts[0]						)			,['''embeddings''', '''id''', '''text''', '''title''']						)
				self.assertEqual(len(doc_dicts[0]['''id''']						)			,_snake_case						)
				self.assertEqual(doc_dicts[0]['''id'''][0]			,'''1'''						)  # max inner product is reached with second doc
				self.assertEqual(doc_dicts[1]['''id'''][0]			,'''0'''						)  # max inner product is reached with first doc
				self.assertListEqual(doc_ids.tolist()			,[[1], [0]]						)







		def 					UpperCAmelCase    (	self						:  str						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    Any				=			self.get_dummy_custom_hf_index_retriever(from_disk=_snake_case						)
				with tempfile.TemporaryDirectory() as tmp_dirname:
						retriever.save_pretrained(_snake_case						)
						lowercase__   :    Optional[int]				=			RagRetriever.from_pretrained(_snake_case						)
						self.assertIsInstance(_snake_case			,_snake_case						)
						lowercase__   :    List[str]				=			np.array(
						    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
						lowercase__   :    int				=			retriever.retrieve(_snake_case			,n_docs=1						)
						self.assertTrue(out is not None						)







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    str				=			1
				lowercase__   :    Dict				=			self.get_dummy_legacy_index_retriever()
				lowercase__   :    str				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__		,			lowercase__		,			lowercase__   :    int				=			retriever.retrieve(_snake_case			,n_docs=_snake_case						)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertEqual(len(_snake_case						)			,2						)
				self.assertEqual(sorted(doc_dicts[0]						)			,['''text''', '''title''']						)
				self.assertEqual(len(doc_dicts[0]['''text''']						)			,_snake_case						)
				self.assertEqual(doc_dicts[0]['''text'''][0]			,'''bar'''						)  # max inner product is reached with second doc
				self.assertEqual(doc_dicts[1]['''text'''][0]			,'''foo'''						)  # max inner product is reached with first doc
				self.assertListEqual(doc_ids.tolist()			,[[1], [0]]						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		int:






				"""simple docstring"""



				lowercase__   :    Dict				=			self.get_dummy_legacy_index_retriever()
				with tempfile.TemporaryDirectory() as tmp_dirname:
						retriever.save_pretrained(_snake_case						)
						lowercase__   :    Optional[int]				=			RagRetriever.from_pretrained(_snake_case						)
						self.assertIsInstance(_snake_case			,_snake_case						)
						lowercase__   :    Union[str, Any]				=			np.array(
						    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
						lowercase__   :    Dict				=			retriever.retrieve(_snake_case			,n_docs=1						)
						self.assertTrue(out is not None						)







		@require_torch
		@require_tokenizers
		@require_sentencepiece
		def 					UpperCAmelCase    (	self						:  List[str]						)					->		List[str]:






				"""simple docstring"""



				import torch

				lowercase__   :    int				=			1
				lowercase__   :    Tuple				=			self.get_dummy_canonical_hf_index_retriever()
				lowercase__   :    Union[str, Any]				=			[[5, 7], [10, 11]]
				lowercase__   :    str				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__   :    Tuple				=			retriever(_snake_case			,_snake_case			,prefix=retriever.config.generator.prefix			,n_docs=_snake_case						)
				lowercase__		,			lowercase__		,			lowercase__   :    int				=			(
				    out['''context_input_ids'''],
				    out['''context_attention_mask'''],
				    out['''retrieved_doc_embeds'''],
				)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertIsInstance(_snake_case			,_snake_case						)
				self.assertIsInstance(_snake_case			,_snake_case						)
				self.assertIsInstance(_snake_case			,np.ndarray						)

				lowercase__   :    Optional[Any]				=			retriever(
				    _snake_case			,_snake_case			,prefix=retriever.config.generator.prefix			,n_docs=_snake_case			,return_tensors='''pt'''			,)
				lowercase__		,			lowercase__		,			lowercase__		,			lowercase__   :    Tuple				=			(  # noqa: F841
				    out['''context_input_ids'''],
				    out['''context_attention_mask'''],
				    out['''retrieved_doc_embeds'''],
				    out['''doc_ids'''],
				)
				self.assertEqual(retrieved_doc_embeds.shape			,(2, n_docs, self.retrieval_vector_size)						)
				self.assertIsInstance(_snake_case			,torch.Tensor						)
				self.assertIsInstance(_snake_case			,torch.Tensor						)
				self.assertIsInstance(_snake_case			,torch.Tensor						)







		@require_torch
		@require_tokenizers
		@require_sentencepiece
		def 					UpperCAmelCase    (	self						:  Dict						)					->		int:






				"""simple docstring"""



				lowercase__   :    List[str]				=			self.get_dpr_ctx_encoder_tokenizer()
				lowercase__   :    Dict				=			1
				lowercase__   :    str				=			self.get_dummy_custom_hf_index_retriever(from_disk=_snake_case						)
				retriever.set_ctx_encoder_tokenizer(_snake_case						)

				lowercase__   :    Any				=			[[5, 7], [10, 11]]
				lowercase__   :    Dict				=			np.array(
				    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]			,dtype=np.floataa						)
				lowercase__   :    Union[str, Any]				=			retriever(_snake_case			,_snake_case			,prefix=retriever.config.generator.prefix			,n_docs=_snake_case						)

				self.assertEqual(
				    len(_snake_case						)			,6						)  # check whether the retriever output consist of 6 attributes including tokenized docs
				self.assertEqual(
				    all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''')						)			,_snake_case						)  # check for doc token related keys in dictionary.





"""simple docstring"""







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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowerCAmelCase_   						=   logging.get_logger(__name__)

lowerCAmelCase_   						=   '▁'

lowerCAmelCase_   						=   {'vocab_file': 'sentencepiece.bpe.model'}

lowerCAmelCase_   						=   {
    'vocab_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model',
    }
}

lowerCAmelCase_   						=   {
    'facebook/xglm-564M': 2_048,
}
class        __A       (	A_    ):







		'''simple docstring'''





		lowerCAmelCase			:					List[Any]   	=				VOCAB_FILES_NAMES
		lowerCAmelCase			:					Any   	=				PRETRAINED_VOCAB_FILES_MAP
		lowerCAmelCase			:					str   	=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		lowerCAmelCase			:					int   	=				["input_ids", "attention_mask"]







		def __init__(	self						:  int			,_snake_case						:  Dict			,_snake_case						:  Dict="<s>"			,_snake_case						:  Dict="</s>"			,_snake_case						:  str="</s>"			,_snake_case						:  Optional[Any]="<s>"			,_snake_case						:  Optional[Any]="<unk>"			,_snake_case						:  Optional[int]="<pad>"			,_snake_case						:  Optional[Dict[str, Any]] = None			,**_snake_case						:  str			,)					->		None:






				"""simple docstring"""



				lowercase__   :    Any				=			{} if sp_model_kwargs is None else sp_model_kwargs

				# Compatibility with the original tokenizer
				lowercase__   :    Any				=			7
				lowercase__   :    Optional[int]				=			[f"""<madeupword{i}>""" for i in range(self.num_madeup_words						)]

				lowercase__   :    Dict				=			kwargs.get('''additional_special_tokens'''			,[]						)
				kwargs["additional_special_tokens"] += [
				    word for word in madeup_words if word not in kwargs["additional_special_tokens"]
				]

				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			,sp_model_kwargs=self.sp_model_kwargs			,**_snake_case			,)

				lowercase__   :    List[str]				=			spm.SentencePieceProcessor(**self.sp_model_kwargs						)
				self.sp_model.Load(str(_snake_case						)						)
				lowercase__   :    str				=			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'

				# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
				lowercase__   :    Optional[int]				=			1

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

				lowercase__   :    List[str]				=			len(self.sp_model						)
				lowercase__   :    Tuple				=			{f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words						)}
				self.fairseq_tokens_to_ids.update(_snake_case						)

				lowercase__   :    Union[str, Any]				=			{v: k for k, v in self.fairseq_tokens_to_ids.items()}







		def __getstate__(	self						:  int						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			self.__dict__.copy()
				lowercase__   :    Optional[int]				=			None
				lowercase__   :    Any				=			self.sp_model.serialized_model_proto()
				return state







		def __setstate__(	self						:  Dict			,_snake_case						:  List[str]						)					->		Any:






				"""simple docstring"""



				lowercase__   :    int				=			d

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

				lowercase__   :    Optional[int]				=			spm.SentencePieceProcessor(**self.sp_model_kwargs						)
				self.sp_model.LoadFromSerializedProto(self.sp_model_proto						)







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  List[int]			,_snake_case						:  Optional[List[int]] = None						)					->		List[int]:






				"""simple docstring"""



				if token_ids_a is None:
						return [self.sep_token_id] + token_ids_a
				lowercase__   :    Optional[Any]				=			[self.sep_token_id]
				return sep + token_ids_a + sep + sep + token_ids_a







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  List[int]			,_snake_case						:  Optional[List[int]] = None			,_snake_case						:  bool = False						)					->		List[int]:






				"""simple docstring"""



				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						)

				if token_ids_a is None:
						return [1] + ([0] * len(_snake_case						))
				return [1] + ([0] * len(_snake_case						)) + [1, 1] + ([0] * len(_snake_case						))







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  List[int]			,_snake_case						:  Optional[List[int]] = None						)					->		List[int]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			[self.sep_token_id]

				if token_ids_a is None:
						return len(sep + token_ids_a						) * [0]
				return len(sep + token_ids_a + sep + sep + token_ids_a						) * [0]







		@property
		def 					UpperCAmelCase    (	self						:  str						)					->		Tuple:






				"""simple docstring"""



				return len(self.sp_model						) + self.fairseq_offset + self.num_madeup_words







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Optional[Any]:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			{self.convert_ids_to_tokens(_snake_case						): i for i in range(self.vocab_size						)}
				vocab.update(self.added_tokens_encoder						)
				return vocab







		def 					UpperCAmelCase    (	self						:  List[Any]			,_snake_case						:  str						)					->		List[str]:






				"""simple docstring"""



				return self.sp_model.encode(_snake_case			,out_type=_snake_case						)







		def 					UpperCAmelCase    (	self						:  int			,_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				if token in self.fairseq_tokens_to_ids:
						return self.fairseq_tokens_to_ids[token]
				lowercase__   :    Tuple				=			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 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  List[str]						)					->		Any:






				"""simple docstring"""



				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 					UpperCAmelCase    (	self						:  Tuple			,_snake_case						:  Tuple						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			''''''.join(_snake_case						).replace(_snake_case			,''' '''						).strip()
				return out_string







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  str			,_snake_case						:  Optional[str] = None						)					->		Tuple[str]:






				"""simple docstring"""



				if not os.path.isdir(_snake_case						):
						logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""						)
						return
				lowercase__   :    Any				=			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__   :    Dict				=			self.sp_model.serialized_model_proto()
								fi.write(_snake_case						)

				return (out_vocab_file,)
