


'''simple docstring'''
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer


def       a				(      __a			, __a			, __a			, __a			, __a=True			, __a="pt"       )  ->     Dict:



					'''simple docstring'''






					UpperCamelCase__       :Optional[Any]							 =			{'''add_prefix_space''': True} if isinstance(A__			, A__       ) and not line.startswith(''' '''       ) else {}
					UpperCamelCase__       :Optional[Any]							 =			padding_side
					return tokenizer(
					    [line]			, max_length=A__			, padding='''max_length''' if pad_to_max_length else None			, truncation=A__			, return_tensors=A__			, add_special_tokens=A__			, **A__			, )


def       a				(      __a			, __a			, __a=None			, )  ->     Tuple:



					'''simple docstring'''






					UpperCamelCase__       :Optional[Any]							 =			input_ids.ne(A__       ).any(dim=0       )
					if attention_mask is None:
										return input_ids[:, keep_column_mask]
					else:
										return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])






class        lowercase     (							lowerCamelCase__ ):

		"""simple docstring"""

		def __init__(		self   ,       UpperCamelCase_   ,       UpperCamelCase_   ,       UpperCamelCase_   ,       UpperCamelCase_   ,       UpperCamelCase_="train"   ,       UpperCamelCase_=None   ,       UpperCamelCase_=None   ,       UpperCamelCase_=None   ,       UpperCamelCase_=""   ,       ):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__       :Any							 =			Path(lowercase__							).joinpath(type_path + '''.source'''							)
							UpperCamelCase__       :Tuple							 =			Path(lowercase__							).joinpath(type_path + '''.target'''							)
							UpperCamelCase__       :int							 =			self.get_char_lens(self.src_file							)
							UpperCamelCase__       :Optional[int]							 =			max_source_length
							UpperCamelCase__       :Optional[Any]							 =			max_target_length
							assert min(self.src_lens							) > 0, F'''found empty line in {self.src_file}'''
							UpperCamelCase__       :List[str]							 =			tokenizer
							UpperCamelCase__       :int							 =			prefix
							if n_obs is not None:
												UpperCamelCase__       :Any							 =			self.src_lens[:n_obs]
							UpperCamelCase__       :Tuple							 =			src_lang
							UpperCamelCase__       :int							 =			tgt_lang




		def __len__(		self							):

							'''simple docstring'''


							return len(self.src_lens							)




		def __getitem__(		self   ,       UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__       :Any							 =			index + 1  # linecache starts at 1
							UpperCamelCase__       :Any							 =			self.prefix + linecache.getline(str(self.src_file							)   ,       lowercase__							).rstrip('''\n'''							)
							UpperCamelCase__       :List[str]							 =			linecache.getline(str(self.tgt_file							)   ,       lowercase__							).rstrip('''\n'''							)
							assert source_line, F'''empty source line for index {index}'''
							assert tgt_line, F'''empty tgt line for index {index}'''

							# Need to add eos token manually for T5
							if isinstance(self.tokenizer   ,       lowercase__							):
												source_line += self.tokenizer.eos_token
												tgt_line += self.tokenizer.eos_token

							# Pad source and target to the right
							UpperCamelCase__       :Tuple							 =			(
							    self.tokenizer.question_encoder if isinstance(self.tokenizer   ,       lowercase__							) else self.tokenizer
							)
							UpperCamelCase__       :int							 =			self.tokenizer.generator if isinstance(self.tokenizer   ,       lowercase__							) else self.tokenizer

							UpperCamelCase__       :Any							 =			encode_line(lowercase__   ,       lowercase__   ,       self.max_source_length   ,       '''right'''							)
							UpperCamelCase__       :Dict							 =			encode_line(lowercase__   ,       lowercase__   ,       self.max_target_length   ,       '''right'''							)

							UpperCamelCase__       :Any							 =			source_inputs['''input_ids'''].squeeze()
							UpperCamelCase__       :Optional[Any]							 =			target_inputs['''input_ids'''].squeeze()
							UpperCamelCase__       :str							 =			source_inputs['''attention_mask'''].squeeze()
							return {
							    "input_ids": source_ids,
							    "attention_mask": src_mask,
							    "decoder_input_ids": target_ids,
							}




		@staticmethod
		def    lowerCAmelCase__    (		UpperCamelCase_							):

							'''simple docstring'''


							return [len(lowercase__							) for x in Path(lowercase__							).open().readlines()]




		def    lowerCAmelCase__    (		self   ,       UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__       :Dict							 =			torch.stack([x['''input_ids'''] for x in batch]							)
							UpperCamelCase__       :Any							 =			torch.stack([x['''attention_mask'''] for x in batch]							)
							UpperCamelCase__       :Optional[Any]							 =			torch.stack([x['''decoder_input_ids'''] for x in batch]							)
							UpperCamelCase__       :List[str]							 =			(
							    self.tokenizer.generator.pad_token_id
							    if isinstance(self.tokenizer   ,       lowercase__							)
							    else self.tokenizer.pad_token_id
							)
							UpperCamelCase__       :Optional[int]							 =			(
							    self.tokenizer.question_encoder.pad_token_id
							    if isinstance(self.tokenizer   ,       lowercase__							)
							    else self.tokenizer.pad_token_id
							)
							UpperCamelCase__       :Tuple							 =			trim_batch(lowercase__   ,       lowercase__							)
							UpperCamelCase__ ,    UpperCamelCase__       :int							 =			trim_batch(lowercase__   ,       lowercase__   ,       attention_mask=lowercase__							)
							UpperCamelCase__       :str							 =			{
							    '''input_ids''': source_ids,
							    '''attention_mask''': source_mask,
							    '''decoder_input_ids''': y,
							}
							return batch



__snake_case											=					getLogger(__name__)


def       a				(      __a       )  ->     Optional[Any]:



					'''simple docstring'''






					return list(itertools.chain.from_iterable(A__       )       )


def       a				(      __a       )  ->     List[str]:



					'''simple docstring'''






					UpperCamelCase__       :Tuple							 =			get_git_info()
					save_json(A__			, os.path.join(A__			, '''git_log.json'''       )       )


def       a				(      __a			, __a			, __a=4			, **__a       )  ->     Any:



					'''simple docstring'''






					with open(A__			, '''w'''       ) as f:
										json.dump(A__			, A__			, indent=A__			, **A__       )


def       a				(      __a       )  ->     List[str]:



					'''simple docstring'''






					with open(A__       ) as f:
										return json.load(A__       )


def       a				(      )  ->     int:



					'''simple docstring'''






					UpperCamelCase__       :List[Any]							 =			git.Repo(search_parent_directories=A__       )
					UpperCamelCase__       :Dict							 =			{
					    '''repo_id''': str(A__       ),
					    '''repo_sha''': str(repo.head.object.hexsha       ),
					    '''repo_branch''': str(repo.active_branch       ),
					    '''hostname''': str(socket.gethostname()       ),
					}
					return repo_infos


def       a				(      __a			, __a       )  ->     str:



					'''simple docstring'''






					return list(map(A__			, A__       )       )


def       a				(      __a			, __a       )  ->     List[str]:



					'''simple docstring'''






					with open(A__			, '''wb'''       ) as f:
										return pickle.dump(A__			, A__       )


def       a				(      __a       )  ->     List[str]:



					'''simple docstring'''






					def remove_articles(__a       ):
										return re.sub(R'''\b(a|an|the)\b'''			, ''' '''			, A__       )

					def white_space_fix(__a       ):
										return " ".join(text.split()       )

					def remove_punc(__a       ):
										UpperCamelCase__       :int							 =			set(string.punctuation       )
										return "".join(ch for ch in text if ch not in exclude       )

					def lower(__a       ):
										return text.lower()

					return white_space_fix(remove_articles(remove_punc(lower(A__       )       )       )       )


def       a				(      __a			, __a       )  ->     List[Any]:



					'''simple docstring'''






					UpperCamelCase__       :Optional[int]							 =			normalize_answer(A__       ).split()
					UpperCamelCase__       :str							 =			normalize_answer(A__       ).split()
					UpperCamelCase__       :Dict							 =			Counter(A__       ) & Counter(A__       )
					UpperCamelCase__       :Any							 =			sum(common.values()       )
					if num_same == 0:
										return 0
					UpperCamelCase__       :Any							 =			1.0 * num_same / len(A__       )
					UpperCamelCase__       :str							 =			1.0 * num_same / len(A__       )
					UpperCamelCase__       :Union[str, Any]							 =			(2 * precision * recall) / (precision + recall)
					return fa


def       a				(      __a			, __a       )  ->     Optional[int]:



					'''simple docstring'''






					return normalize_answer(A__       ) == normalize_answer(A__       )


def       a				(      __a			, __a       )  ->     Union[str, Any]:



					'''simple docstring'''






					assert len(A__       ) == len(A__       )
					UpperCamelCase__       :str							 =			0
					for hypo, pred in zip(A__			, A__       ):
										em += exact_match_score(A__			, A__       )
					if len(A__       ) > 0:
										em /= len(A__       )
					return {"em": em}


def       a				(      __a       )  ->     str:



					'''simple docstring'''






					return model_prefix.startswith('''rag'''       )







def       a				(      __a			, __a			, __a       )  ->     Dict:



					'''simple docstring'''






					UpperCamelCase__       :Union[str, Any]							 =			{p: p for p in extra_params}
					# T5 models don't have `dropout` param, they have `dropout_rate` instead
					UpperCamelCase__       :Optional[int]							 =			'''dropout_rate'''
					for p in extra_params:
										if getattr(A__			, A__			, A__       ):
															if not hasattr(A__			, A__       ) and not hasattr(A__			, equivalent_param[p]       ):
																				logger.info('''config doesn\'t have a `{}` attribute'''.format(A__       )       )
																				delattr(A__			, A__       )
																				continue
															UpperCamelCase__       :Optional[int]							 =			p if hasattr(A__			, A__       ) else equivalent_param[p]
															setattr(A__			, A__			, getattr(A__			, A__       )       )
															delattr(A__			, A__       )
					return hparams, config



'''simple docstring'''
import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer


__snake_case											=					logging.get_logger(__name__)

__snake_case											=					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__snake_case											=					{
    '''vocab_file''': {
        '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt''',
        '''distilbert-base-uncased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt'''
        ),
        '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt''',
        '''distilbert-base-cased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt'''
        ),
        '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt''',
        '''distilbert-base-multilingual-cased''': (
            '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json''',
        '''distilbert-base-uncased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json''',
        '''distilbert-base-cased-distilled-squad''': (
            '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-german-cased''': (
            '''https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json'''
        ),
        '''distilbert-base-multilingual-cased''': (
            '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json'''
        ),
    },
}

__snake_case											=					{
    '''distilbert-base-uncased''': 512,
    '''distilbert-base-uncased-distilled-squad''': 512,
    '''distilbert-base-cased''': 512,
    '''distilbert-base-cased-distilled-squad''': 512,
    '''distilbert-base-german-cased''': 512,
    '''distilbert-base-multilingual-cased''': 512,
}


__snake_case											=					{
    '''distilbert-base-uncased''': {'''do_lower_case''': True},
    '''distilbert-base-uncased-distilled-squad''': {'''do_lower_case''': True},
    '''distilbert-base-cased''': {'''do_lower_case''': False},
    '''distilbert-base-cased-distilled-squad''': {'''do_lower_case''': False},
    '''distilbert-base-german-cased''': {'''do_lower_case''': False},
    '''distilbert-base-multilingual-cased''': {'''do_lower_case''': False},
}
class        lowercase     (							A__ ):

		"""simple docstring"""

		_a   			=    VOCAB_FILES_NAMES
		_a   			=    PRETRAINED_VOCAB_FILES_MAP
		_a   			=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		_a   			=    PRETRAINED_INIT_CONFIGURATION
		_a   			=    ['input_ids', 'attention_mask']
		_a   			=    DistilBertTokenizer




		def __init__(		self   ,       UpperCamelCase_=None   ,       UpperCamelCase_=None   ,       UpperCamelCase_=True   ,       UpperCamelCase_="[UNK]"   ,       UpperCamelCase_="[SEP]"   ,       UpperCamelCase_="[PAD]"   ,       UpperCamelCase_="[CLS]"   ,       UpperCamelCase_="[MASK]"   ,       UpperCamelCase_=True   ,       UpperCamelCase_=None   ,       **UpperCamelCase_   ,       ):

							'''simple docstring'''


							super().__init__(
							    UpperCamelCase_   ,       tokenizer_file=UpperCamelCase_   ,       do_lower_case=UpperCamelCase_   ,       unk_token=UpperCamelCase_   ,       sep_token=UpperCamelCase_   ,       pad_token=UpperCamelCase_   ,       cls_token=UpperCamelCase_   ,       mask_token=UpperCamelCase_   ,       tokenize_chinese_chars=UpperCamelCase_   ,       strip_accents=UpperCamelCase_   ,       **UpperCamelCase_   ,       )

							UpperCamelCase__       :int							 =			json.loads(self.backend_tokenizer.normalizer.__getstate__()							)
							if (
							    normalizer_state.get('''lowercase'''   ,       UpperCamelCase_							) != do_lower_case
							    or normalizer_state.get('''strip_accents'''   ,       UpperCamelCase_							) != strip_accents
							    or normalizer_state.get('''handle_chinese_chars'''   ,       UpperCamelCase_							) != tokenize_chinese_chars
							):
												UpperCamelCase__       :int							 =			getattr(UpperCamelCase_   ,       normalizer_state.pop('''type'''							)							)
												UpperCamelCase__       :Optional[Any]							 =			do_lower_case
												UpperCamelCase__       :Optional[Any]							 =			strip_accents
												UpperCamelCase__       :List[Any]							 =			tokenize_chinese_chars
												UpperCamelCase__       :Any							 =			normalizer_class(**UpperCamelCase_							)

							UpperCamelCase__       :int							 =			do_lower_case




		def    lowerCAmelCase__    (		self   ,       UpperCamelCase_   ,       UpperCamelCase_=None							):

							'''simple docstring'''


							UpperCamelCase__       :Tuple							 =			[self.cls_token_id] + token_ids_a + [self.sep_token_id]

							if token_ids_a:
												output += token_ids_a + [self.sep_token_id]

							return output




		def    lowerCAmelCase__    (		self   ,       UpperCamelCase_   ,       UpperCamelCase_ = None							):

							'''simple docstring'''


							UpperCamelCase__       :List[str]							 =			[self.sep_token_id]
							UpperCamelCase__       :List[str]							 =			[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    lowerCAmelCase__    (		self   ,       UpperCamelCase_   ,       UpperCamelCase_ = None							):

							'''simple docstring'''


							UpperCamelCase__       :str							 =			self._tokenizer.model.save(UpperCamelCase_   ,       name=UpperCamelCase_							)
							return tuple(UpperCamelCase_							)