






'''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     :      List[Any]   					=logging.get_logger(__name__)

_A     :      Optional[int]   					=list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_A     :      Union[str, Any]   					=tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class _lowercase     :
							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=128    ,				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=128    ,				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 _lowercase     (    _lowercase		):
							a    				=	"""train"""
							a    				=	"""dev"""



class _lowercase     (    _lowercase		):
							a    				=	42
							a    				=	42
							a    				=	42
							a    				=	42




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

																												# Legacy cache files have only features, while new cache files
																												# will have dataset and examples also.
																												lowerCamelCase__ :     int	  =	self.old_features["""features"""]
																												lowerCamelCase__ :     int	  =	self.old_features.get("""dataset"""      ,							UpperCamelCase__					)
																												lowerCamelCase__ :     Dict	  =	self.old_features.get("""examples"""      ,							UpperCamelCase__					)
																												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__ :     Union[str, Any]	  =	self.processor.get_train_examples(args.data_dir					)

																												lowerCamelCase__  ,		lowerCamelCase__ :     List[Any]	  =	squad_convert_examples_to_features(
																												    examples=self.examples      ,							tokenizer=UpperCamelCase__      ,							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=UpperCamelCase__      ,							)

																												lowerCamelCase__ :     Dict	  =	time.time()
																												torch.save(
																												    {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}      ,							UpperCamelCase__      ,							)
																												# ^ 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:    Union[str, Any]					):
														return len(self.features					)




							def __getitem__(							self:    List[str]      ,							UpperCamelCase__:    List[str]					):
														# Convert to Tensors and build dataset
														lowerCamelCase__ :     str	  =	self.features[i]

														lowerCamelCase__ :     str	  =	torch.tensor(feature.input_ids      ,							dtype=torch.long					)
														lowerCamelCase__ :     int	  =	torch.tensor(feature.attention_mask      ,							dtype=torch.long					)
														lowerCamelCase__ :     List[Any]	  =	torch.tensor(feature.token_type_ids      ,							dtype=torch.long					)
														lowerCamelCase__ :     List[Any]	  =	torch.tensor(feature.cls_index      ,							dtype=torch.long					)
														lowerCamelCase__ :     Dict	  =	torch.tensor(feature.p_mask      ,							dtype=torch.float					)
														lowerCamelCase__ :     Dict	  =	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__ :     Dict	  =	torch.tensor(feature.start_position      ,							dtype=torch.long					)
																					lowerCamelCase__ :     Dict	  =	torch.tensor(feature.end_position      ,							dtype=torch.long					)
																					inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions}					)

														return inputs









'''simple docstring'''







import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
			from PIL import Image

			from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor

@require_vision
class _lowercase     (    unittest.TestCase		):




							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														lowerCamelCase__ :     Any	  =	tempfile.mkdtemp()

														lowerCamelCase__ :     Any	  =	[
														    """[UNK]""",
														    """[CLS]""",
														    """[SEP]""",
														    """[PAD]""",
														    """[MASK]""",
														    """的""",
														    """价""",
														    """格""",
														    """是""",
														    """15""",
														    """便""",
														    """alex""",
														    """##andra""",
														    """，""",
														    """。""",
														    """-""",
														    """t""",
														    """shirt""",
														]
														lowerCamelCase__ :     Optional[int]	  =	os.path.join(self.tmpdirname      ,							VOCAB_FILES_NAMES["""vocab_file"""]					)
														with open(self.vocab_file      ,							"""w"""      ,							encoding="""utf-8"""					) as vocab_writer:
																					vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]					)					)

														lowerCamelCase__ :     Union[str, Any]	  =	{
														    """do_resize""": True,
														    """size""": {"""height""": 224, """width""": 224},
														    """do_center_crop""": True,
														    """crop_size""": {"""height""": 18, """width""": 18},
														    """do_normalize""": True,
														    """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073],
														    """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711],
														    """do_convert_rgb""": True,
														}
														lowerCamelCase__ :     Optional[int]	  =	os.path.join(self.tmpdirname      ,							UpperCamelCase__					)
														with open(self.image_processor_file      ,							"""w"""      ,							encoding="""utf-8"""					) as fp:
																					json.dump(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    List[Any]      ,							**UpperCamelCase__:    Optional[int]					):
														return BertTokenizer.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Any      ,							**UpperCamelCase__:    List[str]					):
														return BertTokenizerFast.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    str      ,							**UpperCamelCase__:    int					):
														return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														shutil.rmtree(self.tmpdirname					)




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     int	  =	[np.random.randint(255      ,							size=(3, 30, 400)      ,							dtype=np.uinta					)]

														lowerCamelCase__ :     List[str]	  =	[Image.fromarray(np.moveaxis(UpperCamelCase__      ,							0      ,							-1					)					) for x in image_inputs]

														return image_inputs




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     Tuple	  =	self.get_tokenizer()
														lowerCamelCase__ :     Any	  =	self.get_rust_tokenizer()
														lowerCamelCase__ :     str	  =	self.get_image_processor()

														lowerCamelCase__ :     str	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)
														processor_slow.save_pretrained(self.tmpdirname					)
														lowerCamelCase__ :     List[Any]	  =	ChineseCLIPProcessor.from_pretrained(self.tmpdirname      ,							use_fast=UpperCamelCase__					)

														lowerCamelCase__ :     Any	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)
														processor_fast.save_pretrained(self.tmpdirname					)
														lowerCamelCase__ :     List[Any]	  =	ChineseCLIPProcessor.from_pretrained(self.tmpdirname					)

														self.assertEqual(processor_slow.tokenizer.get_vocab()      ,							tokenizer_slow.get_vocab()					)
														self.assertEqual(processor_fast.tokenizer.get_vocab()      ,							tokenizer_fast.get_vocab()					)
														self.assertEqual(tokenizer_slow.get_vocab()      ,							tokenizer_fast.get_vocab()					)
														self.assertIsInstance(processor_slow.tokenizer      ,							UpperCamelCase__					)
														self.assertIsInstance(processor_fast.tokenizer      ,							UpperCamelCase__					)

														self.assertEqual(processor_slow.image_processor.to_json_string()      ,							image_processor.to_json_string()					)
														self.assertEqual(processor_fast.image_processor.to_json_string()      ,							image_processor.to_json_string()					)
														self.assertIsInstance(processor_slow.image_processor      ,							UpperCamelCase__					)
														self.assertIsInstance(processor_fast.image_processor      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														lowerCamelCase__ :     Optional[int]	  =	ChineseCLIPProcessor(tokenizer=self.get_tokenizer()      ,							image_processor=self.get_image_processor()					)
														processor.save_pretrained(self.tmpdirname					)

														lowerCamelCase__ :     str	  =	self.get_tokenizer(cls_token="""(CLS)"""      ,							sep_token="""(SEP)"""					)
														lowerCamelCase__ :     Optional[int]	  =	self.get_image_processor(do_normalize=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[int]	  =	ChineseCLIPProcessor.from_pretrained(
														    self.tmpdirname      ,							cls_token="""(CLS)"""      ,							sep_token="""(SEP)"""      ,							do_normalize=UpperCamelCase__					)

														self.assertEqual(processor.tokenizer.get_vocab()      ,							tokenizer_add_kwargs.get_vocab()					)
														self.assertIsInstance(processor.tokenizer      ,							UpperCamelCase__					)

														self.assertEqual(processor.image_processor.to_json_string()      ,							image_processor_add_kwargs.to_json_string()					)
														self.assertIsInstance(processor.image_processor      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     Optional[Any]	  =	self.get_image_processor()
														lowerCamelCase__ :     Optional[int]	  =	self.get_tokenizer()

														lowerCamelCase__ :     int	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Tuple	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     str	  =	image_processor(UpperCamelCase__      ,							return_tensors="""np"""					)
														lowerCamelCase__ :     Optional[int]	  =	processor(images=UpperCamelCase__      ,							return_tensors="""np"""					)

														for key in input_feat_extract.keys():
																					self.assertAlmostEqual(input_feat_extract[key].sum()      ,							input_processor[key].sum()      ,							delta=1e-2					)




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     int	  =	self.get_image_processor()
														lowerCamelCase__ :     Optional[int]	  =	self.get_tokenizer()

														lowerCamelCase__ :     Union[str, Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Union[str, Any]	  =	"""Alexandra，T-shirt的价格是15便士。"""

														lowerCamelCase__ :     Optional[Any]	  =	processor(text=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[Any]	  =	tokenizer(UpperCamelCase__					)

														for key in encoded_tok.keys():
																					self.assertListEqual(encoded_tok[key]      ,							encoded_processor[key]					)




							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														lowerCamelCase__ :     Optional[int]	  =	self.get_image_processor()
														lowerCamelCase__ :     List[Any]	  =	self.get_tokenizer()

														lowerCamelCase__ :     Optional[Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Dict	  =	"""Alexandra，T-shirt的价格是15便士。"""
														lowerCamelCase__ :     Any	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     Optional[int]	  =	processor(text=UpperCamelCase__      ,							images=UpperCamelCase__					)

														self.assertListEqual(list(inputs.keys()					)      ,							["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""]					)

														# test if it raises when no input is passed
														with pytest.raises(UpperCamelCase__					):
																					processor()




							def 		lowerCamelCase_    (							self:    Dict					):
														lowerCamelCase__ :     Dict	  =	self.get_image_processor()
														lowerCamelCase__ :     Any	  =	self.get_tokenizer()

														lowerCamelCase__ :     Union[str, Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     str	  =	[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

														lowerCamelCase__ :     Any	  =	processor.batch_decode(UpperCamelCase__					)
														lowerCamelCase__ :     int	  =	tokenizer.batch_decode(UpperCamelCase__					)

														self.assertListEqual(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														lowerCamelCase__ :     Dict	  =	self.get_image_processor()
														lowerCamelCase__ :     int	  =	self.get_tokenizer()

														lowerCamelCase__ :     Optional[Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[Any]	  =	"""Alexandra，T-shirt的价格是15便士。"""
														lowerCamelCase__ :     Tuple	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     str	  =	processor(text=UpperCamelCase__      ,							images=UpperCamelCase__					)

														self.assertListEqual(list(inputs.keys()					)      ,							processor.model_input_names					)

