
import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase  :					Optional[Any]													=       random.Random()

if is_torch_available():
		import torch




def 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			Optional[Any]						,  _lowerCamelCase :			Union[str, Any]=1.0						,  _lowerCamelCase :			Any=None						,  _lowerCamelCase :			Any=None)					->    Optional[int]:






							'''simple docstring'''





							if rng is None:
														__UpperCamelCase	:   Tuple			   =					global_rng

							__UpperCamelCase	:   Any			   =					[]
							for batch_idx in range(shape[0]):
														values.append([])
														for _ in range(shape[1]):
																					values[-1].append(rng.random() * scale)

							return values




class  lowerCamelCase__							(				unittest.TestCase):




	'''simple docstring'''




	def __init__(					self		:Union[str, Any]     ,   a		:Dict     ,   a		:int=7     ,   a		:Tuple=4_0_0     ,   a		:Optional[int]=2_0_0_0     ,   a		:Optional[Any]=1     ,   a		:Optional[Any]=0.0     ,   a		:Dict=1_6_0_0_0     ,   a		:List[Any]=True     ,   a		:List[str]=True     ,   )		-> Optional[int]:
								__UpperCamelCase	:   str			   =					parent
								__UpperCamelCase	:   Optional[Any]			   =					batch_size
								__UpperCamelCase	:   Optional[int]			   =					min_seq_length
								__UpperCamelCase	:   List[str]			   =					max_seq_length
								__UpperCamelCase	:   Optional[Any]			   =					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								__UpperCamelCase	:   List[Any]			   =					feature_size
								__UpperCamelCase	:   Tuple			   =					padding_value
								__UpperCamelCase	:   List[str]			   =					sampling_rate
								__UpperCamelCase	:   Dict			   =					return_attention_mask
								__UpperCamelCase	:   List[str]			   =					do_normalize







	def    _lowerCamelCase				(					self		:Dict						)		-> Dict:
								return {
								    "feature_size": self.feature_size,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}







	def    _lowerCamelCase				(					self		:int     ,   a		:Optional[Any]=False     ,   a		:str=False						)		-> Tuple:
								def _flatten(a		:Dict						):
															return list(itertools.chain(*a						)						)

								if equal_length:
															__UpperCamelCase	:   Optional[int]			   =					floats_list((self.batch_size, self.max_seq_length)						)
								else:
															# make sure that inputs increase in size
															__UpperCamelCase	:   List[str]			   =					[
															    _flatten(floats_list((x, self.feature_size)						)						)
															    for x in range(self.min_seq_length     ,   self.max_seq_length     ,   self.seq_length_diff						)
															]

								if numpify:
															__UpperCamelCase	:   Any			   =					[np.asarray(a						) for x in speech_inputs]

								return speech_inputs




