





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

class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							List[str]									=		"""train"""
				__snake_case :							Union[str, Any]									=		"""dev"""

class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							SquadDataTrainingArguments
				__snake_case :							List[SquadFeatures]
				__snake_case :							Split
				__snake_case :							bool




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

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

																									__lowerCamelCase     ,    __lowerCamelCase   :   Optional[Any]       =squad_convert_examples_to_features(
																									    examples=self.examples    ,     tokenizer=__lowercase    ,     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=__lowercase    ,     )

																									__lowerCamelCase   :   Dict       =time.time()
																									torch.save(
																									    {'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples}    ,     __lowercase    ,     )
																									# ^ 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      ):
											return len(self.features      )




				def __getitem__(  self	:Union[str, Any]    ,     __lowercase	:Optional[int]      ):
											# Convert to Tensors and build dataset
											__lowerCamelCase   :   Union[str, Any]       =self.features[i]

											__lowerCamelCase   :   Union[str, Any]       =torch.tensor(feature.input_ids    ,     dtype=torch.long      )
											__lowerCamelCase   :   Union[str, Any]       =torch.tensor(feature.attention_mask    ,     dtype=torch.long      )
											__lowerCamelCase   :   Any       =torch.tensor(feature.token_type_ids    ,     dtype=torch.long      )
											__lowerCamelCase   :   Optional[Any]       =torch.tensor(feature.cls_index    ,     dtype=torch.long      )
											__lowerCamelCase   :   str       =torch.tensor(feature.p_mask    ,     dtype=torch.float      )
											__lowerCamelCase   :   Any       =torch.tensor(feature.is_impossible    ,     dtype=torch.float      )

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

											return inputs











"""simple docstring"""





from typing import Dict, List, Optional, Tuple, 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_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


_UpperCamelCase					      =   logging.get_logger(__name__)
class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							Optional[int]									=		["""pixel_values"""]




				def __init__(  self	:Optional[Any]    ,     __lowercase	:bool = True    ,     __lowercase	:Optional[Dict[str, int]] = None    ,     __lowercase	:PILImageResampling = PILImageResampling.BILINEAR    ,     __lowercase	:bool = True    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:bool = True    ,     __lowercase	:Union[int, float] = 1 / 255    ,     __lowercase	:bool = True    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     **__lowercase	:Tuple    ,     ):
											super().__init__(**__lowercase      )
											__lowerCamelCase   :   int       =size if size is not None else {'''shortest_edge''': 256}
											__lowerCamelCase   :   int       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											__lowerCamelCase   :   Optional[Any]       =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
											__lowerCamelCase   :   List[str]       =get_size_dict(__lowercase    ,     param_name='''crop_size'''      )
											__lowerCamelCase   :   List[str]       =do_resize
											__lowerCamelCase   :   Optional[Any]       =size
											__lowerCamelCase   :   Tuple       =resample
											__lowerCamelCase   :   int       =do_center_crop
											__lowerCamelCase   :   Optional[Any]       =crop_size
											__lowerCamelCase   :   int       =do_rescale
											__lowerCamelCase   :   str       =rescale_factor
											__lowerCamelCase   :   int       =do_normalize
											__lowerCamelCase   :   Union[str, Any]       =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
											__lowerCamelCase   :   Tuple       =image_std if image_std is not None else IMAGENET_STANDARD_STD




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Dict[str, int]    ,     __lowercase	:PILImageResampling = PILImageResampling.BICUBIC    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:str    ,     ):
											__lowerCamelCase   :   Tuple       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											if "shortest_edge" not in size:
																		raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'      )
											__lowerCamelCase   :   List[Any]       =get_resize_output_image_size(__lowercase    ,     size=size['''shortest_edge''']    ,     default_to_square=__lowercase      )
											return resize(__lowercase    ,     size=__lowercase    ,     resample=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Dict[str, int]    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:int    ,     ):
											__lowerCamelCase   :   List[Any]       =get_size_dict(__lowercase      )
											if "height" not in size or "width" not in size:
																		raise ValueError(f'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}'      )
											return center_crop(__lowercase    ,     size=(size['''height'''], size['''width'''])    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:str    ,     __lowercase	:np.ndarray    ,     __lowercase	:float    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:str      ):
											return rescale(__lowercase    ,     scale=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Union[float, List[float]]    ,     __lowercase	:Union[float, List[float]]    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:Union[str, Any]    ,     ):
											return normalize(__lowercase    ,     mean=__lowercase    ,     std=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:List[str]    ,     __lowercase	:ImageInput    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:PILImageResampling = None    ,     __lowercase	:bool = None    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Optional[float] = None    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[str, TensorType]] = None    ,     __lowercase	:Union[str, ChannelDimension] = ChannelDimension.FIRST    ,     **__lowercase	:Optional[Any]    ,     ):
											__lowerCamelCase   :   Optional[Any]       =do_resize if do_resize is not None else self.do_resize
											__lowerCamelCase   :   Optional[Any]       =size if size is not None else self.size
											__lowerCamelCase   :   List[str]       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											__lowerCamelCase   :   List[str]       =resample if resample is not None else self.resample
											__lowerCamelCase   :   Optional[int]       =do_center_crop if do_center_crop is not None else self.do_center_crop
											__lowerCamelCase   :   Any       =crop_size if crop_size is not None else self.crop_size
											__lowerCamelCase   :   Union[str, Any]       =get_size_dict(__lowercase    ,     param_name='''crop_size'''      )
											__lowerCamelCase   :   Any       =do_rescale if do_rescale is not None else self.do_rescale
											__lowerCamelCase   :   List[str]       =rescale_factor if rescale_factor is not None else self.rescale_factor
											__lowerCamelCase   :   List[Any]       =do_normalize if do_normalize is not None else self.do_normalize
											__lowerCamelCase   :   List[Any]       =image_mean if image_mean is not None else self.image_mean
											__lowerCamelCase   :   int       =image_std if image_std is not None else self.image_std

											__lowerCamelCase   :   int       =make_list_of_images(__lowercase      )

											if not valid_images(__lowercase      ):
																		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:
																		raise ValueError('''Size must be specified if do_resize is True.'''      )

											if do_center_crop and crop_size is None:
																		raise ValueError('''Crop size must be specified if do_center_crop is True.'''      )

											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.
											__lowerCamelCase   :   int       =[to_numpy_array(__lowercase      ) for image in images]

											if do_resize:
																		__lowerCamelCase   :   Tuple       =[self.resize(image=__lowercase    ,     size=__lowercase    ,     resample=__lowercase      ) for image in images]

											if do_center_crop:
																		__lowerCamelCase   :   Any       =[self.center_crop(image=__lowercase    ,     size=__lowercase      ) for image in images]

											if do_rescale:
																		__lowerCamelCase   :   Optional[Any]       =[self.rescale(image=__lowercase    ,     scale=__lowercase      ) for image in images]

											if do_normalize:
																		__lowerCamelCase   :   Tuple       =[self.normalize(image=__lowercase    ,     mean=__lowercase    ,     std=__lowercase      ) for image in images]

											__lowerCamelCase   :   List[str]       =[to_channel_dimension_format(__lowercase    ,     __lowercase      ) for image in images]

											__lowerCamelCase   :   Union[str, Any]       ={'''pixel_values''': images}
											return BatchFeature(data=__lowercase    ,     tensor_type=__lowercase      )




				def        __lowercase	(  self	:Dict    ,     __lowercase	:Dict    ,     __lowercase	:List[Tuple] = None      ):
											__lowerCamelCase   :   Dict       =outputs.logits

											# Resize logits and compute semantic segmentation maps
											if target_sizes is not None:
																		if len(__lowercase      ) != len(__lowercase      ):
																									raise ValueError(
																									    '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''      )

																		if is_torch_tensor(__lowercase      ):
																									__lowerCamelCase   :   Optional[int]       =target_sizes.numpy()

																		__lowerCamelCase   :   List[Any]       =[]

																		for idx in range(len(__lowercase      )      ):
																									__lowerCamelCase   :   Optional[int]       =torch.nn.functional.interpolate(
																									    logits[idx].unsqueeze(dim=0      )    ,     size=target_sizes[idx]    ,     mode='''bilinear'''    ,     align_corners=__lowercase      )
																									__lowerCamelCase   :   Union[str, Any]       =resized_logits[0].argmax(dim=0      )
																									semantic_segmentation.append(__lowercase      )
											else:
																		__lowerCamelCase   :   Union[str, Any]       =logits.argmax(dim=1      )
																		__lowerCamelCase   :   Optional[int]       =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]      )]

											return semantic_segmentation




