



import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


A_												=     datasets.utils.logging.get_logger(__name__)

A_												=     ['names', 'prefix']
A_												=     ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols']
A_												=     ['encoding_errors', 'on_bad_lines']
A_												=     ['date_format']

@dataclass
class SCREAMING_SNAKE_CASE_ (					datasets.BuilderConfig   ):





					"""simple docstring"""


					A__				 =    ","
					A__				 =    None
					A__				 =    "infer"
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    True
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    False
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    True
					A__				 =    True
					A__				 =    False
					A__				 =    True
					A__				 =    None
					A__				 =    "."
					A__				 =    None
					A__				 =    '"'
					A__				 =    0
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    None
					A__				 =    True
					A__				 =    True
					A__				 =    0
					A__				 =    True
					A__				 =    False
					A__				 =    None
					A__				 =    1_0_0_0_0
					A__				 =    None
					A__				 =    "strict"
					A__				 =    "error"
					A__				 =    None





					def 					__magic_name__ ( self	):
										if self.delimiter is not None:
															lowerCamelCase__       =       self.delimiter
										if self.column_names is not None:
															lowerCamelCase__       =       self.column_names






					@property
					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       {
										    """sep""": self.sep,
										    """header""": self.header,
										    """names""": self.names,
										    """index_col""": self.index_col,
										    """usecols""": self.usecols,
										    """prefix""": self.prefix,
										    """mangle_dupe_cols""": self.mangle_dupe_cols,
										    """engine""": self.engine,
										    """converters""": self.converters,
										    """true_values""": self.true_values,
										    """false_values""": self.false_values,
										    """skipinitialspace""": self.skipinitialspace,
										    """skiprows""": self.skiprows,
										    """nrows""": self.nrows,
										    """na_values""": self.na_values,
										    """keep_default_na""": self.keep_default_na,
										    """na_filter""": self.na_filter,
										    """verbose""": self.verbose,
										    """skip_blank_lines""": self.skip_blank_lines,
										    """thousands""": self.thousands,
										    """decimal""": self.decimal,
										    """lineterminator""": self.lineterminator,
										    """quotechar""": self.quotechar,
										    """quoting""": self.quoting,
										    """escapechar""": self.escapechar,
										    """comment""": self.comment,
										    """encoding""": self.encoding,
										    """dialect""": self.dialect,
										    """error_bad_lines""": self.error_bad_lines,
										    """warn_bad_lines""": self.warn_bad_lines,
										    """skipfooter""": self.skipfooter,
										    """doublequote""": self.doublequote,
										    """memory_map""": self.memory_map,
										    """float_precision""": self.float_precision,
										    """chunksize""": self.chunksize,
										    """encoding_errors""": self.encoding_errors,
										    """on_bad_lines""": self.on_bad_lines,
										    """date_format""": self.date_format,
										}

										# some kwargs must not be passed if they don't have a default value
										# some others are deprecated and we can also not pass them if they are the default value
										for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
															if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()	,  A__	):
																				del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
										if not (datasets.config.PANDAS_VERSION.major >= 2):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
																				del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
										if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
																				del pd_read_csv_kwargs[pd_read_csv_parameter]

										return pd_read_csv_kwargs

class SCREAMING_SNAKE_CASE_ (					datasets.ArrowBasedBuilder   ):





					"""simple docstring"""


					A__				 =    CsvConfig





					def 					__magic_name__ ( self	):
										return datasets.DatasetInfo(features=self.config.features	)





					def 					__magic_name__ ( self	,  _lowerCAmelCase	):
										if not self.config.data_files:
															raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}"	)
										lowerCamelCase__       =       dl_manager.download_and_extract(self.config.data_files	)
										if isinstance(A__	,  (str, list, tuple)	):
															lowerCamelCase__       =       data_files
															if isinstance(A__	,  A__	):
																				lowerCamelCase__       =       [files]
															lowerCamelCase__       =       [dl_manager.iter_files(A__	) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN	,  gen_kwargs={"files": files}	)]
										lowerCamelCase__       =       []
										for split_name, files in data_files.items():
															if isinstance(A__	,  A__	):
																				lowerCamelCase__       =       [files]
															lowerCamelCase__       =       [dl_manager.iter_files(A__	) for file in files]
															splits.append(datasets.SplitGenerator(name=A__	,  gen_kwargs={"files": files}	)	)
										return splits





					def 					__magic_name__ ( self	,  _lowerCAmelCase	):
										if self.config.features is not None:
															lowerCamelCase__       =       self.config.features.arrow_schema
															if all(not require_storage_cast(A__	) for feature in self.config.features.values()	):
																				# cheaper cast
																				lowerCamelCase__       =       pa.Table.from_arrays([pa_table[field.name] for field in schema]	,  schema=A__	)
															else:
																				# more expensive cast; allows str <-> int/float or str to Audio for example
																				lowerCamelCase__       =       table_cast(A__	,  A__	)
										return pa_table






					def 					__magic_name__ ( self	,  _lowerCAmelCase	):
										lowerCamelCase__       =       self.config.features.arrow_schema if self.config.features else None
										# dtype allows reading an int column as str
										lowerCamelCase__       =       (
										    {
										        name: dtype.to_pandas_dtype() if not require_storage_cast(A__	) else object
										        for name, dtype, feature in zip(schema.names	,  schema.types	,  self.config.features.values()	)
										    }
										    if schema is not None
										    else None
										)
										for file_idx, file in enumerate(itertools.chain.from_iterable(A__	)	):
															lowerCamelCase__       =       pd.read_csv(A__	,  iterator=A__	,  dtype=A__	,  **self.config.pd_read_csv_kwargs	)
															try:
																				for batch_idx, df in enumerate(A__	):
																									lowerCamelCase__       =       pa.Table.from_pandas(A__	)
																									# Uncomment for debugging (will print the Arrow table size and elements)
																									# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																									# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																									yield (file_idx, batch_idx), self._cast_table(A__	)
															except ValueError as e:
																				logger.error(F"Failed to read file '{file}' with error {type(A__	)}: {e}"	)
																				raise








