
'''simple docstring'''

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
				from PIL import Image

				from transformers import ConvNextImageProcessor







class   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case=1_3   ,      snake_case=3_2   ,      snake_case=3   ,      snake_case=4   ,      snake_case=[1_0, 2_0, 3_0, 4_0]   ,      snake_case=[2, 2, 3, 2]   ,      snake_case=True   ,      snake_case=True   ,      snake_case=3_7   ,      snake_case="gelu"   ,      snake_case=1_0   ,      snake_case=0.02   ,      snake_case=3   ,      snake_case=None   ,      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       parent
							UpperCAmelCase		:							str        =       batch_size
							UpperCAmelCase		:							List[str]        =       image_size
							UpperCAmelCase		:							List[Any]        =       num_channels
							UpperCAmelCase		:							Union[str, Any]        =       num_stages
							UpperCAmelCase		:							Tuple        =       hidden_sizes
							UpperCAmelCase		:							Union[str, Any]        =       depths
							UpperCAmelCase		:							Dict        =       is_training
							UpperCAmelCase		:							Optional[int]        =       use_labels
							UpperCAmelCase		:							int        =       intermediate_size
							UpperCAmelCase		:							int        =       hidden_act
							UpperCAmelCase		:							Dict        =       type_sequence_label_size
							UpperCAmelCase		:							int        =       initializer_range
							UpperCAmelCase		:							Dict        =       scope







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Tuple        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

							UpperCAmelCase		:							List[Any]        =       None
							if self.use_labels:
												UpperCAmelCase		:							Optional[Any]        =       ids_tensor([self.batch_size]   ,      self.type_sequence_label_size      )

							UpperCAmelCase		:							Union[str, Any]        =       self.get_config()

							return config, pixel_values, labels







		def 				A_	(			self      ):


							'''simple docstring'''

							return ConvNextConfig(
							    num_channels=self.num_channels   ,      hidden_sizes=self.hidden_sizes   ,      depths=self.depths   ,      num_stages=self.num_stages   ,      hidden_act=self.hidden_act   ,      is_decoder=snake_case   ,      initializer_range=self.initializer_range   ,      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       TFConvNextModel(config=snake_case      )
							UpperCAmelCase		:							Dict        =       model(snake_case   ,      training=snake_case      )
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape   ,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)   ,      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]        =       self.type_sequence_label_size
							UpperCAmelCase		:							List[str]        =       TFConvNextForImageClassification(snake_case      )
							UpperCAmelCase		:							Optional[int]        =       model(snake_case   ,      labels=snake_case   ,      training=snake_case      )
							self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.type_sequence_label_size)      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       self.prepare_config_and_inputs()
							UpperCAmelCase		:							int        =       config_and_inputs
							UpperCAmelCase		:							Any        =       {"pixel_values": pixel_values}
							return config, inputs_dict







