
"""simple docstring"""





import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
				import jax
				import jax.numpy as jnp

				from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor






class     _UpperCAmelCase(    unittest.TestCase	):



		def __init__(					self				,		__a				,		__a=3				,		__a=32				,		__a=3				,		__a=10				,		__a=[10, 20, 30, 40]				,		__a=[1, 1, 2, 1]				,		__a=True				,		__a=True				,		__a="relu"				,		__a=3				,		__a=None				,		)       ->       Dict:






							'''simple docstring'''
							_UpperCamelCase							 =  parent
							_UpperCamelCase							 =  batch_size
							_UpperCamelCase							 =  image_size
							_UpperCamelCase							 =  num_channels
							_UpperCamelCase							 =  embeddings_size
							_UpperCamelCase							 =  hidden_sizes
							_UpperCamelCase							 =  depths
							_UpperCamelCase							 =  is_training
							_UpperCamelCase							 =  use_labels
							_UpperCamelCase							 =  hidden_act
							_UpperCamelCase							 =  num_labels
							_UpperCamelCase							 =  scope
							_UpperCamelCase							 =  len(__a)



		def 						UpperCAmelCase							(					self)       ->       Optional[int]:






							'''simple docstring'''
							_UpperCamelCase							 =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

							_UpperCamelCase							 =  self.get_config()

							return config, pixel_values



		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''simple docstring'''
							return RegNetConfig(
							    num_channels=self.num_channels				,		embeddings_size=self.embeddings_size				,		hidden_sizes=self.hidden_sizes				,		depths=self.depths				,		hidden_act=self.hidden_act				,		num_labels=self.num_labels				,		image_size=self.image_size				,		)



		def 						UpperCAmelCase							(					self				,		__a				,		__a)       ->       Dict:






							'''simple docstring'''
							_UpperCamelCase							 =  FlaxRegNetModel(config=__a)
							_UpperCamelCase							 =  model(__a)

							# Output shape (b, c, h, w)
							self.parent.assertEqual(
							    result.last_hidden_state.shape				,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,		)



		def 						UpperCAmelCase							(					self				,		__a				,		__a)       ->       Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase							 =  self.num_labels
							_UpperCamelCase							 =  FlaxRegNetForImageClassification(config=__a)
							_UpperCamelCase							 =  model(__a)
							self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.num_labels))




		def 						UpperCAmelCase							(					self)       ->       Dict:






							'''simple docstring'''
							_UpperCamelCase							 =  self.prepare_config_and_inputs()
							_UpperCamelCase ,  _UpperCamelCase							 =  config_and_inputs
							_UpperCamelCase							 =  {'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_flax
class     _UpperCAmelCase(    lowerCamelCase      ,     unittest.TestCase	):
		lowercase__						=      (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

		lowercase__						=      False
		lowercase__						=      False
		lowercase__						=      False



		def 						UpperCAmelCase							(					self)       ->       None:






							'''simple docstring'''
							_UpperCamelCase							 =  FlaxRegNetModelTester(self)
							_UpperCamelCase							 =  ConfigTester(self				,		config_class=__a				,		has_text_modality=__a)



		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							self.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()



		def 						UpperCAmelCase							(					self)       ->       int:






							'''simple docstring'''
							return



		def 						UpperCAmelCase							(					self)       ->       str:






							'''simple docstring'''
							_UpperCamelCase							 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__a)



		def 						UpperCAmelCase							(					self)       ->       Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase							 =  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__a)



		@unittest.skip(reason='''RegNet does not use inputs_embeds''')
		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''RegNet does not support input and output embeddings''')
		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							pass



		def 						UpperCAmelCase							(					self)       ->       Dict:






							'''simple docstring'''
							_UpperCamelCase ,  _UpperCamelCase							 =  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_UpperCamelCase							 =  model_class(__a)
												_UpperCamelCase							 =  inspect.signature(model.__call__)
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												_UpperCamelCase							 =  [*signature.parameters.keys()]

												_UpperCamelCase							 =  ['''pixel_values''']
												self.assertListEqual(arg_names[:1]				,		__a)



		def 						UpperCAmelCase							(					self)       ->       Union[str, Any]:






							'''simple docstring'''
							def check_hidden_states_output(__a				,		__a				,		__a):
												_UpperCamelCase							 =  model_class(__a)

												_UpperCamelCase							 =  model(**self._prepare_for_class(__a				,		__a))

												_UpperCamelCase							 =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												_UpperCamelCase							 =  self.model_tester.num_stages
												self.assertEqual(len(__a)				,		expected_num_stages + 1)

							_UpperCamelCase ,  _UpperCamelCase							 =  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_UpperCamelCase							 =  True
												check_hidden_states_output(__a				,		__a				,		__a)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												_UpperCamelCase							 =  True

												check_hidden_states_output(__a				,		__a				,		__a)




		def 						UpperCAmelCase							(					self)       ->       Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase ,  _UpperCamelCase							 =  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												with self.subTest(model_class.__name__):
																	_UpperCamelCase							 =  self._prepare_for_class(__a				,		__a)
																	_UpperCamelCase							 =  model_class(__a)

																	@jax.jit
																	def model_jitted(__a				,		**__a):
																						return model(pixel_values=__a				,		**__a)

																	with self.subTest('''JIT Enabled'''):
																						_UpperCamelCase							 =  model_jitted(**__a).to_tuple()

																	with self.subTest('''JIT Disabled'''):
																						with jax.disable_jit():
																											_UpperCamelCase							 =  model_jitted(**__a).to_tuple()

																	self.assertEqual(len(__a)				,		len(__a))
																	for jitted_output, output in zip(__a				,		__a):
																						self.assertEqual(jitted_output.shape				,		output.shape)