import json
import os
import shutil
import tempfile
import unittest

import numpy as np

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


if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor

@require_tokenizers
@require_vision
class SCREAMING_SNAKE_CASE_ (					unittest.TestCase   ):





					"""simple docstring"""


					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       tempfile.mkdtemp()

										# fmt: off
										lowerCamelCase__       =       ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
										# fmt: on
										lowerCamelCase__       =       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__       =       {
										    "do_resize": True,
										    "size": {"height": 18, "width": 18},
										    "do_normalize": True,
										    "image_mean": [0.5, 0.5, 0.5],
										    "image_std": [0.5, 0.5, 0.5],
										}
										lowerCamelCase__       =       os.path.join(self.tmpdirname	,  _lowerCAmelCase	)
										with open(self.image_processor_file	,  "w"	,  encoding="utf-8"	) as fp:
															json.dump(_lowerCAmelCase	,  _lowerCAmelCase	)





					def 					__magic_name__ ( self	,  **_lowerCAmelCase	):
										return BertTokenizer.from_pretrained(self.tmpdirname	,  **_lowerCAmelCase	)





					def 					__magic_name__ ( self	,  **_lowerCAmelCase	):
										return ViTImageProcessor.from_pretrained(self.tmpdirname	,  **_lowerCAmelCase	)





					def 					__magic_name__ ( self	):
										shutil.rmtree(self.tmpdirname	)





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

										lowerCamelCase__       =       [Image.fromarray(np.moveaxis(_lowerCAmelCase	,  0	,  -1	)	) for x in image_inputs]

										return image_inputs





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_tokenizer()
										lowerCamelCase__       =       self.get_image_processor()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										processor.save_pretrained(self.tmpdirname	)
										lowerCamelCase__       =       VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname	)

										self.assertEqual(processor.tokenizer.get_vocab()	,  tokenizer.get_vocab()	)
										self.assertIsInstance(processor.tokenizer	,  (BertTokenizer, BertTokenizerFast)	)

										self.assertEqual(processor.image_processor.to_json_string()	,  image_processor.to_json_string()	)
										self.assertIsInstance(processor.image_processor	,  _lowerCAmelCase	)





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       VisionTextDualEncoderProcessor(
										    tokenizer=self.get_tokenizer()	,  image_processor=self.get_image_processor()	)
										processor.save_pretrained(self.tmpdirname	)

										lowerCamelCase__       =       self.get_tokenizer(bos_token="(BOS)"	,  eos_token="(EOS)"	)
										lowerCamelCase__       =       self.get_image_processor(do_normalize=_lowerCAmelCase	,  padding_value=1.0	)

										lowerCamelCase__       =       VisionTextDualEncoderProcessor.from_pretrained(
										    self.tmpdirname	,  bos_token="(BOS)"	,  eos_token="(EOS)"	,  do_normalize=_lowerCAmelCase	,  padding_value=1.0	)

										self.assertEqual(processor.tokenizer.get_vocab()	,  tokenizer_add_kwargs.get_vocab()	)
										self.assertIsInstance(processor.tokenizer	,  (BertTokenizer, BertTokenizerFast)	)

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





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       image_processor(_lowerCAmelCase	,  return_tensors="np"	)
										lowerCamelCase__       =       processor(images=_lowerCAmelCase	,  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 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	)

										lowerCamelCase__       =       tokenizer(_lowerCAmelCase	)

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





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"
										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	,  images=_lowerCAmelCase	)

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

										# test if it raises when no input is passed
										with self.assertRaises(_lowerCAmelCase	):
															processor()





					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

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

										lowerCamelCase__       =       processor.batch_decode(_lowerCAmelCase	)
										lowerCamelCase__       =       tokenizer.batch_decode(_lowerCAmelCase	)

										self.assertListEqual(_lowerCAmelCase	,  _lowerCAmelCase	)






					def 					__magic_name__ ( self	):
										lowerCamelCase__       =       self.get_image_processor()
										lowerCamelCase__       =       self.get_tokenizer()

										lowerCamelCase__       =       VisionTextDualEncoderProcessor(tokenizer=_lowerCAmelCase	,  image_processor=_lowerCAmelCase	)

										lowerCamelCase__       =       "lower newer"
										lowerCamelCase__       =       self.prepare_image_inputs()

										lowerCamelCase__       =       processor(text=_lowerCAmelCase	,  images=_lowerCAmelCase	)

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

