





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor







class   _UpperCamelCase  :







					'''simple docstring'''

					def __init__(						self    :  Dict ,					__lowercase    :  Dict ,					__lowercase    :  str=3 ,					__lowercase    :  str=32 ,					__lowercase    :  List[str]=3 ,					__lowercase    :  Tuple=10 ,					__lowercase    :  str=[10, 20, 30, 40] ,					__lowercase    :  Optional[Any]=[1, 1, 2, 1] ,					__lowercase    :  Optional[Any]=True ,					__lowercase    :  List[Any]=True ,					__lowercase    :  str="relu" ,					__lowercase    :  int=3 ,					__lowercase    :  int=None ,					):






						'''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(__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

						UpperCAmelCase_								=     None
						if self.use_labels:
							UpperCAmelCase_								=     ids_tensor([self.batch_size] ,					self.num_labels		)

						UpperCAmelCase_								=     self.get_config()
						return config, pixel_values, labels





					def        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''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 ,					)





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple ,					__lowercase    :  Tuple ,					__lowercase    :  Tuple ,					__lowercase    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     TFRegNetModel(config=__lowercase		)
						UpperCAmelCase_								=     model(__lowercase ,					training=__lowercase		)
						# 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        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any] ,					__lowercase    :  Optional[int] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.num_labels
						UpperCAmelCase_								=     TFRegNetForImageClassification(__lowercase		)
						UpperCAmelCase_								=     model(__lowercase ,					labels=__lowercase ,					training=__lowercase		)
						self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.prepare_config_and_inputs()
						UpperCAmelCase_						,	UpperCAmelCase_						,	UpperCAmelCase_								=     config_and_inputs
						UpperCAmelCase_								=     {"""pixel_values""": pixel_values}
						return config, inputs_dict







@require_tf
class   _UpperCamelCase  (       A_						,       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     List[str]			    =       (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
					lowerCamelCase     :     str			    =       (
					    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
					    if is_tf_available()
					    else {}
					)

					lowerCamelCase     :     Optional[Any]			    =       False
					lowerCamelCase     :     str			    =       False
					lowerCamelCase     :     Optional[Any]			    =       False
					lowerCamelCase     :     str			    =       False
					lowerCamelCase     :     List[Any]			    =       False





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple		):






						'''simple docstring'''







						UpperCAmelCase_								=     TFRegNetModelTester(self		)
						UpperCAmelCase_								=     ConfigTester(self ,					config_class=__lowercase ,					has_text_modality=__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						return





					@unittest.skip(reason="""RegNet does not use inputs_embeds"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''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        SCREAMING_SNAKE_CASE							(						self    :  List[str]		):






						'''simple docstring'''







						super().test_keras_fit()





					@unittest.skip(reason="""RegNet does not support input and output embeddings"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						pass





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							UpperCAmelCase_								=     model_class(__lowercase		)
							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] ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						def check_hidden_states_output(__lowercase    :  Tuple ,					__lowercase    :  Any ,					__lowercase    :  Optional[Any]		):
							UpperCAmelCase_								=     model_class(__lowercase		)
							UpperCAmelCase_								=     model(**self._prepare_for_class(__lowercase ,					__lowercase		) ,					training=__lowercase		)

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

							UpperCAmelCase_								=     self.model_tester.num_stages
							self.assertEqual(len(__lowercase		) ,					expected_num_stages + 1		)

							# RegNet'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 // 2, self.model_tester.image_size // 2] ,					)

						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()
						UpperCAmelCase_								=     ["""basic""", """bottleneck"""]
						for model_class in self.all_model_classes:
							for layer_type in layers_type:
								UpperCAmelCase_								=     layer_type
								UpperCAmelCase_								=     True
								check_hidden_states_output(__lowercase ,					__lowercase ,					__lowercase		)

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

								check_hidden_states_output(__lowercase ,					__lowercase ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

						def check_equivalence(__lowercase    :  Any ,					__lowercase    :  Any ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  Optional[int]={}		):
							UpperCAmelCase_								=     model(__lowercase ,					return_dict=__lowercase ,					**__lowercase		)
							UpperCAmelCase_								=     model(__lowercase ,					return_dict=__lowercase ,					**__lowercase		).to_tuple()

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

								recursive_check(__lowercase ,					__lowercase		)

						for model_class in self.all_model_classes:
							UpperCAmelCase_								=     model_class(__lowercase		)

							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase		)
							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase		)
							check_equivalence(__lowercase ,					__lowercase ,					__lowercase		)

							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase ,					return_labels=__lowercase		)
							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase ,					return_labels=__lowercase		)
							check_equivalence(__lowercase ,					__lowercase ,					__lowercase		)

							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase		)
							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase		)
							check_equivalence(__lowercase ,					__lowercase ,					__lowercase ,					{"""output_hidden_states""": True}		)

							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase ,					return_labels=__lowercase		)
							UpperCAmelCase_								=     self._prepare_for_class(__lowercase ,					__lowercase ,					return_labels=__lowercase		)
							check_equivalence(__lowercase ,					__lowercase ,					__lowercase ,					{"""output_hidden_states""": True}		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__lowercase		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any]		):






						'''simple docstring'''







						for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_								=     TFRegNetModel.from_pretrained(__lowercase		)
							self.assertIsNotNone(__lowercase		)




def    A_(			):
	UpperCAmelCase_								=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
	return image







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







					'''simple docstring'''

					@cached_property
					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						return (
						    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
						    if is_vision_available()
						    else None
						)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

						UpperCAmelCase_								=     self.default_image_processor
						UpperCAmelCase_								=     prepare_img()
						UpperCAmelCase_								=     image_processor(images=__lowercase ,					return_tensors="""tf"""		)

						# forward pass
						UpperCAmelCase_								=     model(**__lowercase ,					training=__lowercase		)

						# verify the logits
						UpperCAmelCase_								=     tf.TensorShape((1, 10_00)		)
						self.assertEqual(outputs.logits.shape ,					__lowercase		)

						UpperCAmelCase_								=     tf.constant([-0.4180, -1.5051, -3.4836]		)

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









import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
				from PIL import Image

				from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor







@require_vision
class   _UpperCamelCase  (       unittest.TestCase  ):







					'''simple docstring'''

					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     tempfile.mkdtemp()

						UpperCAmelCase_								=     [
						    """[UNK]""",
						    """[CLS]""",
						    """[SEP]""",
						    """[PAD]""",
						    """[MASK]""",
						    """的""",
						    """价""",
						    """格""",
						    """是""",
						    """15""",
						    """便""",
						    """alex""",
						    """##andra""",
						    """，""",
						    """。""",
						    """-""",
						    """t""",
						    """shirt""",
						]
						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					VOCAB_FILES_NAMES["""vocab_file"""]		)
						with open(self.vocab_file ,					"""w""" ,					encoding="""utf-8"""		) as vocab_writer:
							vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

						UpperCAmelCase_								=     {
						    """do_resize""": True,
						    """size""": {"""height""": 2_24, """width""": 2_24},
						    """do_center_crop""": True,
						    """crop_size""": {"""height""": 18, """width""": 18},
						    """do_normalize""": True,
						    """image_mean""": [0.48145466, 0.4578275, 0.40821073],
						    """image_std""": [0.26862954, 0.26130258, 0.27577711],
						    """do_convert_rgb""": True,
						}
						UpperCAmelCase_								=     os.path.join(self.tmpdirname ,					__lowercase		)
						with open(self.image_processor_file ,					"""w""" ,					encoding="""utf-8"""		) as fp:
							json.dump(__lowercase ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					**__lowercase    :  Optional[Any]		):






						'''simple docstring'''







						return BertTokenizer.from_pretrained(self.tmpdirname ,					**__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any] ,					**__lowercase    :  Optional[Any]		):






						'''simple docstring'''







						return BertTokenizerFast.from_pretrained(self.tmpdirname ,					**__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  int ,					**__lowercase    :  int		):






						'''simple docstring'''







						return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname ,					**__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						shutil.rmtree(self.tmpdirname		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[int]		):






						'''simple docstring'''







						UpperCAmelCase_								=     [np.random.randint(2_55 ,					size=(3, 30, 4_00) ,					dtype=np.uinta		)]

						UpperCAmelCase_								=     [Image.fromarray(np.moveaxis(__lowercase ,					0 ,					-1		)		) for x in image_inputs]

						return image_inputs





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_tokenizer()
						UpperCAmelCase_								=     self.get_rust_tokenizer()
						UpperCAmelCase_								=     self.get_image_processor()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)
						processor_slow.save_pretrained(self.tmpdirname		)
						UpperCAmelCase_								=     ChineseCLIPProcessor.from_pretrained(self.tmpdirname ,					use_fast=__lowercase		)

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)
						processor_fast.save_pretrained(self.tmpdirname		)
						UpperCAmelCase_								=     ChineseCLIPProcessor.from_pretrained(self.tmpdirname		)

						self.assertEqual(processor_slow.tokenizer.get_vocab() ,					tokenizer_slow.get_vocab()		)
						self.assertEqual(processor_fast.tokenizer.get_vocab() ,					tokenizer_fast.get_vocab()		)
						self.assertEqual(tokenizer_slow.get_vocab() ,					tokenizer_fast.get_vocab()		)
						self.assertIsInstance(processor_slow.tokenizer ,					__lowercase		)
						self.assertIsInstance(processor_fast.tokenizer ,					__lowercase		)

						self.assertEqual(processor_slow.image_processor.to_json_string() ,					image_processor.to_json_string()		)
						self.assertEqual(processor_fast.image_processor.to_json_string() ,					image_processor.to_json_string()		)
						self.assertIsInstance(processor_slow.image_processor ,					__lowercase		)
						self.assertIsInstance(processor_fast.image_processor ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''simple docstring'''







						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=self.get_tokenizer() ,					image_processor=self.get_image_processor()		)
						processor.save_pretrained(self.tmpdirname		)

						UpperCAmelCase_								=     self.get_tokenizer(cls_token="""(CLS)""" ,					sep_token="""(SEP)"""		)
						UpperCAmelCase_								=     self.get_image_processor(do_normalize=__lowercase		)

						UpperCAmelCase_								=     ChineseCLIPProcessor.from_pretrained(
						    self.tmpdirname ,					cls_token="""(CLS)""" ,					sep_token="""(SEP)""" ,					do_normalize=__lowercase		)

						self.assertEqual(processor.tokenizer.get_vocab() ,					tokenizer_add_kwargs.get_vocab()		)
						self.assertIsInstance(processor.tokenizer ,					__lowercase		)

						self.assertEqual(processor.image_processor.to_json_string() ,					image_processor_add_kwargs.to_json_string()		)
						self.assertIsInstance(processor.image_processor ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Tuple		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_image_processor()
						UpperCAmelCase_								=     self.get_tokenizer()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)

						UpperCAmelCase_								=     self.prepare_image_inputs()

						UpperCAmelCase_								=     image_processor(__lowercase ,					return_tensors="""np"""		)
						UpperCAmelCase_								=     processor(images=__lowercase ,					return_tensors="""np"""		)

						for key in input_feat_extract.keys():
							self.assertAlmostEqual(input_feat_extract[key].sum() ,					input_processor[key].sum() ,					delta=1e-2		)





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_image_processor()
						UpperCAmelCase_								=     self.get_tokenizer()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)

						UpperCAmelCase_								=     """Alexandra，T-shirt的价格是15便士。"""

						UpperCAmelCase_								=     processor(text=__lowercase		)

						UpperCAmelCase_								=     tokenizer(__lowercase		)

						for key in encoded_tok.keys():
							self.assertListEqual(encoded_tok[key] ,					encoded_processor[key]		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_image_processor()
						UpperCAmelCase_								=     self.get_tokenizer()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)

						UpperCAmelCase_								=     """Alexandra，T-shirt的价格是15便士。"""
						UpperCAmelCase_								=     self.prepare_image_inputs()

						UpperCAmelCase_								=     processor(text=__lowercase ,					images=__lowercase		)

						self.assertListEqual(list(inputs.keys()		) ,					["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""]		)

						# test if it raises when no input is passed
						with pytest.raises(__lowercase		):
							processor()





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_image_processor()
						UpperCAmelCase_								=     self.get_tokenizer()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)

						UpperCAmelCase_								=     [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

						UpperCAmelCase_								=     processor.batch_decode(__lowercase		)
						UpperCAmelCase_								=     tokenizer.batch_decode(__lowercase		)

						self.assertListEqual(__lowercase ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.get_image_processor()
						UpperCAmelCase_								=     self.get_tokenizer()

						UpperCAmelCase_								=     ChineseCLIPProcessor(tokenizer=__lowercase ,					image_processor=__lowercase		)

						UpperCAmelCase_								=     """Alexandra，T-shirt的价格是15便士。"""
						UpperCAmelCase_								=     self.prepare_image_inputs()

						UpperCAmelCase_								=     processor(text=__lowercase ,					images=__lowercase		)

						self.assertListEqual(list(inputs.keys()		) ,					processor.model_input_names		)


