
import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
				import torch

				from ..models.auto.modeling_auto import (
				    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
				    MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
				)

if is_tf_available() and is_tensorflow_probability_available():
				import tensorflow as tf
				import tensorflow_probability as tfp

				from ..models.auto.modeling_tf_auto import (
				    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
				    TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
				)






class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							def __call__(					self       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		**SCREAMING_SNAKE_CASE_     )->				Any:





													'''simple docstring'''






													requires_backends(self       ,		'''pandas'''     )
													import pandas as pd

													if table is None:
																			raise ValueError('''Keyword argument `table` cannot be None.'''     )
													elif query is None:
																			if isinstance(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     ) and table.get('''query'''     ) is not None and table.get('''table'''     ) is not None:
																									__UpperCamelCase       					=     [table]
																			elif isinstance(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     ) and len(SCREAMING_SNAKE_CASE_     ) > 0:
																									if not all(isinstance(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     ) for d in table     ):
																															raise ValueError(
																															    F"Keyword argument `table` should be a list of dict, but is {(type(SCREAMING_SNAKE_CASE_     ) for d in table)}"     )

																									if table[0].get('''query'''     ) is not None and table[0].get('''table'''     ) is not None:
																															__UpperCamelCase       					=     table
																									else:
																															raise ValueError(
																															    '''If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`'''
																															    F" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."     )
																			elif Dataset is not None and isinstance(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     ) or isinstance(SCREAMING_SNAKE_CASE_       ,		types.GeneratorType     ):
																									return table
																			else:
																									raise ValueError(
																									    '''Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but '''
																									    F"is {type(SCREAMING_SNAKE_CASE_     )})"     )
													else:
																			__UpperCamelCase       					=     [{'''table''': table, '''query''': query}]

													for tqa_pipeline_input in tqa_pipeline_inputs:
																			if not isinstance(tqa_pipeline_input['''table''']       ,		pd.DataFrame     ):
																									if tqa_pipeline_input["table"] is None:
																															raise ValueError('''Table cannot be None.'''     )

																									__UpperCamelCase       					=     pd.DataFrame(tqa_pipeline_input['''table''']     )

													return tqa_pipeline_inputs