@require_torch
@require_torchaudio
class  lowerCamelCase__							(				__lowercase     ,						unittest.TestCase):




	'''simple docstring'''




	_A								=     ASTFeatureExtractor







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> Any:
								__UpperCamelCase	:   str			   =					ASTFeatureExtractionTester(self						)







	def    _lowerCamelCase				(					self		:Any						)		-> Union[str, Any]:
								# Tests that all call wrap to encode_plus and batch_encode_plus
								__UpperCamelCase	:   int			   =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
								# create three inputs of length 800, 1000, and 1200
								__UpperCamelCase	:   Dict			   =					[floats_list((1, x)						)[0] for x in range(8_0_0     ,   1_4_0_0     ,   2_0_0						)]
								__UpperCamelCase	:   Optional[int]			   =					[np.asarray(a						) for speech_input in speech_inputs]

								# Test not batched input
								__UpperCamelCase	:   Tuple			   =					feat_extract(speech_inputs[0]     ,   return_tensors="np"						).input_values
								__UpperCamelCase	:   int			   =					feat_extract(np_speech_inputs[0]     ,   return_tensors="np"						).input_values
								self.assertTrue(np.allclose(a     ,   a     ,   atol=1E-3						)						)

								# Test batched
								__UpperCamelCase	:   List[str]			   =					feat_extract(a     ,   padding=a     ,   return_tensors="np"						).input_values
								__UpperCamelCase	:   Optional[Any]			   =					feat_extract(a     ,   padding=a     ,   return_tensors="np"						).input_values
								for enc_seq_a, enc_seq_a in zip(a     ,   a						):
															self.assertTrue(np.allclose(a     ,   a     ,   atol=1E-3						)						)

								# Test 2-D numpy arrays are batched.
								__UpperCamelCase	:   Optional[Any]			   =					[floats_list((1, x)						)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
								__UpperCamelCase	:   int			   =					np.asarray(a						)
								__UpperCamelCase	:   Union[str, Any]			   =					feat_extract(a     ,   return_tensors="np"						).input_values
								__UpperCamelCase	:   Any			   =					feat_extract(a     ,   return_tensors="np"						).input_values
								for enc_seq_a, enc_seq_a in zip(a     ,   a						):
															self.assertTrue(np.allclose(a     ,   a     ,   atol=1E-3						)						)







	@require_torch
	def    _lowerCamelCase				(					self		:Optional[int]						)		-> List[str]:
								import torch

								__UpperCamelCase	:   Tuple			   =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
								__UpperCamelCase	:   Any			   =					np.random.rand(1_0_0						).astype(np.floataa						)
								__UpperCamelCase	:   List[Any]			   =					np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
															__UpperCamelCase	:   List[str]			   =					feature_extractor.pad([{"input_values": inputs}]     ,   return_tensors="np"						)
															self.assertTrue(np_processed.input_values.dtype == np.floataa						)
															__UpperCamelCase	:   List[str]			   =					feature_extractor.pad([{"input_values": inputs}]     ,   return_tensors="pt"						)
															self.assertTrue(pt_processed.input_values.dtype == torch.floataa						)







	def    _lowerCamelCase				(					self		:int     ,   a		:Optional[int]						)		-> Any:
								from datasets import load_dataset

								__UpperCamelCase	:   Union[str, Any]			   =					load_dataset("hf-internal-testing/librispeech_asr_dummy"     ,   "clean"     ,   split="validation"						)
								# automatic decoding with librispeech
								__UpperCamelCase	:   str			   =					ds.sort("id"						).select(range(a						)						)[:num_samples]["audio"]

								return [x["array"] for x in speech_samples]







	@require_torch
	def    _lowerCamelCase				(					self		:Dict						)		-> Dict:
								# fmt: off
								__UpperCamelCase	:   Dict			   =					torch.tensor(
								    [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
								     -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
								     -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
								     -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]						)
								# fmt: on

								__UpperCamelCase	:   Optional[int]			   =					self._load_datasamples(1						)
								__UpperCamelCase	:   int			   =					ASTFeatureExtractor()
								__UpperCamelCase	:   Optional[Any]			   =					feature_extractor(a     ,   return_tensors="pt"						).input_values
								self.assertEquals(input_values.shape     ,   (1, 1_0_2_4, 1_2_8)						)
								self.assertTrue(torch.allclose(input_values[0, 0, :3_0]     ,   a     ,   atol=1E-4						)						)

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
		from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class  lowerCamelCase__							:




	'''simple docstring'''




	def __init__(					self		:List[Any]     ,   a		:Dict     ,   a		:Any=3     ,   a		:Any=3_2     ,   a		:Optional[Any]=3     ,   a		:str=1_0     ,   a		:Union[str, Any]=[1_0, 2_0, 3_0, 4_0]     ,   a		:Optional[Any]=[1, 1, 2, 1]     ,   a		:Optional[Any]=True     ,   a		:Dict=True     ,   a		:Tuple="relu"     ,   a		:List[str]=3     ,   a		:Tuple=None     ,   )		-> Tuple:
								__UpperCamelCase	:   Optional[Any]			   =					parent
								__UpperCamelCase	:   Dict			   =					batch_size
								__UpperCamelCase	:   int			   =					image_size
								__UpperCamelCase	:   Dict			   =					num_channels
								__UpperCamelCase	:   Optional[int]			   =					embeddings_size
								__UpperCamelCase	:   List[Any]			   =					hidden_sizes
								__UpperCamelCase	:   Optional[Any]			   =					depths
								__UpperCamelCase	:   Optional[int]			   =					is_training
								__UpperCamelCase	:   Union[str, Any]			   =					use_labels
								__UpperCamelCase	:   Optional[int]			   =					hidden_act
								__UpperCamelCase	:   Tuple			   =					num_labels
								__UpperCamelCase	:   Tuple			   =					scope
								__UpperCamelCase	:   Dict			   =					len(a						)







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Any:
								__UpperCamelCase	:   List[str]			   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

								__UpperCamelCase	:   List[str]			   =					None
								if self.use_labels:
															__UpperCamelCase	:   Tuple			   =					ids_tensor([self.batch_size]     ,   self.num_labels						)

								__UpperCamelCase	:   List[Any]			   =					self.get_config()

								return config, pixel_values, labels







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> int:
								return ResNetConfig(
								    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    _lowerCamelCase				(					self		:List[Any]     ,   a		:Dict     ,   a		:int     ,   a		:Optional[Any]						)		-> Tuple:
								__UpperCamelCase	:   str			   =					TFResNetModel(config=a						)
								__UpperCamelCase	:   Union[str, Any]			   =					model(a						)
								# 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    _lowerCamelCase				(					self		:Union[str, Any]     ,   a		:Optional[int]     ,   a		:List[str]     ,   a		:Optional[Any]						)		-> Any:
								__UpperCamelCase	:   str			   =					self.num_labels
								__UpperCamelCase	:   Optional[int]			   =					TFResNetForImageClassification(a						)
								__UpperCamelCase	:   List[str]			   =					model(a     ,   labels=a						)
								self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)						)







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> List[str]:
								__UpperCamelCase	:   Optional[int]			   =					self.prepare_config_and_inputs()
								__UpperCamelCase   ,						__UpperCamelCase   ,						__UpperCamelCase	:   Union[str, Any]			   =					config_and_inputs
								__UpperCamelCase	:   List[str]			   =					{"pixel_values": pixel_values}
								return config, inputs_dict