@require_tf
class   UpperCamelCase__   (       lowercase__							,							lowercase__							,							unittest.TestCase       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     List[str]       =							(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
		SCREAMING_SNAKE_CASE__  :     int       =							(
		    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
		    if is_tf_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE__  :     List[str]       =							False
		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							False
		SCREAMING_SNAKE_CASE__  :     Optional[int]       =							False
		SCREAMING_SNAKE_CASE__  :     str       =							False
		SCREAMING_SNAKE_CASE__  :     str       =							False







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       TFConvNextModelTester(self      )
							UpperCAmelCase		:							Tuple        =       ConfigTester(
							    self   ,      config_class=snake_case   ,      has_text_modality=snake_case   ,      hidden_size=3_7   ,      )







		@unittest.skip(reason="ConvNext does not use inputs_embeds"      )
		def 				A_	(			self      ):


							'''simple docstring'''

							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."   ,      )
		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							super().test_keras_fit()







		@unittest.skip(reason="ConvNext does not support input and output embeddings"      )
		def 				A_	(			self      ):


							'''simple docstring'''

							pass







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       self.model_tester.prepare_config_and_inputs_for_common()

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

												UpperCAmelCase		:							Optional[int]        =       ["pixel_values"]
												self.assertListEqual(arg_names[:1]   ,      snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[int]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case      )







		@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      ):


							'''simple docstring'''

							super().test_dataset_conversion()







		def 				A_	(			self      ):


							'''simple docstring'''

							def check_hidden_states_output(snake_case   ,      snake_case   ,      snake_case      ):
												UpperCAmelCase		:							List[Any]        =       model_class(snake_case      )

												UpperCAmelCase		:							Any        =       model(**self._prepare_for_class(snake_case   ,      snake_case      )      )
												UpperCAmelCase		:							Tuple        =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												UpperCAmelCase		:							int        =       self.model_tester.num_stages
												self.assertEqual(len(snake_case      )   ,      expected_num_stages + 1      )

												# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
												self.assertListEqual(
												    list(hidden_states[0].shape[-2:]      )   ,      [self.model_tester.image_size // 4, self.model_tester.image_size // 4]   ,      )

							UpperCAmelCase		:							Dict        =       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												UpperCAmelCase		:							List[Any]        =       True
												check_hidden_states_output(snake_case   ,      snake_case   ,      snake_case      )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												UpperCAmelCase		:							Union[str, Any]        =       True

												check_hidden_states_output(snake_case   ,      snake_case   ,      snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(snake_case   ,      snake_case   ,      snake_case   ,      snake_case={}      ):
												UpperCAmelCase		:							Optional[Any]        =       model(snake_case   ,      return_dict=snake_case   ,      **snake_case      )
												UpperCAmelCase		:							Any        =       model(snake_case   ,      return_dict=snake_case   ,      **snake_case      ).to_tuple()

												def recursive_check(snake_case   ,      snake_case      ):
																	if isinstance(snake_case   ,      (List, Tuple)      ):
																						for tuple_iterable_value, dict_iterable_value in zip(snake_case   ,      snake_case      ):
																											recursive_check(snake_case   ,      snake_case      )
																	elif tuple_object is None:
																						return
																	else:
																						self.assertTrue(
																						    all(tf.equal(snake_case   ,      snake_case      )      )   ,      msg=(
																						        "Tuple and dict output are not equal. Difference:"
																						        f" {tf.math.reduce_max(tf.abs(tuple_object - dict_object      )      )}"
																						    )   ,      )

																	recursive_check(snake_case   ,      snake_case      )

							for model_class in self.all_model_classes:
												UpperCAmelCase		:							str        =       model_class(snake_case      )

												UpperCAmelCase		:							Optional[int]        =       self._prepare_for_class(snake_case   ,      snake_case      )
												UpperCAmelCase		:							Any        =       self._prepare_for_class(snake_case   ,      snake_case      )
												check_equivalence(snake_case   ,      snake_case   ,      snake_case      )

												UpperCAmelCase		:							int        =       self._prepare_for_class(snake_case   ,      snake_case   ,      return_labels=snake_case      )
												UpperCAmelCase		:							Optional[Any]        =       self._prepare_for_class(snake_case   ,      snake_case   ,      return_labels=snake_case      )
												check_equivalence(snake_case   ,      snake_case   ,      snake_case      )

												UpperCAmelCase		:							Union[str, Any]        =       self._prepare_for_class(snake_case   ,      snake_case      )
												UpperCAmelCase		:							Union[str, Any]        =       self._prepare_for_class(snake_case   ,      snake_case      )
												check_equivalence(snake_case   ,      snake_case   ,      snake_case   ,      {"output_hidden_states": True}      )

												UpperCAmelCase		:							List[Any]        =       self._prepare_for_class(snake_case   ,      snake_case   ,      return_labels=snake_case      )
												UpperCAmelCase		:							Any        =       self._prepare_for_class(snake_case   ,      snake_case   ,      return_labels=snake_case      )
												check_equivalence(snake_case   ,      snake_case   ,      snake_case   ,      {"output_hidden_states": True}      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*snake_case      )







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"      )
							self.assertIsNotNone(snake_case      )





def 				lowercase (					):



					'''simple docstring'''







					UpperCAmelCase		:							Dict        =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
					return image







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


		"""simple docstring"""

		@cached_property
		def 				A_	(			self      ):


							'''simple docstring'''

							return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"      ) if is_vision_available() else None







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"      )

							UpperCAmelCase		:							Dict        =       self.default_image_processor
							UpperCAmelCase		:							Union[str, Any]        =       prepare_img()
							UpperCAmelCase		:							str        =       image_processor(images=snake_case   ,      return_tensors="tf"      )

							# forward pass
							UpperCAmelCase		:							Tuple        =       model(**snake_case      )

							# verify the logits
							UpperCAmelCase		:							Tuple        =       tf.TensorShape((1, 1_0_0_0)      )
							self.assertEqual(outputs.logits.shape   ,      snake_case      )

							UpperCAmelCase		:							Any        =       tf.constant([-0.0260, -0.4739, 0.1911]      )

							tf.debugging.assert_near(outputs.logits[0, :3]   ,      snake_case   ,      atol=1e-4      )



'''simple docstring'''

import multiprocessing
import os
from typing import BinaryIO, Optional, Union

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.csv.csv import Csv
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      snake_case = None   ,      snake_case = False   ,      snake_case = False   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							super().__init__(
							    snake_case   ,      split=snake_case   ,      features=snake_case   ,      cache_dir=snake_case   ,      keep_in_memory=snake_case   ,      streaming=snake_case   ,      num_proc=snake_case   ,      **snake_case   ,      )
							UpperCAmelCase		:							str        =       path_or_paths if isinstance(snake_case   ,      snake_case      ) else {self.split: path_or_paths}
							UpperCAmelCase		:							int        =       Csv(
							    cache_dir=snake_case   ,      data_files=snake_case   ,      features=snake_case   ,      **snake_case   ,      )







		def 				A_	(			self      ):


							'''simple docstring'''

							if self.streaming:
												UpperCAmelCase		:							Optional[Any]        =       self.builder.as_streaming_dataset(split=self.split      )
							# Build regular (map-style) dataset
							else:
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							str        =       None
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							int        =       None

												self.builder.download_and_prepare(
												    download_config=snake_case   ,      download_mode=snake_case   ,      verification_mode=snake_case   ,      base_path=snake_case   ,      num_proc=self.num_proc   ,      )
												UpperCAmelCase		:							Tuple        =       self.builder.as_dataset(
												    split=self.split   ,      verification_mode=snake_case   ,      in_memory=self.keep_in_memory      )
							return dataset







class   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							if num_proc is not None and num_proc <= 0:
												raise ValueError(f"num_proc {num_proc} must be an integer > 0."      )

							UpperCAmelCase		:							Tuple        =       dataset
							UpperCAmelCase		:							Dict        =       path_or_buf
							UpperCAmelCase		:							List[Any]        =       batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
							UpperCAmelCase		:							str        =       num_proc
							UpperCAmelCase		:							List[Any]        =       "utf-8"
							UpperCAmelCase		:							Tuple        =       to_csv_kwargs







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.to_csv_kwargs.pop("path_or_buf"   ,      snake_case      )
							UpperCAmelCase		:							Any        =       self.to_csv_kwargs.pop("header"   ,      snake_case      )
							UpperCAmelCase		:							Dict        =       self.to_csv_kwargs.pop("index"   ,      snake_case      )

							if isinstance(self.path_or_buf   ,      (str, bytes, os.PathLike)      ):
												with open(self.path_or_buf   ,      "wb+"      ) as buffer:
																	UpperCAmelCase		:							Tuple        =       self._write(file_obj=snake_case   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							else:
												UpperCAmelCase		:							Any        =       self._write(file_obj=self.path_or_buf   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							return written







		def 				A_	(			self   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase		:							Optional[int]        =       args

							UpperCAmelCase		:							List[str]        =       query_table(
							    table=self.dataset.data   ,      key=slice(snake_case   ,      offset + self.batch_size      )   ,      indices=self.dataset._indices   ,      )
							UpperCAmelCase		:							int        =       batch.to_pandas().to_csv(
							    path_or_buf=snake_case   ,      header=header if (offset == 0) else False   ,      index=snake_case   ,      **snake_case      )
							return csv_str.encode(self.encoding      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      **snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       0

							if self.num_proc is None or self.num_proc == 1:
												for offset in logging.tqdm(
												    range(0   ,      len(self.dataset      )   ,      self.batch_size      )   ,      unit="ba"   ,      disable=not logging.is_progress_bar_enabled()   ,      desc="Creating CSV from Arrow format"   ,      ):
																	UpperCAmelCase		:							Any        =       self._batch_csv((offset, header, index, to_csv_kwargs)      )
																	written += file_obj.write(snake_case      )

							else:
												UpperCAmelCase ,			UpperCAmelCase		:							Union[str, Any]        =       len(self.dataset      ), self.batch_size
												with multiprocessing.Pool(self.num_proc      ) as pool:
																	for csv_str in logging.tqdm(
																	    pool.imap(
																	        self._batch_csv   ,      [(offset, header, index, to_csv_kwargs) for offset in range(0   ,      snake_case   ,      snake_case      )]   ,      )   ,      total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size   ,      unit="ba"   ,      disable=not logging.is_progress_bar_enabled()   ,      desc="Creating CSV from Arrow format"   ,      ):
																						written += file_obj.write(snake_case      )

							return written