def       lowerCamelCase__		(			)							->		int:


					"""simple docstring"""





					_UpperCamelCase							 =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
					return image






@require_flax
class     _UpperCAmelCase(    unittest.TestCase	):



		@cached_property
		def 						UpperCAmelCase							(					self)       ->       Optional[int]:






							'''simple docstring'''
							return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''') if is_vision_available() else None




		@slow
		def 						UpperCAmelCase							(					self)       ->       List[str]:






							'''simple docstring'''
							_UpperCamelCase							 =  FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''')

							_UpperCamelCase							 =  self.default_image_processor
							_UpperCamelCase							 =  prepare_img()
							_UpperCamelCase							 =  image_processor(images=__a				,		return_tensors='''np''')

							_UpperCamelCase							 =  model(**__a)

							# verify the logits
							_UpperCamelCase							 =  (1, 10_00)
							self.assertEqual(outputs.logits.shape				,		__a)

							_UpperCamelCase							 =  jnp.array([-0.4180, -1.5051, -3.4836])

							self.assertTrue(jnp.allclose(outputs.logits[0, :3]				,		__a				,		atol=1e-4))








"""simple docstring"""





import json
import os
from pathlib import Path

import pytest

from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename


_a														=		"""http://www.mocksite.com/file1.txt"""
_a														=		"""\"text\": [\"foo\", \"foo\"]"""
_a														=		"""6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8"""






class     _UpperCAmelCase:
		lowercase__						=      2_00
		lowercase__						=      {'Content-Length': '100'}
		lowercase__						=      {}



		def 						UpperCAmelCase							(					self				,		**__a)       ->       Optional[int]:






							'''simple docstring'''
							return [bytes(__a				,		'''utf-8''')]





def       lowerCamelCase__		(			*__snake_case,     **__snake_case	)							->		int:


					"""simple docstring"""





					return MockResponse()



@pytest.mark.parametrize('''urls_type''',     [str, list, dict]	)
def       lowerCamelCase__		(			__snake_case,     __snake_case,     __snake_case	)							->		Dict:


					"""simple docstring"""





					import requests

					monkeypatch.setattr(__snake_case,     '''request''',     __snake_case	)

					_UpperCamelCase							 =  URL
					if issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  url
					elif issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  [url]
					elif issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  {'''train''': url}
					_UpperCamelCase							 =  '''dummy'''
					_UpperCamelCase							 =  '''downloads'''
					_UpperCamelCase							 =  tmp_path
					_UpperCamelCase							 =  DownloadConfig(
					    cache_dir=os.path.join(__snake_case,     __snake_case	),     use_etag=__snake_case,     )
					_UpperCamelCase							 =  DownloadManager(dataset_name=__snake_case,     download_config=__snake_case	)
					_UpperCamelCase							 =  dl_manager.download(__snake_case	)
					_UpperCamelCase							 =  urls
					for downloaded_paths in [downloaded_paths]:
										if isinstance(__snake_case,     __snake_case	):
															_UpperCamelCase							 =  [downloaded_paths]
															_UpperCamelCase							 =  [urls]
										elif isinstance(__snake_case,     __snake_case	):
															assert "train" in downloaded_paths.keys()
															_UpperCamelCase							 =  downloaded_paths.values()
															_UpperCamelCase							 =  urls.values()
										assert downloaded_paths
										for downloaded_path, input_url in zip(__snake_case,     __snake_case	):
															assert downloaded_path == dl_manager.downloaded_paths[input_url]
															_UpperCamelCase							 =  Path(__snake_case	)
															_UpperCamelCase							 =  downloaded_path.parts
															assert parts[-1] == HASH
															assert parts[-2] == cache_subdir
															assert downloaded_path.exists()
															_UpperCamelCase							 =  downloaded_path.read_text()
															assert content == CONTENT
															_UpperCamelCase							 =  downloaded_path.with_suffix('''.json'''	)
															assert metadata_downloaded_path.exists()
															_UpperCamelCase							 =  json.loads(metadata_downloaded_path.read_text()	)
															assert metadata_content == {"url": URL, "etag": None}