@require_tf
class  lowerCamelCase__							(				__lowercase     ,						__lowercase     ,						unittest.TestCase):




	'''simple docstring'''




	_A								=     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	_A								=     (
	    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False
	_A								=     False







	def    _lowerCamelCase				(					self		:int						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					TFResNetModelTester(self						)
								__UpperCamelCase	:   List[Any]			   =					ConfigTester(self     ,   config_class=a     ,   has_text_modality=a						)







	def    _lowerCamelCase				(					self		:int						)		-> Dict:
								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    _lowerCamelCase				(					self		:str						)		-> Optional[Any]:
								return







	@unittest.skip(reason="ResNet does not use inputs_embeds"						)
	def    _lowerCamelCase				(					self		:Tuple						)		-> Tuple:
								pass







	@unittest.skip(reason="ResNet does not support input and output embeddings"						)
	def    _lowerCamelCase				(					self		:List[Any]						)		-> List[str]:
								pass







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Tuple:
								__UpperCamelCase   ,						__UpperCamelCase	:   Union[str, Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()

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

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







	def    _lowerCamelCase				(					self		:List[str]						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a						)







	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> Tuple:
								def check_hidden_states_output(a		:Optional[Any]     ,   a		:Optional[int]     ,   a		:List[str]						):
															__UpperCamelCase	:   int			   =					model_class(a						)
															__UpperCamelCase	:   int			   =					model(**self._prepare_for_class(a     ,   a						)						)

															__UpperCamelCase	:   Optional[Any]			   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															__UpperCamelCase	:   Optional[int]			   =					self.model_tester.num_stages
															self.assertEqual(len(a						)     ,   expected_num_stages + 1						)

															# ResNet'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   ,						__UpperCamelCase	:   Optional[Any]			   =					self.model_tester.prepare_config_and_inputs_for_common()
								__UpperCamelCase	:   str			   =					["basic", "bottleneck"]
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						__UpperCamelCase	:   int			   =					layer_type
																						__UpperCamelCase	:   int			   =					True
																						check_hidden_states_output(a     ,   a     ,   a						)

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

																						check_hidden_states_output(a     ,   a     ,   a						)







	def    _lowerCamelCase				(					self		:Union[str, Any]						)		-> Dict:
								__UpperCamelCase	:   int			   =					self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a						)







	@slow
	def    _lowerCamelCase				(					self		:Dict						)		-> Dict:
								for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__UpperCamelCase	:   Optional[Any]			   =					TFResNetModel.from_pretrained(a						)
															self.assertIsNotNone(a						)




def 	_SCREAMING_SNAKE_CASE					(		)					->    int:






							'''simple docstring'''





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




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




	'''simple docstring'''




	@cached_property
	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> Tuple:
								return (
								    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
								    if is_vision_available()
								    else None
								)







	@slow
	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Optional[int]:
								__UpperCamelCase	:   int			   =					TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

								__UpperCamelCase	:   List[Any]			   =					self.default_image_processor
								__UpperCamelCase	:   List[str]			   =					prepare_img()
								__UpperCamelCase	:   List[str]			   =					image_processor(images=a     ,   return_tensors="tf"						)

								# forward pass
								__UpperCamelCase	:   Dict			   =					model(**a						)

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

								__UpperCamelCase	:   Union[str, Any]			   =					tf.constant([-11.1069, -9.7877, -8.3777]						)

								self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()     ,   a     ,   atol=1E-4						)						)