




import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import RegNetForImageClassification, RegNetModel
		from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class 					snake_case__							:
				"""simple docstring"""



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





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

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

							a					=    self.get_config()

							return config, pixel_values, labels





				def 							__UpperCAmelCase							(   self       :  Union[str, Any]							)      ->  int:
							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 							__UpperCAmelCase							(   self       :  int      ,   __lowerCamelCase       :  Optional[int]      ,   __lowerCamelCase       :  Union[str, Any]      ,   __lowerCamelCase       :  Optional[Any]							)      ->  Dict:
							a					=    RegNetModel(config=__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a					=    model(__lowerCamelCase							)
							# 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 							__UpperCAmelCase							(   self       :  Tuple      ,   __lowerCamelCase       :  Optional[Any]      ,   __lowerCamelCase       :  Any      ,   __lowerCamelCase       :  Union[str, Any]							)      ->  Dict:
							a					=    self.num_labels
							a					=    RegNetForImageClassification(__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a					=    model(__lowerCamelCase      ,   labels=__lowerCamelCase							)
							self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels)							)





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  Dict:
							a					=    self.prepare_config_and_inputs()
							a					,	a					,	a					=    config_and_inputs
							a					=    {"pixel_values": pixel_values}
							return config, inputs_dict




@require_torch
class 					snake_case__							(_UpperCamelCase					, _UpperCamelCase					, unittest.TestCase     ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_ :							Dict											=      (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE_ :							Optional[int]											=      (
				    {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE_ :							Optional[int]											=      False
				SCREAMING_SNAKE_CASE_ :							Any											=      False
				SCREAMING_SNAKE_CASE_ :							Optional[int]											=      False
				SCREAMING_SNAKE_CASE_ :							Tuple											=      False





				def 							__UpperCAmelCase							(   self       :  Optional[Any]							)      ->  Any:
							a					=    RegNetModelTester(self							)
							a					=    ConfigTester(self      ,   config_class=__lowerCamelCase      ,   has_text_modality=__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  str							)      ->  Tuple:
							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       :  List[Any]							)      ->  str:
							return





				@unittest.skip(reason="RegNet does not use inputs_embeds"							)
				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  Any:
							pass





				@unittest.skip(reason="RegNet does not support input and output embeddings"							)
				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  int:
							pass





				def 							__UpperCAmelCase							(   self       :  Tuple							)      ->  Union[str, Any]:
							a					,	a					=    self.model_tester.prepare_config_and_inputs_for_common()

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

										a					=    ["pixel_values"]
										self.assertListEqual(arg_names[:1]      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  str							)      ->  Dict:
							a					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[Any]:
							a					,	a					=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a					=    model_class(config=__lowerCamelCase							)
										for name, module in model.named_modules():
													if isinstance(__lowerCamelCase      ,   (nn.BatchNormad, nn.GroupNorm)							):
																self.assertTrue(
																    torch.all(module.weight == 1							)      ,   msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""      ,   )
																self.assertTrue(
																    torch.all(module.bias == 0							)      ,   msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""      ,   )





				def 							__UpperCAmelCase							(   self       :  str							)      ->  Union[str, Any]:
							def check_hidden_states_output(__lowerCamelCase       :  int      ,   __lowerCamelCase       :  Optional[int]      ,   __lowerCamelCase       :  Union[str, Any]							):
										a					=    model_class(__lowerCamelCase							)
										model.to(__lowerCamelCase							)
										model.eval()

										with torch.no_grad():
													a					=    model(**self._prepare_for_class(__lowerCamelCase      ,   __lowerCamelCase							)							)

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

										a					=    self.model_tester.num_stages
										self.assertEqual(len(__lowerCamelCase							)      ,   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]      ,   )

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

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

													check_hidden_states_output(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Optional[Any]							)      ->  str:
							a					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)





				@slow
				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Tuple:
							for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a					=    RegNetModel.from_pretrained(__lowerCamelCase							)
										self.assertIsNotNone(__lowerCamelCase							)




def     __magic_name__       (				):






			'''simple docstring'''







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






@require_torch
@require_vision
class 					snake_case__							(unittest.TestCase     ):
				"""simple docstring"""



				@cached_property
				def 							__UpperCAmelCase							(   self       :  Any							)      ->  int:
							return (
							    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
							    if is_vision_available()
							    else None
							)





				@slow
				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[int]:
							a					=    RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(__lowerCamelCase							)

							a					=    self.default_image_processor
							a					=    prepare_img()
							a					=    image_processor(images=__lowerCamelCase      ,   return_tensors="pt"							).to(__lowerCamelCase							)

							# forward pass
							with torch.no_grad():
										a					=    model(**__lowerCamelCase							)

							# verify the logits
							a					=    torch.Size((1, 10_00)							)
							self.assertEqual(outputs.logits.shape      ,   __lowerCamelCase							)

							a					=    torch.tensor([-0.4_180, -1.5_051, -3.4_836]							).to(__lowerCamelCase							)

							self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,   __lowerCamelCase      ,   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 					snake_case__							(unittest.TestCase     ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(   self       :  int							)      ->  Dict:
							a					=    tempfile.mkdtemp()

							a					=    [
							    "[UNK]",
							    "[CLS]",
							    "[SEP]",
							    "[PAD]",
							    "[MASK]",
							    "的",
							    "价",
							    "格",
							    "是",
							    "15",
							    "便",
							    "alex",
							    "##andra",
							    "，",
							    "。",
							    "-",
							    "t",
							    "shirt",
							]
							a					=    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]							)							)

							a					=    {
							    "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.48_145_466, 0.4_578_275, 0.40_821_073],
							    "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711],
							    "do_convert_rgb": True,
							}
							a					=    os.path.join(self.tmpdirname      ,   __lowerCamelCase							)
							with open(self.image_processor_file      ,   "w"      ,   encoding="utf-8"							) as fp:
										json.dump(__lowerCamelCase      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Dict      ,   **__lowerCamelCase       :  Union[str, Any]							)      ->  List[Any]:
							return BertTokenizer.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  str      ,   **__lowerCamelCase       :  Optional[int]							)      ->  str:
							return BertTokenizerFast.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  List[str]      ,   **__lowerCamelCase       :  Optional[int]							)      ->  Tuple:
							return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname      ,   **__lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  Optional[Any]:
							shutil.rmtree(self.tmpdirname							)





				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[int]:
							a					=    [np.random.randint(2_55      ,   size=(3, 30, 4_00)      ,   dtype=np.uinta							)]

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

							return image_inputs





				def 							__UpperCAmelCase							(   self       :  int							)      ->  List[str]:
							a					=    self.get_tokenizer()
							a					=    self.get_rust_tokenizer()
							a					=    self.get_image_processor()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)
							processor_slow.save_pretrained(self.tmpdirname							)
							a					=    ChineseCLIPProcessor.from_pretrained(self.tmpdirname      ,   use_fast=__lowerCamelCase							)

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)
							processor_fast.save_pretrained(self.tmpdirname							)
							a					=    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      ,   __lowerCamelCase							)
							self.assertIsInstance(processor_fast.tokenizer      ,   __lowerCamelCase							)

							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      ,   __lowerCamelCase							)
							self.assertIsInstance(processor_fast.image_processor      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Optional[int]							)      ->  List[Any]:
							a					=    ChineseCLIPProcessor(tokenizer=self.get_tokenizer()      ,   image_processor=self.get_image_processor()							)
							processor.save_pretrained(self.tmpdirname							)

							a					=    self.get_tokenizer(cls_token="(CLS)"      ,   sep_token="(SEP)"							)
							a					=    self.get_image_processor(do_normalize=__lowerCamelCase							)

							a					=    ChineseCLIPProcessor.from_pretrained(
							    self.tmpdirname      ,   cls_token="(CLS)"      ,   sep_token="(SEP)"      ,   do_normalize=__lowerCamelCase							)

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

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





				def 							__UpperCAmelCase							(   self       :  Tuple							)      ->  Dict:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

							a					=    self.prepare_image_inputs()

							a					=    image_processor(__lowerCamelCase      ,   return_tensors="np"							)
							a					=    processor(images=__lowerCamelCase      ,   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 							__UpperCAmelCase							(   self       :  str							)      ->  Optional[int]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

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

							a					=    processor(text=__lowerCamelCase							)

							a					=    tokenizer(__lowerCamelCase							)

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





				def 							__UpperCAmelCase							(   self       :  List[Any]							)      ->  Any:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

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

							a					=    processor(text=__lowerCamelCase      ,   images=__lowerCamelCase							)

							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(__lowerCamelCase							):
										processor()





				def 							__UpperCAmelCase							(   self       :  List[str]							)      ->  Optional[int]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

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

							a					=    processor.batch_decode(__lowerCamelCase							)
							a					=    tokenizer.batch_decode(__lowerCamelCase							)

							self.assertListEqual(__lowerCamelCase      ,   __lowerCamelCase							)





				def 							__UpperCAmelCase							(   self       :  Dict							)      ->  List[str]:
							a					=    self.get_image_processor()
							a					=    self.get_tokenizer()

							a					=    ChineseCLIPProcessor(tokenizer=__lowerCamelCase      ,   image_processor=__lowerCamelCase							)

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

							a					=    processor(text=__lowerCamelCase      ,   images=__lowerCamelCase							)

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