@pytest.mark.parametrize('''paths_type''',     [str, list, dict]	)
def       lowerCamelCase__		(			__snake_case,     __snake_case,     __snake_case	)							->		List[str]:


					"""simple docstring"""





					_UpperCamelCase							 =  str(__snake_case	)
					if issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  filename
					elif issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  [filename]
					elif issubclass(__snake_case,     __snake_case	):
										_UpperCamelCase							 =  {'''train''': filename}
					_UpperCamelCase							 =  '''dummy'''
					_UpperCamelCase							 =  xz_file.parent
					_UpperCamelCase							 =  '''extracted'''
					_UpperCamelCase							 =  DownloadConfig(
					    cache_dir=__snake_case,     use_etag=__snake_case,     )
					_UpperCamelCase							 =  DownloadManager(dataset_name=__snake_case,     download_config=__snake_case	)
					_UpperCamelCase							 =  dl_manager.extract(__snake_case	)
					_UpperCamelCase							 =  paths
					for extracted_paths in [extracted_paths]:
										if isinstance(__snake_case,     __snake_case	):
															_UpperCamelCase							 =  [extracted_paths]
															_UpperCamelCase							 =  [paths]
										elif isinstance(__snake_case,     __snake_case	):
															assert "train" in extracted_paths.keys()
															_UpperCamelCase							 =  extracted_paths.values()
															_UpperCamelCase							 =  paths.values()
										assert extracted_paths
										for extracted_path, input_path in zip(__snake_case,     __snake_case	):
															assert extracted_path == dl_manager.extracted_paths[input_path]
															_UpperCamelCase							 =  Path(__snake_case	)
															_UpperCamelCase							 =  extracted_path.parts
															assert parts[-1] == hash_url_to_filename(__snake_case,     etag=__snake_case	)
															assert parts[-2] == extracted_subdir
															assert extracted_path.exists()
															_UpperCamelCase							 =  extracted_path.read_text()
															_UpperCamelCase							 =  text_file.read_text()
															assert extracted_file_content == expected_file_content



def       lowerCamelCase__		(			__snake_case,     __snake_case	)							->		Optional[Any]:


					"""simple docstring"""





					assert path.endswith('''.jsonl'''	)
					for num_items, line in enumerate(__snake_case,     start=1	):
										_UpperCamelCase							 =  json.loads(line.decode('''utf-8'''	)	)
										assert item.keys() == {"col_1", "col_2", "col_3"}
					assert num_items == 4



@pytest.mark.parametrize('''archive_jsonl''',     ['''tar_jsonl_path''', '''zip_jsonl_path''']	)
def       lowerCamelCase__		(			__snake_case,     __snake_case	)							->		int:


					"""simple docstring"""





					_UpperCamelCase							 =  request.getfixturevalue(__snake_case	)
					_UpperCamelCase							 =  DownloadManager()
					for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(__snake_case	),     start=1	):
										_test_jsonl(__snake_case,     __snake_case	)
					assert num_jsonl == 2



@pytest.mark.parametrize('''archive_nested_jsonl''',     ['''tar_nested_jsonl_path''', '''zip_nested_jsonl_path''']	)
def       lowerCamelCase__		(			__snake_case,     __snake_case	)							->		int:


					"""simple docstring"""





					_UpperCamelCase							 =  request.getfixturevalue(__snake_case	)
					_UpperCamelCase							 =  DownloadManager()
					for num_tar, (path, file) in enumerate(dl_manager.iter_archive(__snake_case	),     start=1	):
										for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(__snake_case	),     start=1	):
															_test_jsonl(__snake_case,     __snake_case	)
					assert num_tar == 1
					assert num_jsonl == 2



def       lowerCamelCase__		(			__snake_case	)							->		Dict:


					"""simple docstring"""





					_UpperCamelCase							 =  DownloadManager()
					for num_file, file in enumerate(dl_manager.iter_files(__snake_case	),     start=1	):
										assert os.path.basename(__snake_case	) == ("test.txt" if num_file == 1 else "train.txt")
					assert num_file == 2






