





"""simple docstring"""




from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFCvtForImageClassification, TFCvtModel
		from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor


class  __UpperCamelCase       (		a__		):






							def 					__a     (     self   )			->				Optional[Any]:
								a   :	Tuple			=       self.config_class(**self.inputs_dict   )
								self.parent.assertTrue(hasattr(lowerCAmelCase__   ,      "embed_dim"   )   )
								self.parent.assertTrue(hasattr(lowerCAmelCase__   ,      "num_heads"   )   )


class  __UpperCamelCase       :






							def __init__(     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__=13   ,      lowerCAmelCase__=64   ,      lowerCAmelCase__=3   ,      lowerCAmelCase__=[16, 48, 96]   ,      lowerCAmelCase__=[1, 3, 6]   ,      lowerCAmelCase__=[1, 2, 10]   ,      lowerCAmelCase__=[7, 3, 3]   ,      lowerCAmelCase__=[4, 2, 2]   ,      lowerCAmelCase__=[2, 1, 1]   ,      lowerCAmelCase__=[2, 2, 2]   ,      lowerCAmelCase__=[False, False, True]   ,      lowerCAmelCase__=[0.0, 0.0, 0.0]   ,      lowerCAmelCase__=0.02   ,      lowerCAmelCase__=1E-12   ,      lowerCAmelCase__=True   ,      lowerCAmelCase__=True   ,      lowerCAmelCase__=2   ,      )			->				List[Any]:
								a   :	List[str]			=       parent
								a   :	Tuple			=       batch_size
								a   :	str			=       image_size
								a   :	List[Any]			=       patch_sizes
								a   :	List[Any]			=       patch_stride
								a   :	int			=       patch_padding
								a   :	int			=       is_training
								a   :	str			=       use_labels
								a   :	List[str]			=       num_labels
								a   :	str			=       num_channels
								a   :	Optional[int]			=       embed_dim
								a   :	Optional[Any]			=       num_heads
								a   :	Tuple			=       stride_kv
								a   :	Union[str, Any]			=       depth
								a   :	Optional[Any]			=       cls_token
								a   :	List[Any]			=       attention_drop_rate
								a   :	List[str]			=       initializer_range
								a   :	str			=       layer_norm_eps






							def 					__a     (     self   )			->				Any:
								a   :	Dict			=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

								a   :	Any			=       None
								if self.use_labels:
									# create a random int32 tensor of given shape
									a   :	Dict			=       ids_tensor([self.batch_size]   ,      self.num_labels   )

								a   :	int			=       self.get_config()
								return config, pixel_values, labels






							def 					__a     (     self   )			->				List[Any]:
								return CvtConfig(
								    image_size=self.image_size   ,      num_labels=self.num_labels   ,      num_channels=self.num_channels   ,      embed_dim=self.embed_dim   ,      num_heads=self.num_heads   ,      patch_sizes=self.patch_sizes   ,      patch_padding=self.patch_padding   ,      patch_stride=self.patch_stride   ,      stride_kv=self.stride_kv   ,      depth=self.depth   ,      cls_token=self.cls_token   ,      attention_drop_rate=self.attention_drop_rate   ,      initializer_range=self.initializer_range   ,      )






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				Optional[int]:
								a   :	List[str]			=       TFCvtModel(config=lowerCAmelCase__   )
								a   :	Optional[Any]			=       model(lowerCAmelCase__   ,      training=lowerCAmelCase__   )
								a   :	List[str]			=       (self.image_size, self.image_size)
								a, a   :	List[str]			=       image_size[0], image_size[1]
								for i in range(len(self.depth   )   ):
									a   :	Union[str, Any]			=       floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
									a   :	List[Any]			=       floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
								self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.embed_dim[-1], height, width)   )






							def 					__a     (     self   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )			->				Dict:
								a   :	Tuple			=       self.num_labels
								a   :	Any			=       TFCvtForImageClassification(lowerCAmelCase__   )
								a   :	int			=       model(lowerCAmelCase__   ,      labels=lowerCAmelCase__   ,      training=lowerCAmelCase__   )
								self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels)   )






							def 					__a     (     self   )			->				Tuple:
								a   :	List[str]			=       self.prepare_config_and_inputs()
								a, a, a   :	Optional[int]			=       config_and_inputs
								a   :	int			=       {"pixel_values": pixel_values}
								return config, inputs_dict


