


"""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


UpperCamelCase__				:Union[str, Any]			   =	logging.get_logger(__name__)

UpperCamelCase__				:Optional[Any]			   =	list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase__				:List[str]			   =	tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)






@dataclass
class      A:

		"""simple docstring"""





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






class      A(  __lowercase		):

		"""simple docstring"""





		A    =							"train"
		A    =							"dev"






class      A(  __lowercase		):

		"""simple docstring"""





		A    =							42
		A    =							42
		A    =							42
		A    =							42
		def __init__( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__ = None					,				SCREAMING_SNAKE_CASE__ = Split.train					,				SCREAMING_SNAKE_CASE__ = False					,				SCREAMING_SNAKE_CASE__ = None					,				SCREAMING_SNAKE_CASE__ = "pt"					,				)      ->	int:

					"""simple docstring"""



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

											# Legacy cache files have only features, while new cache files
											# will have dataset and examples also.
											_UpperCamelCase					:Optional[Any]					     =	self.old_features['''features''']
											_UpperCamelCase					:List[Any]					     =	self.old_features.get('''dataset'''					,				SCREAMING_SNAKE_CASE__   )
											_UpperCamelCase					:Any					     =	self.old_features.get('''examples'''					,				SCREAMING_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					:Any					     =	self.processor.get_dev_examples(args.data_dir   )
											else:
														_UpperCamelCase					:Tuple					     =	self.processor.get_train_examples(args.data_dir   )

											_UpperCamelCase     ,      _UpperCamelCase					:Dict					     =	squad_convert_examples_to_features(
											    examples=self.examples					,				tokenizer=SCREAMING_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=SCREAMING_SNAKE_CASE__					,				)

											_UpperCamelCase					:Optional[int]					     =	time.time()
											torch.save(
											    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}					,				SCREAMING_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   )      ->	List[Any]:

					"""simple docstring"""



					return len(self.features   )





		def __getitem__( self					,				SCREAMING_SNAKE_CASE__   )      ->	Dict[str, torch.Tensor]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	self.features[i]

					_UpperCamelCase					:Dict					     =	torch.tensor(feature.input_ids					,				dtype=torch.long   )
					_UpperCamelCase					:Tuple					     =	torch.tensor(feature.attention_mask					,				dtype=torch.long   )
					_UpperCamelCase					:str					     =	torch.tensor(feature.token_type_ids					,				dtype=torch.long   )
					_UpperCamelCase					:str					     =	torch.tensor(feature.cls_index					,				dtype=torch.long   )
					_UpperCamelCase					:List[str]					     =	torch.tensor(feature.p_mask					,				dtype=torch.float   )
					_UpperCamelCase					:List[str]					     =	torch.tensor(feature.is_impossible					,				dtype=torch.float   )

					_UpperCamelCase					:List[Any]					     =	{
					    '''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					:str					     =	torch.tensor(feature.start_position					,				dtype=torch.long   )
								_UpperCamelCase					:int					     =	torch.tensor(feature.end_position					,				dtype=torch.long   )
								inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions}   )

					return inputs



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


lowerCamelCase__						=				logging.get_logger(__name__)







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			Dict						=		["pixel_values"]

						def __init__(      self							,				a = True							,				a = None							,				a = None							,				a = PILImageResampling.BILINEAR							,				a = True							,				a = 1 / 2_55							,				a = True							,				a = None							,				a = None							,				**a							,				)       ->   None:


								'''simple docstring'''

								super().__init__(**a					)
								_UpperCamelCase         =						size if size is not None else {"""shortest_edge""": 3_84}
								_UpperCamelCase         =						get_size_dict(a							,				default_to_square=a					)

								_UpperCamelCase         =						do_resize
								_UpperCamelCase         =						size
								# Default value set here for backwards compatibility where the value in config is None
								_UpperCamelCase         =						crop_pct if crop_pct is not None else 2_24 / 2_56
								_UpperCamelCase         =						resample
								_UpperCamelCase         =						do_rescale
								_UpperCamelCase         =						rescale_factor
								_UpperCamelCase         =						do_normalize
								_UpperCamelCase         =						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
								_UpperCamelCase         =						image_std if image_std is not None else IMAGENET_STANDARD_STD

						def 			A_					(      self							,				a							,				a							,				a							,				a = PILImageResampling.BICUBIC							,				a = None							,				**a							,				)       ->   np.ndarray:


								'''simple docstring'''

								_UpperCamelCase         =						get_size_dict(a							,				default_to_square=a					)
								if "shortest_edge" not in size:
										raise ValueError(F'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}'					)
								_UpperCamelCase         =						size["""shortest_edge"""]

								if shortest_edge < 3_84:
										# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
										_UpperCamelCase         =						int(shortest_edge / crop_pct					)
										_UpperCamelCase         =						get_resize_output_image_size(a							,				size=a							,				default_to_square=a					)
										_UpperCamelCase         =						resize(image=a							,				size=a							,				resample=a							,				data_format=a							,				**a					)
										# then crop to (shortest_edge, shortest_edge)
										return center_crop(image=a							,				size=(shortest_edge, shortest_edge)							,				data_format=a							,				**a					)
								else:
										# warping (no cropping) when evaluated at 384 or larger
										return resize(
										    a							,				size=(shortest_edge, shortest_edge)							,				resample=a							,				data_format=a							,				**a					)

						def 			A_					(      self							,				a							,				a							,				a = None							,				**a							,				)       ->   Optional[int]:


								'''simple docstring'''

								return rescale(a							,				scale=a							,				data_format=a							,				**a					)

						def 			A_					(      self							,				a							,				a							,				a							,				a = None							,				**a							,				)       ->   np.ndarray:


								'''simple docstring'''

								return normalize(a							,				mean=a							,				std=a							,				data_format=a							,				**a					)







						def 			A_					(      self							,				a							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = ChannelDimension.FIRST							,				**a							,				)       ->   PIL.Image.Image:


								'''simple docstring'''

								_UpperCamelCase         =						do_resize if do_resize is not None else self.do_resize
								_UpperCamelCase         =						crop_pct if crop_pct is not None else self.crop_pct
								_UpperCamelCase         =						resample if resample is not None else self.resample
								_UpperCamelCase         =						do_rescale if do_rescale is not None else self.do_rescale
								_UpperCamelCase         =						rescale_factor if rescale_factor is not None else self.rescale_factor
								_UpperCamelCase         =						do_normalize if do_normalize is not None else self.do_normalize
								_UpperCamelCase         =						image_mean if image_mean is not None else self.image_mean
								_UpperCamelCase         =						image_std if image_std is not None else self.image_std

								_UpperCamelCase         =						size if size is not None else self.size
								_UpperCamelCase         =						get_size_dict(a							,				default_to_square=a					)

								_UpperCamelCase         =						make_list_of_images(a					)

								if not valid_images(a					):
										raise ValueError(
										    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
										    """torch.Tensor, tf.Tensor or jax.ndarray."""					)

								if do_resize and size is None or resample is None:
										raise ValueError("""Size and resample must be specified if do_resize is True."""					)

								if do_resize and size["shortest_edge"] < 3_84 and crop_pct is None:
										raise ValueError("""crop_pct must be specified if size < 384."""					)

								if do_rescale and rescale_factor is None:
										raise ValueError("""Rescale factor must be specified if do_rescale is True."""					)

								if do_normalize and (image_mean is None or image_std is None):
										raise ValueError("""Image mean and std must be specified if do_normalize is True."""					)

								# All transformations expect numpy arrays.
								_UpperCamelCase         =						[to_numpy_array(a					) for image in images]

								if do_resize:
										_UpperCamelCase         =						[self.resize(image=a							,				size=a							,				crop_pct=a							,				resample=a					) for image in images]

								if do_rescale:
										_UpperCamelCase         =						[self.rescale(image=a							,				scale=a					) for image in images]

								if do_normalize:
										_UpperCamelCase         =						[self.normalize(image=a							,				mean=a							,				std=a					) for image in images]

								_UpperCamelCase         =						[to_channel_dimension_format(a							,				a					) for image in images]

								_UpperCamelCase         =						{"""pixel_values""": images}
								return BatchFeature(data=a							,				tensor_type=a					)