@add_end_docstrings(SCREAMING_SNAKE_CASE_      )
class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							_snake_case       						=					'table,query'



							def __init__(					self       ,		SCREAMING_SNAKE_CASE_=TableQuestionAnsweringArgumentHandler()       ,		*SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_     )->				Any:





													'''simple docstring'''






													super().__init__(*SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     args_parser

													self.check_model_type(
													    dict(
													        TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
													        + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()     )
													    if self.framework == '''tf'''
													    else dict(
													        MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()     )     )

													__UpperCamelCase       					=     bool(getattr(self.model.config       ,		'''aggregation_labels'''       ,		SCREAMING_SNAKE_CASE_     )     ) and bool(
													    getattr(self.model.config       ,		'''num_aggregation_labels'''       ,		SCREAMING_SNAKE_CASE_     )     )
													__UpperCamelCase       					=     '''tapas''' if hasattr(self.model.config       ,		'''aggregation_labels'''     ) else None



							def       A__						(					self       ,		**SCREAMING_SNAKE_CASE_     )->				Union[str, Any]:





													'''simple docstring'''






													return self.model(**SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		**SCREAMING_SNAKE_CASE_     )->				List[str]:





													'''simple docstring'''






													if self.framework == "pt":
																			__UpperCamelCase       					=     []
																			__UpperCamelCase       					=     []
																			__UpperCamelCase       					=     None
																			__UpperCamelCase       					=     inputs['''input_ids'''].shape[0]

																			__UpperCamelCase       					=     inputs['''input_ids'''].to(self.device     )
																			__UpperCamelCase       					=     inputs['''attention_mask'''].to(self.device     )
																			__UpperCamelCase       					=     inputs['''token_type_ids'''].to(self.device     )
																			__UpperCamelCase       					=     None

																			for index in range(SCREAMING_SNAKE_CASE_     ):
																									# If sequences have already been processed, the token type IDs will be created according to the previous
																									# answer.
																									if prev_answers is not None:
																															__UpperCamelCase       					=     token_type_ids_example[:, 3]  # shape (seq_len,)
																															__UpperCamelCase       					=     np.zeros_like(prev_labels_example.cpu().numpy()     )  # shape (seq_len,)

																															__UpperCamelCase       					=     token_type_ids[index]  # shape (seq_len, 7)
																															for i in range(model_labels.shape[0]     ):
																																					__UpperCamelCase       					=     token_type_ids_example[:, 0].tolist()[i]
																																					__UpperCamelCase       					=     token_type_ids_example[:, 1].tolist()[i] - 1
																																					__UpperCamelCase       					=     token_type_ids_example[:, 2].tolist()[i] - 1

																																					if row_id >= 0 and col_id >= 0 and segment_id == 1:
																																											__UpperCamelCase       					=     int(prev_answers[(col_id, row_id)]     )

																															__UpperCamelCase       					=     torch.from_numpy(SCREAMING_SNAKE_CASE_     ).type(torch.long     ).to(self.device     )

																									__UpperCamelCase       					=     input_ids[index]
																									__UpperCamelCase       					=     attention_mask[index]  # shape (seq_len,)
																									__UpperCamelCase       					=     token_type_ids[index]  # shape (seq_len, 7)
																									__UpperCamelCase       					=     self.model(
																									    input_ids=input_ids_example.unsqueeze(0     )       ,		attention_mask=attention_mask_example.unsqueeze(0     )       ,		token_type_ids=token_type_ids_example.unsqueeze(0     )       ,		)
																									__UpperCamelCase       					=     outputs.logits

																									if self.aggregate:
																															all_aggregations.append(outputs.logits_aggregation     )

																									all_logits.append(SCREAMING_SNAKE_CASE_     )

																									__UpperCamelCase       					=     torch.distributions.Bernoulli(logits=SCREAMING_SNAKE_CASE_     )
																									__UpperCamelCase       					=     dist_per_token.probs * attention_mask_example.type(torch.floataa     ).to(
																									    dist_per_token.probs.device     )

																									__UpperCamelCase       					=     collections.defaultdict(SCREAMING_SNAKE_CASE_     )
																									for i, p in enumerate(probabilities.squeeze().tolist()     ):
																															__UpperCamelCase       					=     token_type_ids_example[:, 0].tolist()[i]
																															__UpperCamelCase       					=     token_type_ids_example[:, 1].tolist()[i] - 1
																															__UpperCamelCase       					=     token_type_ids_example[:, 2].tolist()[i] - 1
																															if col >= 0 and row >= 0 and segment_id == 1:
																																					coords_to_probs[(col, row)].append(SCREAMING_SNAKE_CASE_     )

																									__UpperCamelCase       					=     {key: np.array(coords_to_probs[key]     ).mean() > 0.5 for key in coords_to_probs}

																			__UpperCamelCase       					=     torch.cat(tuple(SCREAMING_SNAKE_CASE_     )       ,		0     )

																			return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(SCREAMING_SNAKE_CASE_     )       ,		0     ))
													else:
																			__UpperCamelCase       					=     []
																			__UpperCamelCase       					=     []
																			__UpperCamelCase       					=     None
																			__UpperCamelCase       					=     inputs['''input_ids'''].shape[0]

																			__UpperCamelCase       					=     inputs['''input_ids''']
																			__UpperCamelCase       					=     inputs['''attention_mask''']
																			__UpperCamelCase       					=     inputs['''token_type_ids'''].numpy()
																			__UpperCamelCase       					=     None

																			for index in range(SCREAMING_SNAKE_CASE_     ):
																									# If sequences have already been processed, the token type IDs will be created according to the previous
																									# answer.
																									if prev_answers is not None:
																															__UpperCamelCase       					=     token_type_ids_example[:, 3]  # shape (seq_len,)
																															__UpperCamelCase       					=     np.zeros_like(SCREAMING_SNAKE_CASE_       ,		dtype=np.intaa     )  # shape (seq_len,)

																															__UpperCamelCase       					=     token_type_ids[index]  # shape (seq_len, 7)
																															for i in range(model_labels.shape[0]     ):
																																					__UpperCamelCase       					=     token_type_ids_example[:, 0].tolist()[i]
																																					__UpperCamelCase       					=     token_type_ids_example[:, 1].tolist()[i] - 1
																																					__UpperCamelCase       					=     token_type_ids_example[:, 2].tolist()[i] - 1

																																					if row_id >= 0 and col_id >= 0 and segment_id == 1:
																																											__UpperCamelCase       					=     int(prev_answers[(col_id, row_id)]     )

																															__UpperCamelCase       					=     model_labels

																									__UpperCamelCase       					=     input_ids[index]
																									__UpperCamelCase       					=     attention_mask[index]  # shape (seq_len,)
																									__UpperCamelCase       					=     token_type_ids[index]  # shape (seq_len, 7)
																									__UpperCamelCase       					=     self.model(
																									    input_ids=np.expand_dims(SCREAMING_SNAKE_CASE_       ,		axis=0     )       ,		attention_mask=np.expand_dims(SCREAMING_SNAKE_CASE_       ,		axis=0     )       ,		token_type_ids=np.expand_dims(SCREAMING_SNAKE_CASE_       ,		axis=0     )       ,		)
																									__UpperCamelCase       					=     outputs.logits

																									if self.aggregate:
																															all_aggregations.append(outputs.logits_aggregation     )

																									all_logits.append(SCREAMING_SNAKE_CASE_     )

																									__UpperCamelCase       					=     tfp.distributions.Bernoulli(logits=SCREAMING_SNAKE_CASE_     )
																									__UpperCamelCase       					=     dist_per_token.probs_parameter() * tf.cast(SCREAMING_SNAKE_CASE_       ,		tf.floataa     )

																									__UpperCamelCase       					=     collections.defaultdict(SCREAMING_SNAKE_CASE_     )
																									__UpperCamelCase       					=     token_type_ids_example
																									for i, p in enumerate(tf.squeeze(SCREAMING_SNAKE_CASE_     ).numpy().tolist()     ):
																															__UpperCamelCase       					=     token_type_ids_example[:, 0].tolist()[i]
																															__UpperCamelCase       					=     token_type_ids_example[:, 1].tolist()[i] - 1
																															__UpperCamelCase       					=     token_type_ids_example[:, 2].tolist()[i] - 1
																															if col >= 0 and row >= 0 and segment_id == 1:
																																					coords_to_probs[(col, row)].append(SCREAMING_SNAKE_CASE_     )

																									__UpperCamelCase       					=     {key: np.array(coords_to_probs[key]     ).mean() > 0.5 for key in coords_to_probs}

																			__UpperCamelCase       					=     tf.concat(tuple(SCREAMING_SNAKE_CASE_     )       ,		0     )

																			return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(SCREAMING_SNAKE_CASE_     )       ,		0     ))



							def __call__(					self       ,		*SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_     )->				str:





													'''simple docstring'''






													__UpperCamelCase       					=     self._args_parser(*SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_     )

													__UpperCamelCase       					=     super().__call__(SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_     )
													if len(SCREAMING_SNAKE_CASE_     ) == 1:
																			return results[0]
													return results



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		**SCREAMING_SNAKE_CASE_     )->				Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       					=     {}
													if padding is not None:
																			__UpperCamelCase       					=     padding
													if truncation is not None:
																			__UpperCamelCase       					=     truncation

													__UpperCamelCase       					=     {}
													if sequential is not None:
																			__UpperCamelCase       					=     sequential
													return preprocess_params, forward_params, {}



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=True       ,		SCREAMING_SNAKE_CASE_=None     )->				str:





													'''simple docstring'''






													if truncation is None:
																			if self.type == "tapas":
																									__UpperCamelCase       					=     '''drop_rows_to_fit'''
																			else:
																									__UpperCamelCase       					=     '''do_not_truncate'''

													__UpperCamelCase					,							__UpperCamelCase       					=     pipeline_input['''table'''], pipeline_input['''query''']
													if table.empty:
																			raise ValueError('''table is empty'''     )
													if query is None or query == "":
																			raise ValueError('''query is empty'''     )
													__UpperCamelCase       					=     self.tokenizer(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		return_tensors=self.framework       ,		truncation=SCREAMING_SNAKE_CASE_       ,		padding=SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     table
													return inputs



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_=False     )->				Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     model_inputs.pop('''table'''     )

													if self.type == "tapas":
																			if sequential:
																									__UpperCamelCase       					=     self.sequential_inference(**SCREAMING_SNAKE_CASE_     )
																			else:
																									__UpperCamelCase       					=     self.batch_inference(**SCREAMING_SNAKE_CASE_     )
													else:
																			__UpperCamelCase       					=     self.model.generate(**SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     {'''model_inputs''': model_inputs, '''table''': table, '''outputs''': outputs}
													return model_outputs



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													__UpperCamelCase       					=     model_outputs['''model_inputs''']
													__UpperCamelCase       					=     model_outputs['''table''']
													__UpperCamelCase       					=     model_outputs['''outputs''']
													if self.type == "tapas":
																			if self.aggregate:
																									__UpperCamelCase					,							__UpperCamelCase       					=     outputs[:2]
																									__UpperCamelCase       					=     self.tokenizer.convert_logits_to_predictions(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )
																									__UpperCamelCase					,							__UpperCamelCase       					=     predictions
																									__UpperCamelCase       					=     {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(SCREAMING_SNAKE_CASE_     )}

																									__UpperCamelCase       					=     self.model.config.no_aggregation_label_index
																									__UpperCamelCase       					=     {
																									    i: aggregators[i] + ''' > ''' for i, pred in enumerate(SCREAMING_SNAKE_CASE_     ) if pred != no_agg_label_index
																									}
																			else:
																									__UpperCamelCase       					=     outputs[0]
																									__UpperCamelCase       					=     self.tokenizer.convert_logits_to_predictions(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )
																									__UpperCamelCase       					=     predictions[0]
																									__UpperCamelCase       					=     {}
																									__UpperCamelCase       					=     {}
																			__UpperCamelCase       					=     []
																			for index, coordinates in enumerate(SCREAMING_SNAKE_CASE_     ):
																									__UpperCamelCase       					=     [table.iat[coordinate] for coordinate in coordinates]
																									__UpperCamelCase       					=     aggregators.get(SCREAMING_SNAKE_CASE_       ,		''''''     )
																									__UpperCamelCase       					=     aggregators_prefix.get(SCREAMING_SNAKE_CASE_       ,		''''''     )
																									__UpperCamelCase       					=     {
																									    '''answer''': aggregator_prefix + ''', '''.join(SCREAMING_SNAKE_CASE_     ),
																									    '''coordinates''': coordinates,
																									    '''cells''': [table.iat[coordinate] for coordinate in coordinates],
																									}
																									if aggregator:
																															__UpperCamelCase       					=     aggregator

																									answers.append(SCREAMING_SNAKE_CASE_     )
																			if len(SCREAMING_SNAKE_CASE_     ) == 0:
																									raise PipelineException('''Empty answer'''     )
													else:
																			__UpperCamelCase       					=     [{'''answer''': answer} for answer in self.tokenizer.batch_decode(SCREAMING_SNAKE_CASE_       ,		skip_special_tokens=SCREAMING_SNAKE_CASE_     )]

													return answers if len(SCREAMING_SNAKE_CASE_     ) > 1 else answers[0]






import json
import os
import re
import unicodedata
from typing import Dict, List, Optional, Tuple

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


lowercase__							:							Optional[Any]													=     logging.get_logger(__name__)

lowercase__							:							str													=     {
    "src_vocab_file": "vocab-src.json",
    "tgt_vocab_file": "vocab-tgt.json",
    "merges_file": "merges.txt",
}

lowercase__							:							int													=     {
    "src_vocab_file": {
        "stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-src.json"
    },
    "tgt_vocab_file": {
        "stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-tgt.json"
    },
    "merges_file": {"stas/tiny-wmt19-en-de": "https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/merges.txt"},
}

lowercase__							:							Any													=     {"stas/tiny-wmt19-en-de": 1_0_2_4}
lowercase__							:							List[str]													=     {
    "stas/tiny-wmt19-en-de": {
        "langs": ["en", "de"],
        "model_max_length": 1_0_2_4,
        "special_tokens_map_file": None,
        "full_tokenizer_file": None,
    }
}




def 		A_	(							snake_case							:				Union[str, Any]	) ->      Any:



						'''simple docstring'''

						__UpperCamelCase       					=     set()
						__UpperCamelCase       					=     word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)	)
												__UpperCamelCase       					=     char
						return pairs