@require_tf
class  __UpperCamelCase       (		a__	, a__	, unittest.TestCase		):
							lowerCamelCase     :      List[str]         =(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
							lowerCamelCase     :      List[Any]         =(
							    {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
							    if is_tf_available()
							    else {}
							)
							lowerCamelCase     :      Optional[Any]         =False
							lowerCamelCase     :      List[str]         =False
							lowerCamelCase     :      Optional[Any]         =False
							lowerCamelCase     :      int         =False
							lowerCamelCase     :      Dict         =False






							def 					__a     (     self   )			->				Optional[int]:
								a   :	Dict			=       TFCvtModelTester(self   )
								a   :	List[Any]			=       TFCvtConfigTester(self   ,      config_class=lowerCAmelCase__   ,      has_text_modality=lowerCAmelCase__   ,      hidden_size=37   )






							def 					__a     (     self   )			->				Optional[Any]:
								self.config_tester.create_and_test_config_common_properties()
								self.config_tester.create_and_test_config_to_json_string()
								self.config_tester.create_and_test_config_to_json_file()
								self.config_tester.create_and_test_config_from_and_save_pretrained()
								self.config_tester.create_and_test_config_with_num_labels()
								self.config_tester.check_config_can_be_init_without_params()
								self.config_tester.check_config_arguments_init()






							@unittest.skip(reason="Cvt does not output attentions"   )
							def 					__a     (     self   )			->				Dict:
								pass






							@unittest.skip(reason="Cvt does not use inputs_embeds"   )
							def 					__a     (     self   )			->				Union[str, Any]:
								pass






							@unittest.skip(reason="Cvt does not support input and output embeddings"   )
							def 					__a     (     self   )			->				Union[str, Any]:
								pass






							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("GPU"   )   ) == 0   ,      reason="TF does not support backprop for grouped convolutions on CPU."   ,      )
							def 					__a     (     self   )			->				List[Any]:
								super().test_dataset_conversion()






							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("GPU"   )   ) == 0   ,      reason="TF does not support backprop for grouped convolutions on CPU."   ,      )
							@slow
							def 					__a     (     self   )			->				Optional[int]:
								super().test_keras_fit()






							@unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"   )
							def 					__a     (     self   )			->				int:
								a   :	Optional[int]			=       tf.keras.mixed_precision.Policy("mixed_float16"   )
								tf.keras.mixed_precision.set_global_policy(lowerCAmelCase__   )
								super().test_keras_fit()
								tf.keras.mixed_precision.set_global_policy("float32"   )






							def 					__a     (     self   )			->				Any:
								a, a   :	Dict			=       self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a   :	List[str]			=       model_class(lowerCAmelCase__   )
									a   :	Optional[int]			=       inspect.signature(model.call   )
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									a   :	Dict			=       [*signature.parameters.keys()]

									a   :	Union[str, Any]			=       ["pixel_values"]
									self.assertListEqual(arg_names[:1]   ,      lowerCAmelCase__   )






							def 					__a     (     self   )			->				int:
								def check_hidden_states_output(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   ):
									a   :	Union[str, Any]			=       model_class(lowerCAmelCase__   )

									a   :	Union[str, Any]			=       model(**self._prepare_for_class(lowerCAmelCase__   ,      lowerCAmelCase__   )   )
									a   :	Dict			=       outputs.hidden_states

									a   :	Any			=       len(self.model_tester.depth   )
									self.assertEqual(len(lowerCAmelCase__   )   ,      lowerCAmelCase__   )

									# verify the first hidden states (first block)
									self.assertListEqual(
									    list(hidden_states[0].shape[-3:]   )   ,      [
									        self.model_tester.embed_dim[0],
									        self.model_tester.image_size // 4,
									        self.model_tester.image_size // 4,
									    ]   ,      )

								a, a   :	Optional[int]			=       self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									a   :	Dict			=       True
									check_hidden_states_output(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									a   :	Optional[int]			=       True

									check_hidden_states_output(lowerCAmelCase__   ,      lowerCAmelCase__   ,      lowerCAmelCase__   )






							def 					__a     (     self   )			->				Union[str, Any]:
								a   :	Tuple			=       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCAmelCase__   )






							def 					__a     (     self   )			->				Any:
								a   :	Dict			=       self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__   )






							@slow
							def 					__a     (     self   )			->				str:
								for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									a   :	Tuple			=       TFCvtModel.from_pretrained(lowerCAmelCase__   )
									self.assertIsNotNone(lowerCAmelCase__   )






def    _SCREAMING_SNAKE_CASE	(			)				->int:






	'''simple docstring'''






	a   :	Optional[Any]			=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
	return image







@require_tf
@require_vision
class  __UpperCamelCase       (		unittest.TestCase		):






							@cached_property
							def 					__a     (     self   )			->				Optional[Any]:
								return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )






							@slow
							def 					__a     (     self   )			->				Optional[Any]:
								a   :	Union[str, Any]			=       TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )

								a   :	Any			=       self.default_image_processor
								a   :	Any			=       prepare_img()
								a   :	str			=       image_processor(images=lowerCAmelCase__   ,      return_tensors="tf"   )

								# forward pass
								a   :	List[str]			=       model(**lowerCAmelCase__   )

								# verify the logits
								a   :	Dict			=       tf.TensorShape((1, 1000)   )
								self.assertEqual(outputs.logits.shape   ,      lowerCAmelCase__   )

								a   :	str			=       tf.constant([0.9_285, 0.9_015, -0.3_150]   )
								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()   ,      lowerCAmelCase__   ,      atol=1E-4   )   )









