


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


__UpperCamelCase     		=							logging.get_logger(__name__)

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







@dataclass
class 							lowerCamelCase__						:






			"""simple docstring"""






			_UpperCamelCase		:       str 			=		field(
			    default=UpperCAmelCase       ,						metadata={'help': 'Model type selected in the list: ' + ', '.join(UpperCAmelCase   )}   )
			_UpperCamelCase		:       str 			=		field(
			    default=UpperCAmelCase       ,						metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}   )
			_UpperCamelCase		:       int 			=		field(
			    default=128       ,						metadata={
			        'help': (
			            'The maximum total input sequence length after tokenization. Sequences longer '
			            'than this will be truncated, sequences shorter will be padded.'
			        )
			    }       ,						)
			_UpperCamelCase		:       int 			=		field(
			    default=128       ,						metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}       ,						)
			_UpperCamelCase		:       int 			=		field(
			    default=64       ,						metadata={
			        'help': (
			            'The maximum number of tokens for the question. Questions longer than this will '
			            'be truncated to this length.'
			        )
			    }       ,						)
			_UpperCamelCase		:       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.'
			        )
			    }       ,						)
			_UpperCamelCase		:       bool 			=		field(
			    default=UpperCAmelCase       ,						metadata={'help': 'Overwrite the cached training and evaluation sets'}   )
			_UpperCamelCase		:       bool 			=		field(
			    default=UpperCAmelCase       ,						metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'}   )
			_UpperCamelCase		:       float 			=		field(
			    default=0.0       ,						metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}   )
			_UpperCamelCase		:       int 			=		field(
			    default=20       ,						metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}   )
			_UpperCamelCase		:       int 			=		field(
			    default=0       ,						metadata={
			        'help': (
			            'language id of input for language-specific xlm models (see'
			            ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
			        )
			    }       ,						)
			_UpperCamelCase		:       int 			=		field(default=1       ,						metadata={'help': 'multiple threads for converting example to features'}   )







class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			_UpperCamelCase		:       str 			=		'train'
			_UpperCamelCase		:       Tuple 			=		'dev'







class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			_UpperCamelCase		:       SquadDataTrainingArguments
			_UpperCamelCase		:       List[SquadFeatures]
			_UpperCamelCase		:       Split
			_UpperCamelCase		:       bool




			def __init__(				self   ,    snake_case   ,    snake_case   ,    snake_case = None   ,    snake_case = Split.train   ,    snake_case = False   ,    snake_case = None   ,    snake_case = "pt"   ,    ):

						'''simple docstring'''


						UpperCamelCase__       =							args
						UpperCamelCase__       =							is_language_sensitive
						UpperCamelCase__       =							SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
						if isinstance(snake_case   ,    snake_case  ):
									try:
												UpperCamelCase__       =							Split[mode]
									except KeyError:
												raise KeyError("mode is not a valid split name"  )
						UpperCamelCase__       =							mode
						# Load data features from cache or dataset file
						UpperCamelCase__       =							"v2" if args.version_2_with_negative else "v1"
						UpperCamelCase__       =							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.
						UpperCamelCase__       =							cached_features_file + ".lock"
						with FileLock(snake_case  ):
									if os.path.exists(snake_case  ) and not args.overwrite_cache:
												UpperCamelCase__       =							time.time()
												UpperCamelCase__       =							torch.load(snake_case  )

												# Legacy cache files have only features, while new cache files
												# will have dataset and examples also.
												UpperCamelCase__       =							self.old_features["features"]
												UpperCamelCase__       =							self.old_features.get("dataset"   ,    snake_case  )
												UpperCamelCase__       =							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:
															UpperCamelCase__       =							self.processor.get_dev_examples(args.data_dir  )
												else:
															UpperCamelCase__       =							self.processor.get_train_examples(args.data_dir  )

												UpperCamelCase__,   UpperCamelCase__       =							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   ,    )

												UpperCamelCase__       =							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  ):

						'''simple docstring'''


						return len(self.features  )







			def __getitem__(				self   ,    snake_case  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.features[i]

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

						UpperCamelCase__       =							{
						    "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:
									UpperCamelCase__       =							torch.tensor(feature.start_position   ,    dtype=torch.long  )
									UpperCamelCase__       =							torch.tensor(feature.end_position   ,    dtype=torch.long  )
									inputs.update({"start_positions": start_positions, "end_positions": end_positions}  )

						return inputs






from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCamelCase     		=							logging.get_logger(__name__)

__UpperCamelCase     		=							{
    'microsoft/trocr-base-handwritten': (
        'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}







class 							lowerCamelCase__						(				UpperCAmelCase   ):






			"""simple docstring"""






			_UpperCamelCase		:       Dict 			=		'trocr'
			_UpperCamelCase		:       Union[str, Any] 			=		['past_key_values']
			_UpperCamelCase		:       Union[str, Any] 			=		{
			    'num_attention_heads': 'decoder_attention_heads',
			    'hidden_size': 'd_model',
			    'num_hidden_layers': 'decoder_layers',
			}




			def __init__(				self   ,    snake_case=50265   ,    snake_case=1024   ,    snake_case=12   ,    snake_case=16   ,    snake_case=4096   ,    snake_case="gelu"   ,    snake_case=512   ,    snake_case=0.1   ,    snake_case=0.0   ,    snake_case=0.0   ,    snake_case=2   ,    snake_case=0.02   ,    snake_case=0.0   ,    snake_case=True   ,    snake_case=False   ,    snake_case=True   ,    snake_case=True   ,    snake_case=1   ,    snake_case=0   ,    snake_case=2   ,    **snake_case   ,    ):

						'''simple docstring'''


						UpperCamelCase__       =							vocab_size
						UpperCamelCase__       =							d_model
						UpperCamelCase__       =							decoder_layers
						UpperCamelCase__       =							decoder_attention_heads
						UpperCamelCase__       =							decoder_ffn_dim
						UpperCamelCase__       =							activation_function
						UpperCamelCase__       =							max_position_embeddings
						UpperCamelCase__       =							dropout
						UpperCamelCase__       =							attention_dropout
						UpperCamelCase__       =							activation_dropout
						UpperCamelCase__       =							init_std
						UpperCamelCase__       =							decoder_layerdrop
						UpperCamelCase__       =							use_cache
						UpperCamelCase__       =							scale_embedding
						UpperCamelCase__       =							use_learned_position_embeddings
						UpperCamelCase__       =							layernorm_embedding

						super().__init__(
						    pad_token_id=snake_case   ,    bos_token_id=snake_case   ,    eos_token_id=snake_case   ,    decoder_start_token_id=snake_case   ,    **snake_case   ,    )


