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		:







							def __init__(				self     :    Optional[int]	,					__snake_case     :    Tuple	,					__snake_case     :    Optional[Any]=3	,					__snake_case     :    int=32	,					__snake_case     :    List[Any]=3	,					__snake_case     :    int=10	,					__snake_case     :    Any=[10, 20, 30, 40]	,					__snake_case     :    Dict=[1, 1, 2, 1]	,					__snake_case     :    Union[str, Any]=True	,					__snake_case     :    Dict=True	,					__snake_case     :    Union[str, Any]="relu"	,					__snake_case     :    Any=3	,					__snake_case     :    Dict=None	,					):
										lowerCamelCase						:Tuple						  =     parent
										lowerCamelCase						:int						  =     batch_size
										lowerCamelCase						:Union[str, Any]						  =     image_size
										lowerCamelCase						:Union[str, Any]						  =     num_channels
										lowerCamelCase						:List[str]						  =     embeddings_size
										lowerCamelCase						:int						  =     hidden_sizes
										lowerCamelCase						:Optional[int]						  =     depths
										lowerCamelCase						:List[Any]						  =     is_training
										lowerCamelCase						:Dict						  =     use_labels
										lowerCamelCase						:Optional[int]						  =     hidden_act
										lowerCamelCase						:Optional[int]						  =     num_labels
										lowerCamelCase						:Dict						  =     scope
										lowerCamelCase						:str						  =     len(__snake_case		)







							def 				snake_case  (				self     :    Dict		):
										lowerCamelCase						:Union[str, Any]						  =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

										lowerCamelCase						:Optional[Any]						  =     None
										if self.use_labels:
													lowerCamelCase						:Optional[int]						  =     ids_tensor([self.batch_size]	,					self.num_labels		)

										lowerCamelCase						:Tuple						  =     self.get_config()

										return config, pixel_values, labels







							def 				snake_case  (				self     :    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 				snake_case  (				self     :    Tuple	,					__snake_case     :    Any	,					__snake_case     :    Optional[Any]	,					__snake_case     :    Dict		):
										lowerCamelCase						:int						  =     TFResNetModel(config=__snake_case		)
										lowerCamelCase						:str						  =     model(__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 // 32, self.image_size // 32)	,					)







							def 				snake_case  (				self     :    Union[str, Any]	,					__snake_case     :    Optional[int]	,					__snake_case     :    Union[str, Any]	,					__snake_case     :    Union[str, Any]		):
										lowerCamelCase						:Any						  =     self.num_labels
										lowerCamelCase						:Dict						  =     TFResNetForImageClassification(__snake_case		)
										lowerCamelCase						:List[str]						  =     model(__snake_case	,					labels=__snake_case		)
										self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels)		)







							def 				snake_case  (				self     :    List[Any]		):
										lowerCamelCase						:Optional[Any]						  =     self.prepare_config_and_inputs()
										lowerCamelCase  ,    lowerCamelCase  ,    lowerCamelCase						:Optional[Any]						  =     config_and_inputs
										lowerCamelCase						:Tuple						  =     {'''pixel_values''': pixel_values}
										return config, inputs_dict


@require_tf
class   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
							_UpperCAmelCase						    =     (
							    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False
							_UpperCAmelCase						    =     False







							def 				snake_case  (				self     :    List[str]		):
										lowerCamelCase						:Union[str, Any]						  =     TFResNetModelTester(self		)
										lowerCamelCase						:str						  =     ConfigTester(self	,					config_class=__snake_case	,					has_text_modality=__snake_case		)







							def 				snake_case  (				self     :    List[str]		):
										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 				snake_case  (				self     :    Union[str, Any]		):
										return







							@unittest.skip(reason='''ResNet does not use inputs_embeds'''		)
							def 				snake_case  (				self     :    Optional[int]		):
										pass







							@unittest.skip(reason='''ResNet does not support input and output embeddings'''		)
							def 				snake_case  (				self     :    List[str]		):
										pass







							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase  ,    lowerCamelCase						:Union[str, Any]						  =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													lowerCamelCase						:Any						  =     model_class(__snake_case		)
													lowerCamelCase						:Dict						  =     inspect.signature(model.call		)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													lowerCamelCase						:Optional[Any]						  =     [*signature.parameters.keys()]

													lowerCamelCase						:Optional[int]						  =     ['''pixel_values''']
													self.assertListEqual(arg_names[:1]	,					__snake_case		)







							def 				snake_case  (				self     :    List[str]		):
										lowerCamelCase						:int						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__snake_case		)







							def 				snake_case  (				self     :    List[str]		):
										def check_hidden_states_output(__snake_case     :    List[str]	,					__snake_case     :    Any	,					__snake_case     :    List[str]		):
													lowerCamelCase						:Optional[Any]						  =     model_class(__snake_case		)
													lowerCamelCase						:List[str]						  =     model(**self._prepare_for_class(__snake_case	,					__snake_case		)		)

													lowerCamelCase						:List[Any]						  =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													lowerCamelCase						:List[Any]						  =     self.model_tester.num_stages
													self.assertEqual(len(__snake_case		)	,					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]	,					)

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

																check_hidden_states_output(__snake_case	,					__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:Any						  =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__snake_case		)







							@slow
							def 				snake_case  (				self     :    List[str]		):
										for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowerCamelCase						:Tuple						  =     TFResNetModel.from_pretrained(__snake_case		)
													self.assertIsNotNone(__snake_case		)