def 		A_	(							snake_case							:				Union[str, Any]	) ->      int:



						'''simple docstring'''

						__UpperCamelCase       					=     text.replace('''，'''	, ''','''	)
						__UpperCamelCase       					=     re.sub(r'''。\s*'''	, '''. '''	, snake_case	)
						__UpperCamelCase       					=     text.replace('''、'''	, ''','''	)
						__UpperCamelCase       					=     text.replace('''”'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''“'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''∶'''	, ''':'''	)
						__UpperCamelCase       					=     text.replace('''：'''	, ''':'''	)
						__UpperCamelCase       					=     text.replace('''？'''	, '''?'''	)
						__UpperCamelCase       					=     text.replace('''《'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''》'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''）'''	, ''')'''	)
						__UpperCamelCase       					=     text.replace('''！'''	, '''!'''	)
						__UpperCamelCase       					=     text.replace('''（'''	, '''('''	)
						__UpperCamelCase       					=     text.replace('''；'''	, ''';'''	)
						__UpperCamelCase       					=     text.replace('''１'''	, '''1'''	)
						__UpperCamelCase       					=     text.replace('''」'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''「'''	, '''"'''	)
						__UpperCamelCase       					=     text.replace('''０'''	, '''0'''	)
						__UpperCamelCase       					=     text.replace('''３'''	, '''3'''	)
						__UpperCamelCase       					=     text.replace('''２'''	, '''2'''	)
						__UpperCamelCase       					=     text.replace('''５'''	, '''5'''	)
						__UpperCamelCase       					=     text.replace('''６'''	, '''6'''	)
						__UpperCamelCase       					=     text.replace('''９'''	, '''9'''	)
						__UpperCamelCase       					=     text.replace('''７'''	, '''7'''	)
						__UpperCamelCase       					=     text.replace('''８'''	, '''8'''	)
						__UpperCamelCase       					=     text.replace('''４'''	, '''4'''	)
						__UpperCamelCase       					=     re.sub(r'''．\s*'''	, '''. '''	, snake_case	)
						__UpperCamelCase       					=     text.replace('''～'''	, '''~'''	)
						__UpperCamelCase       					=     text.replace('''’'''	, '''\''''	)
						__UpperCamelCase       					=     text.replace('''…'''	, '''...'''	)
						__UpperCamelCase       					=     text.replace('''━'''	, '''-'''	)
						__UpperCamelCase       					=     text.replace('''〈'''	, '''<'''	)
						__UpperCamelCase       					=     text.replace('''〉'''	, '''>'''	)
						__UpperCamelCase       					=     text.replace('''【'''	, '''['''	)
						__UpperCamelCase       					=     text.replace('''】'''	, ''']'''	)
						__UpperCamelCase       					=     text.replace('''％'''	, '''%'''	)
						return text




