



"""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   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=True				,      lowerCamelCase__="pt"			) ->							List[str]:
							A         =					{'add_prefix_space': True} if isinstance(lowerCamelCase__				,      lowerCamelCase__			) and not line.startswith(' '			) else {}
							A         =					padding_side
							return tokenizer(
							    [line]				,      max_length=lowerCamelCase__				,      padding='max_length' if pad_to_max_length else None				,      truncation=lowerCamelCase__				,      return_tensors=lowerCamelCase__				,      add_special_tokens=lowerCamelCase__				,      **lowerCamelCase__				,      )

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=None				,      ) ->							List[Any]:
							A         =					input_ids.ne(lowerCamelCase__			).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      UpperCAmelCase__		(      UpperCamelCase     ):



		def __init__( self  :    Union[str, Any]      ,							snake_case  :    List[str]      ,							snake_case  :    int      ,							snake_case  :    str      ,							snake_case  :    Optional[Any]      ,							snake_case  :    Dict="train"      ,							snake_case  :    Dict=None      ,							snake_case  :    str=None      ,							snake_case  :    Union[str, Any]=None      ,							snake_case  :    Dict=""      ,							)			->						Optional[int]:






									'''simple docstring'''

									super().__init__()
									A         =					Path(snake_case				).joinpath(type_path + '.source'				)
									A         =					Path(snake_case				).joinpath(type_path + '.target'				)
									A         =					self.get_char_lens(self.src_file				)
									A         =					max_source_length
									A         =					max_target_length
									assert min(self.src_lens				) > 0, f"""found empty line in {self.src_file}"""
									A         =					tokenizer
									A         =					prefix
									if n_obs is not None:
																A         =					self.src_lens[:n_obs]
									A         =					src_lang
									A         =					tgt_lang



		def __len__( self  :    Dict				)			->						Dict:






									'''simple docstring'''

									return len(self.src_lens				)



		def __getitem__( self  :    Union[str, Any]      ,							snake_case  :    Optional[int]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									A         =					index + 1  # linecache starts at 1
									A         =					self.prefix + linecache.getline(str(self.src_file				)      ,							snake_case				).rstrip('\n'				)
									A         =					linecache.getline(str(self.tgt_file				)      ,							snake_case				).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      ,							snake_case				):
																source_line += self.tokenizer.eos_token
																tgt_line += self.tokenizer.eos_token

									# Pad source and target to the right
									A         =					(
									    self.tokenizer.question_encoder if isinstance(self.tokenizer      ,							snake_case				) else self.tokenizer
									)
									A         =					self.tokenizer.generator if isinstance(self.tokenizer      ,							snake_case				) else self.tokenizer

									A         =					encode_line(snake_case      ,							snake_case      ,							self.max_source_length      ,							'right'				)
									A         =					encode_line(snake_case      ,							snake_case      ,							self.max_target_length      ,							'right'				)

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



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






									'''simple docstring'''

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



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    List[str]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									A         =					torch.stack([x['input_ids'] for x in batch]				)
									A         =					torch.stack([x['attention_mask'] for x in batch]				)
									A         =					torch.stack([x['decoder_input_ids'] for x in batch]				)
									A         =					(
									    self.tokenizer.generator.pad_token_id
									    if isinstance(self.tokenizer      ,							snake_case				)
									    else self.tokenizer.pad_token_id
									)
									A         =					(
									    self.tokenizer.question_encoder.pad_token_id
									    if isinstance(self.tokenizer      ,							snake_case				)
									    else self.tokenizer.pad_token_id
									)
									A         =					trim_batch(snake_case      ,							snake_case				)
									A      ,  A         =					trim_batch(snake_case      ,							snake_case      ,							attention_mask=snake_case				)
									A         =					{
									    'input_ids': source_ids,
									    'attention_mask': source_mask,
									    'decoder_input_ids': y,
									}
									return batch



A    =			getLogger(__name__)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							Union[str, Any]:
							return list(itertools.chain.from_iterable(lowerCamelCase__			)			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							None:
							A         =					get_git_info()
							save_json(lowerCamelCase__				,      os.path.join(lowerCamelCase__				,      'git_log.json'			)			)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=4				,      **lowerCamelCase__			) ->							Any:
							with open(lowerCamelCase__				,      'w'			) as f:
														json.dump(lowerCamelCase__				,      lowerCamelCase__				,      indent=lowerCamelCase__				,      **lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							str:
							with open(lowerCamelCase__			) as f:
														return json.load(lowerCamelCase__			)

def   lowerCAmelCase__			(     ) ->							Dict:
							A         =					git.Repo(search_parent_directories=lowerCamelCase__			)
							A         =					{
							    'repo_id': str(lowerCamelCase__			),
							    'repo_sha': str(repo.head.object.hexsha			),
							    'repo_branch': str(repo.active_branch			),
							    'hostname': str(socket.gethostname()			),
							}
							return repo_infos

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							List:
							return list(map(lowerCamelCase__				,      lowerCamelCase__			)			)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							Dict:
							with open(lowerCamelCase__				,      'wb'			) as f:
														return pickle.dump(lowerCamelCase__				,      lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							List[str]:

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

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

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

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

							return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__			)			)			)			)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							Tuple:
							A         =					normalize_answer(lowerCamelCase__			).split()
							A         =					normalize_answer(lowerCamelCase__			).split()
							A         =					Counter(lowerCamelCase__			) & Counter(lowerCamelCase__			)
							A         =					sum(common.values()			)
							if num_same == 0:
														return 0
							A         =					1.0 * num_same / len(lowerCamelCase__			)
							A         =					1.0 * num_same / len(lowerCamelCase__			)
							A         =					(2 * precision * recall) / (precision + recall)
							return fa

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							Dict:
							return normalize_answer(lowerCamelCase__			) == normalize_answer(lowerCamelCase__			)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__			) ->							Dict:
							assert len(lowerCamelCase__			) == len(lowerCamelCase__			)
							A         =					0
							for hypo, pred in zip(lowerCamelCase__				,      lowerCamelCase__			):
														em += exact_match_score(lowerCamelCase__				,      lowerCamelCase__			)
							if len(lowerCamelCase__			) > 0:
														em /= len(lowerCamelCase__			)
							return {"em": em}

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							Optional[Any]:
							return model_prefix.startswith('rag'			)

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








"""simple docstring"""







import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


A    =			logging.get_logger(__name__)

A    =			list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A    =			tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class      UpperCAmelCase__		:
		lowerCAmelCase_       :	str 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """Model type selected in the list: """ + """, """.join(UpperCamelCase     )}     )
		lowerCAmelCase_       :	str 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=1_28   ,metadata={
		        """help""": (
		            """The maximum total input sequence length after tokenization. Sequences longer """
		            """than this will be truncated, sequences shorter will be padded."""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=1_28   ,metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=64   ,metadata={
		        """help""": (
		            """The maximum number of tokens for the question. Questions longer than this will """
		            """be truncated to this length."""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(
		    default=30   ,metadata={
		        """help""": (
		            """The maximum length of an answer that can be generated. This is needed because the start """
		            """and end predictions are not conditioned on one another."""
		        )
		    }   ,)
		lowerCAmelCase_       :	bool 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )
		lowerCAmelCase_       :	bool 							=     field(
		    default=UpperCamelCase   ,metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}     )
		lowerCAmelCase_       :	float 							=     field(
		    default=0.0   ,metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=20   ,metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}     )
		lowerCAmelCase_       :	int 							=     field(
		    default=0   ,metadata={
		        """help""": (
		            """language id of input for language-specific xlm models (see"""
		            """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
		        )
		    }   ,)
		lowerCAmelCase_       :	int 							=     field(default=1   ,metadata={"""help""": """multiple threads for converting example to features"""}     )






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	str 							=     """train"""
		lowerCAmelCase_       :	Union[str, Any] 							=     """dev"""






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	SquadDataTrainingArguments
		lowerCAmelCase_       :	List[SquadFeatures]
		lowerCAmelCase_       :	Split
		lowerCAmelCase_       :	bool



		def __init__( self  :    List[Any]      ,							snake_case  :    SquadDataTrainingArguments      ,							snake_case  :    PreTrainedTokenizer      ,							snake_case  :    Optional[int] = None      ,							snake_case  :    Union[str, Split] = Split.train      ,							snake_case  :    Optional[bool] = False      ,							snake_case  :    Optional[str] = None      ,							snake_case  :    Optional[str] = "pt"      ,							)			->						Optional[Any]:






									'''simple docstring'''

									A         =					args
									A         =					is_language_sensitive
									A         =					SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
									if isinstance(snake_case      ,							snake_case				):
																try:
																							A         =					Split[mode]
																except KeyError:
																							raise KeyError('mode is not a valid split name'				)
									A         =					mode
									# Load data features from cache or dataset file
									A         =					'v2' if args.version_2_with_negative else 'v1'
									A         =					os.path.join(
									    cache_dir if cache_dir is not None else args.data_dir      ,							f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"""      ,							)

									# Make sure only the first process in distributed training processes the dataset,
									# and the others will use the cache.
									A         =					cached_features_file + '.lock'
									with FileLock(snake_case				):
																if os.path.exists(snake_case				) and not args.overwrite_cache:
																							A         =					time.time()
																							A         =					torch.load(snake_case				)

																							# Legacy cache files have only features, while new cache files
																							# will have dataset and examples also.
																							A         =					self.old_features['features']
																							A         =					self.old_features.get('dataset'      ,							snake_case				)
																							A         =					self.old_features.get('examples'      ,							snake_case				)
																							logger.info(
																							    f"""Loading features from cached file {cached_features_file} [took %.3f s]"""      ,							time.time() - start				)

																							if self.dataset is None or self.examples is None:
																														logger.warning(
																														    f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
																														    ' future run'				)
																else:
																							if mode == Split.dev:
																														A         =					self.processor.get_dev_examples(args.data_dir				)
																							else:
																														A         =					self.processor.get_train_examples(args.data_dir				)

																							A      ,  A         =					squad_convert_examples_to_features(
																							    examples=self.examples      ,							tokenizer=snake_case      ,							max_seq_length=args.max_seq_length      ,							doc_stride=args.doc_stride      ,							max_query_length=args.max_query_length      ,							is_training=mode == Split.train      ,							threads=args.threads      ,							return_dataset=snake_case      ,							)

																							A         =					time.time()
																							torch.save(
																							    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}      ,							snake_case      ,							)
																							# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																							logger.info(
																							    f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""				)



		def __len__( self  :    Any				)			->						Dict:






									'''simple docstring'''

									return len(self.features				)



		def __getitem__( self  :    Union[str, Any]      ,							snake_case  :    List[str]				)			->						Dict[str, torch.Tensor]:






									'''simple docstring'''

									A         =					self.features[i]

									A         =					torch.tensor(feature.input_ids      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.attention_mask      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.token_type_ids      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.cls_index      ,							dtype=torch.long				)
									A         =					torch.tensor(feature.p_mask      ,							dtype=torch.float				)
									A         =					torch.tensor(feature.is_impossible      ,							dtype=torch.float				)

									A         =					{
									    'input_ids': input_ids,
									    'attention_mask': attention_mask,
									    'token_type_ids': token_type_ids,
									}

									if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
																del inputs["token_type_ids"]

									if self.args.model_type in ["xlnet", "xlm"]:
																inputs.update({'cls_index': cls_index, 'p_mask': p_mask}				)
																if self.args.version_2_with_negative:
																							inputs.update({'is_impossible': is_impossible}				)
																if self.is_language_sensitive:
																							inputs.update({'langs': (torch.ones(input_ids.shape      ,							dtype=torch.intaa				) * self.args.lang_id)}				)

									if self.mode == Split.train:
																A         =					torch.tensor(feature.start_position      ,							dtype=torch.long				)
																A         =					torch.tensor(feature.end_position      ,							dtype=torch.long				)
																inputs.update({'start_positions': start_positions, 'end_positions': end_positions}				)

									return inputs