def  _lowerCamelCase					(   ):
			lowerCamelCase						:List[str]						  =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
			return image


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







							@cached_property
							def 				snake_case  (				self     :    List[str]		):
										return (
										    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
										    if is_vision_available()
										    else None
										)







							@slow
							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:Optional[int]						  =     TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

										lowerCamelCase						:Optional[Any]						  =     self.default_image_processor
										lowerCamelCase						:Optional[Any]						  =     prepare_img()
										lowerCamelCase						:Optional[int]						  =     image_processor(images=__snake_case	,					return_tensors='''tf'''		)

										# forward pass
										lowerCamelCase						:Optional[Any]						  =     model(**__snake_case		)

										# verify the logits
										lowerCamelCase						:str						  =     tf.TensorShape((1, 1000)		)
										self.assertEqual(outputs.logits.shape	,					__snake_case		)

										lowerCamelCase						:List[str]						  =     tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]		)

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




import unittest
from queue import Empty
from threading import Thread

from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available
from transformers.testing_utils import CaptureStdout, require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
			import torch

			from transformers import AutoModelForCausalLM
@require_torch
class   _lowerCAmelCase		(     unittest.TestCase				):







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:int						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:List[Any]						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[Any]						  =     -1

										lowerCamelCase						:List[str]						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Tuple						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:str						  =     tokenizer.decode(greedy_ids[0]		)

										with CaptureStdout() as cs:
													lowerCamelCase						:str						  =     TextStreamer(__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case	,					streamer=__snake_case		)
										# The greedy text should be printed to stdout, except for the final "\n" in the streamer
										lowerCamelCase						:Optional[int]						  =     cs.out[:-1]

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    Dict		):
										lowerCamelCase						:Tuple						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:int						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:List[Any]						  =     -1

										lowerCamelCase						:Dict						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Tuple						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:List[Any]						  =     tokenizer.decode(greedy_ids[0]		)

										lowerCamelCase						:List[str]						  =     TextIteratorStreamer(__snake_case		)
										lowerCamelCase						:List[str]						  =     {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
										lowerCamelCase						:Tuple						  =     Thread(target=model.generate	,					kwargs=__snake_case		)
										thread.start()
										lowerCamelCase						:Any						  =     ''''''
										for new_text in streamer:
													streamer_text += new_text

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:int						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:Dict						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:List[str]						  =     -1

										lowerCamelCase						:Optional[Any]						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:Optional[Any]						  =     model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case		)
										lowerCamelCase						:List[str]						  =     greedy_ids[:, input_ids.shape[1] :]
										lowerCamelCase						:Union[str, Any]						  =     tokenizer.decode(new_greedy_ids[0]		)

										with CaptureStdout() as cs:
													lowerCamelCase						:List[str]						  =     TextStreamer(__snake_case	,					skip_prompt=__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=10	,					do_sample=__snake_case	,					streamer=__snake_case		)
										# The greedy text should be printed to stdout, except for the final "\n" in the streamer
										lowerCamelCase						:int						  =     cs.out[:-1]

										self.assertEqual(__snake_case	,					__snake_case		)







							def 				snake_case  (				self     :    Optional[int]		):
										# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested
										# with actual models -- the dummy models' tokenizers are not aligned with their models, and
										# `skip_special_tokens=True` has no effect on them
										lowerCamelCase						:List[Any]						  =     AutoTokenizer.from_pretrained('''distilgpt2'''		)
										lowerCamelCase						:Union[str, Any]						  =     AutoModelForCausalLM.from_pretrained('''distilgpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[int]						  =     -1

										lowerCamelCase						:Union[str, Any]						  =     torch.ones((1, 5)	,					device=__snake_case		).long() * model.config.bos_token_id
										with CaptureStdout() as cs:
													lowerCamelCase						:Dict						  =     TextStreamer(__snake_case	,					skip_special_tokens=__snake_case		)
													model.generate(__snake_case	,					max_new_tokens=1	,					do_sample=__snake_case	,					streamer=__snake_case		)

										# The prompt contains a special token, so the streamer should not print it. As such, the output text, when
										# re-tokenized, must only contain one token
										lowerCamelCase						:Tuple						  =     cs.out[:-1]  # Remove the final "\n"
										lowerCamelCase						:int						  =     tokenizer(__snake_case	,					return_tensors='''pt'''		)
										self.assertEqual(streamer_text_tokenized.input_ids.shape	,					(1, 1)		)







							def 				snake_case  (				self     :    List[Any]		):
										lowerCamelCase						:List[str]						  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		)
										lowerCamelCase						:Optional[int]						  =     AutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''		).to(__snake_case		)
										lowerCamelCase						:Optional[int]						  =     -1

										lowerCamelCase						:Tuple						  =     ids_tensor((1, 5)	,					vocab_size=model.config.vocab_size		).to(__snake_case		)
										lowerCamelCase						:List[Any]						  =     TextIteratorStreamer(__snake_case	,					timeout=0.0_0_1		)
										lowerCamelCase						:Dict						  =     {'''input_ids''': input_ids, '''max_new_tokens''': 10, '''do_sample''': False, '''streamer''': streamer}
										lowerCamelCase						:Tuple						  =     Thread(target=model.generate	,					kwargs=__snake_case		)
										thread.start()

										# The streamer will timeout after 0.001 seconds, so an exception will be raised
										with self.assertRaises(__snake_case		):
													lowerCamelCase						:Dict						  =     ''''''
													for new_text in streamer:
																streamer_text += new_text