def 		A_	(							snake_case							:				List[str]	) ->      Optional[Any]:



						'''simple docstring'''

						__UpperCamelCase       					=     []
						for char in text:
												__UpperCamelCase       					=     unicodedata.category(snake_case	)
												if cat.startswith('''C'''	):
																		continue
												output.append(snake_case	)
						return "".join(snake_case	)






class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							_snake_case       						=					VOCAB_FILES_NAMES
							_snake_case       						=					PRETRAINED_VOCAB_FILES_MAP
							_snake_case       						=					PRETRAINED_INIT_CONFIGURATION
							_snake_case       						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_snake_case       						=					['input_ids', 'attention_mask']



							def __init__(					self       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=False       ,		SCREAMING_SNAKE_CASE_="<unk>"       ,		SCREAMING_SNAKE_CASE_="<s>"       ,		SCREAMING_SNAKE_CASE_="</s>"       ,		SCREAMING_SNAKE_CASE_="<pad>"       ,		**SCREAMING_SNAKE_CASE_       ,		)->				str:





													'''simple docstring'''






													super().__init__(
													    langs=SCREAMING_SNAKE_CASE_       ,		src_vocab_file=SCREAMING_SNAKE_CASE_       ,		tgt_vocab_file=SCREAMING_SNAKE_CASE_       ,		merges_file=SCREAMING_SNAKE_CASE_       ,		do_lower_case=SCREAMING_SNAKE_CASE_       ,		unk_token=SCREAMING_SNAKE_CASE_       ,		bos_token=SCREAMING_SNAKE_CASE_       ,		sep_token=SCREAMING_SNAKE_CASE_       ,		pad_token=SCREAMING_SNAKE_CASE_       ,		**SCREAMING_SNAKE_CASE_       ,		)

													try:
																			import sacremoses
													except ImportError:
																			raise ImportError(
																			    '''You need to install sacremoses to use XLMTokenizer. '''
																			    '''See https://pypi.org/project/sacremoses/ for installation.'''     )

													__UpperCamelCase       					=     sacremoses

													__UpperCamelCase       					=     src_vocab_file
													__UpperCamelCase       					=     tgt_vocab_file
													__UpperCamelCase       					=     merges_file
													__UpperCamelCase       					=     do_lower_case

													# cache of sm.MosesPunctNormalizer instance
													__UpperCamelCase       					=     {}
													# cache of sm.MosesTokenizer instance
													__UpperCamelCase       					=     {}
													__UpperCamelCase       					=     {}

													if langs and len(SCREAMING_SNAKE_CASE_     ) == 2:
																			__UpperCamelCase					,							__UpperCamelCase       					=     langs
													else:
																			raise ValueError(
																			    F"arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. "
																			    '''Usually that means that tokenizer can\'t find a mapping for the given model path '''
																			    '''in PRETRAINED_VOCAB_FILES_MAP, and other maps of this tokenizer.'''     )

													with open(SCREAMING_SNAKE_CASE_       ,		encoding='''utf-8'''     ) as src_vocab_handle:
																			__UpperCamelCase       					=     json.load(SCREAMING_SNAKE_CASE_     )
													with open(SCREAMING_SNAKE_CASE_       ,		encoding='''utf-8'''     ) as tgt_vocab_handle:
																			__UpperCamelCase       					=     json.load(SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     {v: k for k, v in tgt_vocab.items()}
													with open(SCREAMING_SNAKE_CASE_       ,		encoding='''utf-8'''     ) as merges_handle:
																			__UpperCamelCase       					=     merges_handle.read().split('''\n'''     )[:-1]
													__UpperCamelCase       					=     [tuple(merge.split()[:2]     ) for merge in merges]
													__UpperCamelCase       					=     dict(zip(SCREAMING_SNAKE_CASE_       ,		range(len(SCREAMING_SNAKE_CASE_     )     )     )     )
													__UpperCamelCase       					=     {}



							def       A__						(					self     )->				Dict[str, int]:





													'''simple docstring'''






													return self.get_src_vocab()



							@property
							def       A__						(					self     )->				int:





													'''simple docstring'''






													return self.src_vocab_size



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )->				int:





													'''simple docstring'''






													if lang not in self.cache_moses_punct_normalizer:
																			__UpperCamelCase       					=     self.sm.MosesPunctNormalizer(lang=SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     punct_normalizer
													return self.cache_moses_punct_normalizer[lang].normalize(SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													if lang not in self.cache_moses_tokenizer:
																			__UpperCamelCase       					=     self.sm.MosesTokenizer(lang=SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     moses_tokenizer
													return self.cache_moses_tokenizer[lang].tokenize(
													    SCREAMING_SNAKE_CASE_       ,		aggressive_dash_splits=SCREAMING_SNAKE_CASE_       ,		return_str=SCREAMING_SNAKE_CASE_       ,		escape=SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													if lang not in self.cache_moses_detokenizer:
																			__UpperCamelCase       					=     self.sm.MosesDetokenizer(lang=SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     moses_detokenizer
													return self.cache_moses_detokenizer[lang].detokenize(SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )->				List[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     replace_unicode_punct(SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     self.moses_punct_norm(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     remove_non_printing_char(SCREAMING_SNAKE_CASE_     )
													return text



							@property
							def       A__						(					self     )->				List[str]:





													'''simple docstring'''






													return len(self.encoder     )



							@property
							def       A__						(					self     )->				Any:





													'''simple docstring'''






													return len(self.decoder     )



							def       A__						(					self     )->				int:





													'''simple docstring'''






													return dict(self.encoder       ,		**self.added_tokens_encoder     )



							def       A__						(					self     )->				Any:





													'''simple docstring'''






													return dict(self.decoder       ,		**self.added_tokens_decoder     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     tuple(token[:-1]     ) + (token[-1] + '''</w>''',)
													if token in self.cache:
																			return self.cache[token]
													__UpperCamelCase       					=     get_pairs(SCREAMING_SNAKE_CASE_     )

													if not pairs:
																			return token + "</w>"

													while True:
																			__UpperCamelCase       					=     min(SCREAMING_SNAKE_CASE_       ,		key=lambda SCREAMING_SNAKE_CASE_     : self.bpe_ranks.get(SCREAMING_SNAKE_CASE_       ,		float('''inf'''     )     )     )
																			if bigram not in self.bpe_ranks:
																									break
																			__UpperCamelCase					,							__UpperCamelCase       					=     bigram
																			__UpperCamelCase       					=     []
																			__UpperCamelCase       					=     0
																			while i < len(SCREAMING_SNAKE_CASE_     ):
																									try:
																															__UpperCamelCase       					=     word.index(SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_     )
																									except ValueError:
																															new_word.extend(word[i:]     )
																															break
																									else:
																															new_word.extend(word[i:j]     )
																															__UpperCamelCase       					=     j

																									if word[i] == first and i < len(SCREAMING_SNAKE_CASE_     ) - 1 and word[i + 1] == second:
																															new_word.append(first + second     )
																															i += 2
																									else:
																															new_word.append(word[i]     )
																															i += 1
																			__UpperCamelCase       					=     tuple(SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     new_word
																			if len(SCREAMING_SNAKE_CASE_     ) == 1:
																									break
																			else:
																									__UpperCamelCase       					=     get_pairs(SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     ''' '''.join(SCREAMING_SNAKE_CASE_     )
													if word == "\n  </w>":
																			__UpperCamelCase       					=     '''\n</w>'''
													__UpperCamelCase       					=     word
													return word



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_="en"       ,		SCREAMING_SNAKE_CASE_=False     )->				List[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     self.src_lang

													if self.do_lower_case:
																			__UpperCamelCase       					=     text.lower()

													if bypass_tokenizer:
																			__UpperCamelCase       					=     text.split()
													else:
																			__UpperCamelCase       					=     self.moses_pipeline(SCREAMING_SNAKE_CASE_       ,		lang=SCREAMING_SNAKE_CASE_     )
																			__UpperCamelCase       					=     self.moses_tokenize(SCREAMING_SNAKE_CASE_       ,		lang=SCREAMING_SNAKE_CASE_     )

													__UpperCamelCase       					=     []
													for token in text:
																			if token:
																									split_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_     ).split(''' '''     )     )     )

													return split_tokens



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Any:





													'''simple docstring'''






													return self.encoder.get(SCREAMING_SNAKE_CASE_       ,		self.encoder.get(self.unk_token     )     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													return self.decoder.get(SCREAMING_SNAKE_CASE_       ,		self.unk_token     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				List[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     [t.replace(''' '''       ,		''''''     ).replace('''</w>'''       ,		''' '''     ) for t in tokens]
													__UpperCamelCase       					=     ''''''.join(SCREAMING_SNAKE_CASE_     ).split()
													# detokenize
													__UpperCamelCase       					=     self.moses_detokenize(SCREAMING_SNAKE_CASE_       ,		self.tgt_lang     )
													return text



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = None     )->				List[int]:





													'''simple docstring'''






													__UpperCamelCase       					=     [self.sep_token_id]

													# no bos used in fairseq
													if token_ids_a is None:
																			return token_ids_a + sep
													return token_ids_a + sep + token_ids_a + sep



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = None       ,		SCREAMING_SNAKE_CASE_ = False     )->				List[int]:





													'''simple docstring'''






													if already_has_special_tokens:
																			return super().get_special_tokens_mask(
																			    token_ids_a=SCREAMING_SNAKE_CASE_       ,		token_ids_a=SCREAMING_SNAKE_CASE_       ,		already_has_special_tokens=SCREAMING_SNAKE_CASE_     )
													# no bos used in fairseq
													if token_ids_a is not None:
																			return ([0] * len(SCREAMING_SNAKE_CASE_     )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE_     )) + [1]
													return ([0] * len(SCREAMING_SNAKE_CASE_     )) + [1]



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = None     )->				List[int]:





													'''simple docstring'''






													__UpperCamelCase       					=     [self.sep_token_id]

													# no bos used in fairseq
													if token_ids_a is None:
																			return len(token_ids_a + sep     ) * [0]
													return len(token_ids_a + sep     ) * [0] + len(token_ids_a + sep     ) * [1]



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = None     )->				Tuple[str]:





													'''simple docstring'''






													if not os.path.isdir(SCREAMING_SNAKE_CASE_     ):
																			logger.error(F"Vocabulary path ({save_directory}) should be a directory"     )
																			return

													__UpperCamelCase       					=     os.path.join(
													    SCREAMING_SNAKE_CASE_       ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''src_vocab_file''']     )
													__UpperCamelCase       					=     os.path.join(
													    SCREAMING_SNAKE_CASE_       ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''tgt_vocab_file''']     )
													__UpperCamelCase       					=     os.path.join(
													    SCREAMING_SNAKE_CASE_       ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']     )

													with open(SCREAMING_SNAKE_CASE_       ,		'''w'''       ,		encoding='''utf-8'''     ) as f:
																			f.write(json.dumps(self.encoder       ,		indent=2       ,		sort_keys=SCREAMING_SNAKE_CASE_       ,		ensure_ascii=SCREAMING_SNAKE_CASE_     ) + '''\n'''     )

													with open(SCREAMING_SNAKE_CASE_       ,		'''w'''       ,		encoding='''utf-8'''     ) as f:
																			__UpperCamelCase       					=     {v: k for k, v in self.decoder.items()}
																			f.write(json.dumps(SCREAMING_SNAKE_CASE_       ,		indent=2       ,		sort_keys=SCREAMING_SNAKE_CASE_       ,		ensure_ascii=SCREAMING_SNAKE_CASE_     ) + '''\n'''     )

													__UpperCamelCase       					=     0
													with open(SCREAMING_SNAKE_CASE_       ,		'''w'''       ,		encoding='''utf-8'''     ) as writer:
																			for bpe_tokens, token_index in sorted(self.bpe_ranks.items()       ,		key=lambda SCREAMING_SNAKE_CASE_     : kv[1]     ):
																									if index != token_index:
																															logger.warning(
																															    F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
																															    ''' Please check that the tokenizer is not corrupted!'''     )
																															__UpperCamelCase       					=     token_index
																									writer.write(''' '''.join(SCREAMING_SNAKE_CASE_     ) + '''\n'''     )
																									index += 1

													return src_vocab_file, tgt_vocab_file, merges_file



							def __getstate__(					self     )->				str:





													'''simple docstring'''






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



							def __setstate__(					self       ,		SCREAMING_SNAKE_CASE_     )->				List[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     d

													try:
																			import sacremoses
													except ImportError:
																			raise ImportError(
																			    '''You need to install sacremoses to use XLMTokenizer. '''
																			    '''See https://pypi.org/project/sacremoses/ for installation.'''     )

													__UpperCamelCase       					=     sacremoses




