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  (			lowerCAmelCase__   ):

	'''simple docstring'''



	def 	__UpperCAmelCase(  self       ):
			__A				:       str			    = tempfile.mkdtemp()
			__A				:       Any			    = 8

			# DPR tok
			__A				:       Optional[Any]			    = [
			    "[UNK]",
			    "[CLS]",
			    "[SEP]",
			    "[PAD]",
			    "[MASK]",
			    "want",
			    "##want",
			    "##ed",
			    "wa",
			    "un",
			    "runn",
			    "##ing",
			    ",",
			    "low",
			    "lowest",
			]
			__A				:       Tuple			    = os.path.join(self.tmpdirname				,					"dpr_tokenizer"       )
			os.makedirs(__UpperCAmelCase				,					exist_ok=__UpperCAmelCase       )
			__A				:       Optional[Any]			    = os.path.join(__UpperCAmelCase				,					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
			__A				:       int			    = [
			    "l",
			    "o",
			    "w",
			    "e",
			    "r",
			    "s",
			    "t",
			    "i",
			    "d",
			    "n",
			    "\u0120",
			    "\u0120l",
			    "\u0120n",
			    "\u0120lo",
			    "\u0120low",
			    "er",
			    "\u0120lowest",
			    "\u0120newer",
			    "\u0120wider",
			    "<unk>",
			]
			__A				:       List[Any]			    = dict(zip(__UpperCAmelCase				,					range(len(__UpperCAmelCase       )       )       )       )
			__A				:       int			    = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
			__A				:       str			    = {"unk_token": "<unk>"}

			__A				:       Optional[Any]			    = os.path.join(self.tmpdirname				,					"bart_tokenizer"       )
			os.makedirs(__UpperCAmelCase				,					exist_ok=__UpperCAmelCase       )
			__A				:       str			    = os.path.join(__UpperCAmelCase				,					BART_VOCAB_FILES_NAMES["vocab_file"]       )
			__A				:       List[Any]			    = os.path.join(__UpperCAmelCase				,					BART_VOCAB_FILES_NAMES["merges_file"]       )
			with open(self.vocab_file				,					"w"				,					encoding="utf-8"       ) as fp:
					fp.write(json.dumps(__UpperCAmelCase       ) + "\n"       )
			with open(self.merges_file				,					"w"				,					encoding="utf-8"       ) as fp:
					fp.write("\n".join(__UpperCAmelCase       )       )

	def 	__UpperCAmelCase(  self       ):
			return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname				,					"dpr_tokenizer"       )       )

	def 	__UpperCAmelCase(  self       ):
			return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname				,					"dpr_tokenizer"       )       )

	def 	__UpperCAmelCase(  self       ):
			return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname				,					"bart_tokenizer"       )       )

	def 	__UpperCAmelCase(  self       ):
			shutil.rmtree(self.tmpdirname       )

	def 	__UpperCAmelCase(  self       ):
			__A				:       List[str]			    = 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       ):
			__A				:       Union[str, Any]			    = self.get_dummy_dataset()
			__A				:       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:
					__A				:       int			    = dataset
					__A				:       Any			    = RagRetriever(
					    __UpperCAmelCase				,					question_encoder_tokenizer=self.get_dpr_tokenizer()				,					generator_tokenizer=self.get_bart_tokenizer()				,					)
			return retriever

	def 	__UpperCAmelCase(  self				,					__UpperCAmelCase       ):
			__A				:       str			    = self.get_dummy_dataset()
			__A				:       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:
					__A				:       Tuple			    = os.path.join(self.tmpdirname				,					"dataset"       )
					__A				:       str			    = 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
					__A				:       str			    = RagRetriever(
					    __UpperCAmelCase				,					question_encoder_tokenizer=self.get_dpr_tokenizer()				,					generator_tokenizer=self.get_bart_tokenizer()				,					)
			else:
					__A				:       Optional[int]			    = RagRetriever(
					    __UpperCAmelCase				,					question_encoder_tokenizer=self.get_dpr_tokenizer()				,					generator_tokenizer=self.get_bart_tokenizer()				,					index=CustomHFIndex(config.retrieval_vector_size				,					__UpperCAmelCase       )				,					)
			return retriever

	def 	__UpperCAmelCase(  self       ):
			__A				:       Optional[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       )

			__A				:       int			    = 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"       )       )

			__A				:       Dict			    = os.path.join(self.tmpdirname				,					"psgs_w100.tsv.pkl"       )
			__A				:       List[Any]			    = {sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
			pickle.dump(__UpperCAmelCase				,					open(__UpperCAmelCase				,					"wb"       )       )

			__A				:       Any			    = RagConfig(
			    retrieval_vector_size=self.retrieval_vector_size				,					question_encoder=DPRConfig().to_dict()				,					generator=BartConfig().to_dict()				,					index_name="legacy"				,					index_path=self.tmpdirname				,					)
			__A				:       str			    = RagRetriever(
			    __UpperCAmelCase				,					question_encoder_tokenizer=self.get_dpr_tokenizer()				,					generator_tokenizer=self.get_bart_tokenizer()       )
			return retriever

	def 	__UpperCAmelCase(  self       ):
			__A				:       Any			    = 1
			__A				:       List[str]			    = self.get_dummy_canonical_hf_index_retriever()
			__A				:       Any			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A    ,  __A    ,  __A				:       List[Any]			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=__UpperCAmelCase       )
			self.assertEqual(retrieved_doc_embeds.shape				,					(2, n_docs, self.retrieval_vector_size)       )
			self.assertEqual(len(__UpperCAmelCase       )				,					2       )
			self.assertEqual(sorted(doc_dicts[0]       )				,					["embeddings", "id", "text", "title"]       )
			self.assertEqual(len(doc_dicts[0]["id"]       )				,					__UpperCAmelCase       )
			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       ):
			__A				:       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:
							__A				:       List[str]			    = self.get_dummy_dataset()
							retriever.save_pretrained(__UpperCAmelCase       )
							__A				:       str			    = RagRetriever.from_pretrained(__UpperCAmelCase       )
							self.assertIsInstance(__UpperCAmelCase				,					__UpperCAmelCase       )
							__A				:       Any			    = np.array(
							    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
							__A				:       str			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=1       )
							self.assertTrue(out is not None       )

	def 	__UpperCAmelCase(  self       ):
			__A				:       Optional[int]			    = 1
			__A				:       Dict			    = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase       )
			__A				:       Union[str, Any]			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A    ,  __A    ,  __A				:       Dict			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=__UpperCAmelCase       )
			self.assertEqual(retrieved_doc_embeds.shape				,					(2, n_docs, self.retrieval_vector_size)       )
			self.assertEqual(len(__UpperCAmelCase       )				,					2       )
			self.assertEqual(sorted(doc_dicts[0]       )				,					["embeddings", "id", "text", "title"]       )
			self.assertEqual(len(doc_dicts[0]["id"]       )				,					__UpperCAmelCase       )
			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       ):
			__A				:       Any			    = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase       )
			with tempfile.TemporaryDirectory() as tmp_dirname:
					retriever.save_pretrained(__UpperCAmelCase       )
					__A				:       Optional[Any]			    = RagRetriever.from_pretrained(__UpperCAmelCase       )
					self.assertIsInstance(__UpperCAmelCase				,					__UpperCAmelCase       )
					__A				:       Union[str, Any]			    = np.array(
					    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
					__A				:       List[str]			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=1       )
					self.assertTrue(out is not None       )

	def 	__UpperCAmelCase(  self       ):
			__A				:       Tuple			    = 1
			__A				:       Tuple			    = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase       )
			__A				:       Optional[Any]			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A    ,  __A    ,  __A				:       List[Any]			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=__UpperCAmelCase       )
			self.assertEqual(retrieved_doc_embeds.shape				,					(2, n_docs, self.retrieval_vector_size)       )
			self.assertEqual(len(__UpperCAmelCase       )				,					2       )
			self.assertEqual(sorted(doc_dicts[0]       )				,					["embeddings", "id", "text", "title"]       )
			self.assertEqual(len(doc_dicts[0]["id"]       )				,					__UpperCAmelCase       )
			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       ):
			__A				:       Union[str, Any]			    = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase       )
			with tempfile.TemporaryDirectory() as tmp_dirname:
					retriever.save_pretrained(__UpperCAmelCase       )
					__A				:       int			    = RagRetriever.from_pretrained(__UpperCAmelCase       )
					self.assertIsInstance(__UpperCAmelCase				,					__UpperCAmelCase       )
					__A				:       Union[str, Any]			    = np.array(
					    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
					__A				:       List[str]			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=1       )
					self.assertTrue(out is not None       )

	def 	__UpperCAmelCase(  self       ):
			__A				:       Optional[int]			    = 1
			__A				:       List[Any]			    = self.get_dummy_legacy_index_retriever()
			__A				:       Tuple			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A    ,  __A    ,  __A				:       Any			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=__UpperCAmelCase       )
			self.assertEqual(retrieved_doc_embeds.shape				,					(2, n_docs, self.retrieval_vector_size)       )
			self.assertEqual(len(__UpperCAmelCase       )				,					2       )
			self.assertEqual(sorted(doc_dicts[0]       )				,					["text", "title"]       )
			self.assertEqual(len(doc_dicts[0]["text"]       )				,					__UpperCAmelCase       )
			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       ):
			__A				:       Dict			    = self.get_dummy_legacy_index_retriever()
			with tempfile.TemporaryDirectory() as tmp_dirname:
					retriever.save_pretrained(__UpperCAmelCase       )
					__A				:       List[str]			    = RagRetriever.from_pretrained(__UpperCAmelCase       )
					self.assertIsInstance(__UpperCAmelCase				,					__UpperCAmelCase       )
					__A				:       List[str]			    = np.array(
					    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
					__A				:       int			    = retriever.retrieve(__UpperCAmelCase				,					n_docs=1       )
					self.assertTrue(out is not None       )

	@require_torch
	@require_tokenizers
	@require_sentencepiece
	def 	__UpperCAmelCase(  self       ):
			import torch

			__A				:       Optional[int]			    = 1
			__A				:       Optional[int]			    = self.get_dummy_canonical_hf_index_retriever()
			__A				:       List[str]			    = [[5, 7], [10, 11]]
			__A				:       Union[str, Any]			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A				:       Union[str, Any]			    = retriever(__UpperCAmelCase				,					__UpperCAmelCase				,					prefix=retriever.config.generator.prefix				,					n_docs=__UpperCAmelCase       )
			__A    ,  __A    ,  __A				:       Union[str, Any]			    = (
			    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(__UpperCAmelCase				,					__UpperCAmelCase       )
			self.assertIsInstance(__UpperCAmelCase				,					__UpperCAmelCase       )
			self.assertIsInstance(__UpperCAmelCase				,					np.ndarray       )

			__A				:       str			    = retriever(
			    __UpperCAmelCase				,					__UpperCAmelCase				,					prefix=retriever.config.generator.prefix				,					n_docs=__UpperCAmelCase				,					return_tensors="pt"				,					)
			__A    ,  __A    ,  __A    ,  __A				:       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(__UpperCAmelCase				,					torch.Tensor       )
			self.assertIsInstance(__UpperCAmelCase				,					torch.Tensor       )
			self.assertIsInstance(__UpperCAmelCase				,					torch.Tensor       )







	@require_torch
	@require_tokenizers
	@require_sentencepiece
	def 	__UpperCAmelCase(  self       ):
			__A				:       Optional[int]			    = self.get_dpr_ctx_encoder_tokenizer()
			__A				:       Optional[Any]			    = 1
			__A				:       Optional[Any]			    = self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase       )
			retriever.set_ctx_encoder_tokenizer(__UpperCAmelCase       )

			__A				:       List[str]			    = [[5, 7], [10, 11]]
			__A				:       Any			    = np.array(
			    [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]				,					dtype=np.floataa       )
			__A				:       Any			    = retriever(__UpperCAmelCase				,					__UpperCAmelCase				,					prefix=retriever.config.generator.prefix				,					n_docs=__UpperCAmelCase       )

			self.assertEqual(
			    len(__UpperCAmelCase       )				,					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")       )				,					__UpperCAmelCase       )  # check for doc token related keys in dictionary.










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

import sentencepiece as spm

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


a__   :					Optional[int] 						=      logging.get_logger(__name__)
a__   :					Dict 						=      {"vocab_file": "spiece.model"}

a__   :					str 						=      {
    "vocab_file": {
        "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model",
        "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model",
        "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model",
        "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model",
        "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model",
        "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model",
        "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model",
        "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model",
    }
}

a__   :					Union[str, Any] 						=      {
    "albert-base-v1": 5_12,
    "albert-large-v1": 5_12,
    "albert-xlarge-v1": 5_12,
    "albert-xxlarge-v1": 5_12,
    "albert-base-v2": 5_12,
    "albert-large-v2": 5_12,
    "albert-xlarge-v2": 5_12,
    "albert-xxlarge-v2": 5_12,
}

a__   :					Optional[int] 						=      "▁"



class    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   A     :	Tuple												=     VOCAB_FILES_NAMES
   A     :	Dict												=     PRETRAINED_VOCAB_FILES_MAP
   A     :	str												=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES


   def __init__(    self	:      List[str]      ,					lowerCAmelCase	:      Tuple      ,					lowerCAmelCase	:      Optional[int]=True      ,					lowerCAmelCase	:      List[Any]=True      ,					lowerCAmelCase	:      str=False      ,					lowerCAmelCase	:      str="[CLS]"      ,					lowerCAmelCase	:      Optional[int]="[SEP]"      ,					lowerCAmelCase	:      int="<unk>"      ,					lowerCAmelCase	:      str="[SEP]"      ,					lowerCAmelCase	:      Dict="<pad>"      ,					lowerCAmelCase	:      int="[CLS]"      ,					lowerCAmelCase	:      Tuple="[MASK]"      ,					lowerCAmelCase	:      Optional[Dict[str, Any]] = None      ,					**lowerCAmelCase	:      List[str]      ,					)						->					None:




         """simple docstring"""

         lowercase__  =	(
             AddedToken(lowerCAmelCase      ,					lstrip=lowerCAmelCase      ,					rstrip=lowerCAmelCase      ,					normalized=lowerCAmelCase)
             if isinstance(lowerCAmelCase      ,					lowerCAmelCase)
             else mask_token
         )

         lowercase__  =	{} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             do_lower_case=lowerCAmelCase      ,					remove_space=lowerCAmelCase      ,					keep_accents=lowerCAmelCase      ,					bos_token=lowerCAmelCase      ,					eos_token=lowerCAmelCase      ,					unk_token=lowerCAmelCase      ,					sep_token=lowerCAmelCase      ,					pad_token=lowerCAmelCase      ,					cls_token=lowerCAmelCase      ,					mask_token=lowerCAmelCase      ,					sp_model_kwargs=self.sp_model_kwargs      ,					**lowerCAmelCase      ,					)

         lowercase__  =	do_lower_case
         lowercase__  =	remove_space
         lowercase__  =	keep_accents
         lowercase__  =	vocab_file

         lowercase__  =	spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(lowerCAmelCase)


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




         """simple docstring"""

         return len(self.sp_model)


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




         """simple docstring"""

         lowercase__  =	{self.convert_ids_to_tokens(lowerCAmelCase): i for i in range(self.vocab_size)}
         vocab.update(self.added_tokens_encoder)
         return vocab


   def __getstate__(    self	:      int)						->					List[str]:




         """simple docstring"""

         lowercase__  =	self.__dict__.copy()
         lowercase__  =	None
         return state


   def __setstate__(    self	:      int      ,					lowerCAmelCase	:      str)						->					Any:




         """simple docstring"""

         lowercase__  =	d

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

         lowercase__  =	spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(self.vocab_file)


   def       UpperCAmelCase		(    self	:      Dict      ,					lowerCAmelCase	:      int)						->					List[str]:




         """simple docstring"""

         if self.remove_space:
               lowercase__  =	' '.join(inputs.strip().split())
         else:
               lowercase__  =	inputs
         lowercase__  =	outputs.replace('``'      ,					'"').replace('\'\''      ,					'"')

         if not self.keep_accents:
               lowercase__  =	unicodedata.normalize('NFKD'      ,					lowerCAmelCase)
               lowercase__  =	''.join([c for c in outputs if not unicodedata.combining(lowerCAmelCase)])
         if self.do_lower_case:
               lowercase__  =	outputs.lower()

         return outputs


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




         """simple docstring"""

         lowercase__  =	self.preprocess_text(lowerCAmelCase)
         lowercase__  =	self.sp_model.encode(lowerCAmelCase      ,					out_type=lowerCAmelCase)
         lowercase__  =	[]
         for piece in pieces:
               if len(lowerCAmelCase) > 1 and piece[-1] == str(',') and piece[-2].isdigit():
                     lowercase__  =	self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCAmelCase      ,					''))
                     if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                           if len(cur_pieces[0]) == 1:
                                 lowercase__  =	cur_pieces[1:]
                           else:
                                 lowercase__  =	cur_pieces[0][1:]
                     cur_pieces.append(piece[-1])
                     new_pieces.extend(lowerCAmelCase)
               else:
                     new_pieces.append(lowerCAmelCase)

         return new_pieces


   def       UpperCAmelCase		(    self	:      Any      ,					lowerCAmelCase	:      int)						->					int:




         """simple docstring"""

         return self.sp_model.PieceToId(lowerCAmelCase)


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




         """simple docstring"""

         return self.sp_model.IdToPiece(lowerCAmelCase)


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




         """simple docstring"""

         lowercase__  =	[]
         lowercase__  =	''
         lowercase__  =	False
         for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                     if not prev_is_special:
                           out_string += " "
                     out_string += self.sp_model.decode(lowerCAmelCase) + token
                     lowercase__  =	True
                     lowercase__  =	[]
               else:
                     current_sub_tokens.append(lowerCAmelCase)
                     lowercase__  =	False
         out_string += self.sp_model.decode(lowerCAmelCase)
         return out_string.strip()


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




         """simple docstring"""

         lowercase__  =	[self.sep_token_id]
         lowercase__  =	[self.cls_token_id]
         if token_ids_a is None:
               return cls + token_ids_a + sep
         return cls + token_ids_a + sep + token_ids_a + sep


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




         """simple docstring"""

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

         if token_ids_a is not None:
               return [1] + ([0] * len(lowerCAmelCase)) + [1] + ([0] * len(lowerCAmelCase)) + [1]
         return [1] + ([0] * len(lowerCAmelCase)) + [1]


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




         """simple docstring"""

         lowercase__  =	[self.sep_token_id]
         lowercase__  =	[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) * [0] + len(token_ids_a + sep) * [1]



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




         """simple docstring"""

         if not os.path.isdir(lowerCAmelCase):
               logger.error(f'''Vocabulary path ({save_directory}) should be a directory''')
               return
         lowercase__  =	os.path.join(
             lowerCAmelCase      ,					(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])

         if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCAmelCase) and os.path.isfile(self.vocab_file):
               copyfile(self.vocab_file      ,					lowerCAmelCase)
         elif not os.path.isfile(self.vocab_file):
               with open(lowerCAmelCase      ,					'wb') as fi:
                     lowercase__  =	self.sp_model.serialized_model_proto()
                     fi.write(lowerCAmelCase)

         return (out_vocab_file,)