"""simple docstring"""




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		:				Optional[Any]  			=    datasets.utils.logging.get_logger(__name__)

a		:				Union[str, Any]  			=    ['''names''', '''prefix''']
a		:				Any  			=    ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
a		:				Any  			=    ['''encoding_errors''', '''on_bad_lines''']
a		:				List[str]  			=    ['''date_format''']


@dataclass
class  __UpperCamelCase       (		datasets.BuilderConfig		):
							lowerCamelCase     :      str         =","
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      Optional[Union[int, List[int], str]]         ="infer"
							lowerCamelCase     :      Optional[List[str]]         =None
							lowerCamelCase     :      Optional[List[str]]         =None
							lowerCamelCase     :      Optional[Union[int, str, List[int], List[str]]]         =None
							lowerCamelCase     :      Optional[Union[List[int], List[str]]]         =None
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      Optional[Literal["c", "python", "pyarrow"]]         =None
							lowerCamelCase     :      Dict[Union[int, str], Callable[[Any], Any]]         =None
							lowerCamelCase     :      Optional[list]         =None
							lowerCamelCase     :      Optional[list]         =None
							lowerCamelCase     :      bool         =False
							lowerCamelCase     :      Optional[Union[int, List[int]]]         =None
							lowerCamelCase     :      Optional[int]         =None
							lowerCamelCase     :      Optional[Union[str, List[str]]]         =None
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      bool         =False
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      str         ="."
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      str         ='"'
							lowerCamelCase     :      int         =0
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      int         =0
							lowerCamelCase     :      bool         =True
							lowerCamelCase     :      bool         =False
							lowerCamelCase     :      Optional[str]         =None
							lowerCamelCase     :      int         =1_0000
							lowerCamelCase     :      Optional[datasets.Features]         =None
							lowerCamelCase     :      Optional[str]         ="strict"
							lowerCamelCase     :      Literal["error", "warn", "skip"]         ="error"
							lowerCamelCase     :      Optional[str]         =None






							def 					__a     (     self   )			->				Dict:
								if self.delimiter is not None:
									a   :	int			=       self.delimiter
								if self.column_names is not None:
									a   :	Any			=       self.column_names






							@property
							def 					__a     (     self   )			->				List[str]:
								a   :	Dict			=       {
								    "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()   ,      lowerCAmelCase__   ):
										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  __UpperCamelCase       (		datasets.ArrowBasedBuilder		):
							lowerCamelCase     :      Union[str, Any]         =CsvConfig






							def 					__a     (     self   )			->				Optional[Any]:
								return datasets.DatasetInfo(features=self.config.features   )






							def 					__a     (     self   ,      lowerCAmelCase__   )			->				Optional[int]:
								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}"""   )
								a   :	Optional[Any]			=       dl_manager.download_and_extract(self.config.data_files   )
								if isinstance(lowerCAmelCase__   ,      (str, list, tuple)   ):
									a   :	Tuple			=       data_files
									if isinstance(lowerCAmelCase__   ,      lowerCAmelCase__   ):
										a   :	Tuple			=       [files]
									a   :	int			=       [dl_manager.iter_files(lowerCAmelCase__   ) for file in files]
									return [datasets.SplitGenerator(name=datasets.Split.TRAIN   ,      gen_kwargs={"files": files}   )]
								a   :	int			=       []
								for split_name, files in data_files.items():
									if isinstance(lowerCAmelCase__   ,      lowerCAmelCase__   ):
										a   :	Any			=       [files]
									a   :	List[str]			=       [dl_manager.iter_files(lowerCAmelCase__   ) for file in files]
									splits.append(datasets.SplitGenerator(name=lowerCAmelCase__   ,      gen_kwargs={"files": files}   )   )
								return splits






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






							def 					__a     (     self   ,      lowerCAmelCase__   )			->				Any:
								a   :	Tuple			=       self.config.features.arrow_schema if self.config.features else None
								# dtype allows reading an int column as str
								a   :	Any			=       (
								    {
								        name: dtype.to_pandas_dtype() if not require_storage_cast(lowerCAmelCase__   ) 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(lowerCAmelCase__   )   ):
									a   :	Tuple			=       pd.read_csv(lowerCAmelCase__   ,      iterator=lowerCAmelCase__   ,      dtype=lowerCAmelCase__   ,      **self.config.pd_read_csv_kwargs   )
									try:
										for batch_idx, df in enumerate(lowerCAmelCase__   ):
											a   :	Any			=       pa.Table.from_pandas(lowerCAmelCase__   )
											# 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(lowerCAmelCase__   )
									except ValueError as e:
										logger.error(f"""Failed to read file '{file}' with error {type(lowerCAmelCase__   )}: {e}"""   )
										raise


