

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   __lowercase    :




			"""simple docstring"""







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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					int):
									SCREAMING_SNAKE_CASE_:			Optional[Any]   		=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

									SCREAMING_SNAKE_CASE_:			Union[str, Any]   		=	self.get_config()

									return config, pixel_values, labels



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									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 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					List[Any]       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					str):
									SCREAMING_SNAKE_CASE_:			List[Any]   		=	TFResNetModel(config=_a)
									SCREAMING_SNAKE_CASE_:			List[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 // 32, self.image_size // 32)       ,						)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					Any       ,						lowerCAmelCase__  :					List[str]):
									SCREAMING_SNAKE_CASE_:			str   		=	self.num_labels
									SCREAMING_SNAKE_CASE_:			Tuple   		=	TFResNetForImageClassification(_a)
									SCREAMING_SNAKE_CASE_:			Tuple   		=	model(_a       ,						labels=_a)
									self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.num_labels))




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict):
									SCREAMING_SNAKE_CASE_:			List[Any]   		=	self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_:			Dict   		=	config_and_inputs
									SCREAMING_SNAKE_CASE_:			Union[str, Any]   		=	{"pixel_values": pixel_values}
									return config, inputs_dict







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




			"""simple docstring"""







			_UpperCAmelCase       :							List[str]      							=					(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
			_UpperCAmelCase       :							Tuple      							=					(
			    {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			_UpperCAmelCase       :							int      							=					False
			_UpperCAmelCase       :							Union[str, Any]      							=					False
			_UpperCAmelCase       :							List[Any]      							=					False
			_UpperCAmelCase       :							List[Any]      							=					False
			_UpperCAmelCase       :							List[str]      							=					False



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Any):
									SCREAMING_SNAKE_CASE_:			Dict   		=	TFResNetModelTester(self)
									SCREAMING_SNAKE_CASE_:			Optional[Any]   		=	ConfigTester(self       ,						config_class=_a       ,						has_text_modality=_a)



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



			@unittest.skip(reason="ResNet does not use inputs_embeds")
			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									pass



			@unittest.skip(reason="ResNet does not support input and output embeddings")
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									pass



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			List[Any]   		=	self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_:			List[Any]   		=	model_class(_a)
															SCREAMING_SNAKE_CASE_:			Any   		=	inspect.signature(model.call)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															SCREAMING_SNAKE_CASE_:			Tuple   		=	[*signature.parameters.keys()]

															SCREAMING_SNAKE_CASE_:			Any   		=	["pixel_values"]
															self.assertListEqual(arg_names[:1]       ,						_a)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									SCREAMING_SNAKE_CASE_:			str   		=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_a)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]):
									def check_hidden_states_output(lowerCAmelCase__  :					List[str]       ,						lowerCAmelCase__  :					Union[str, Any]       ,						lowerCAmelCase__  :					List[Any]):
															SCREAMING_SNAKE_CASE_:			int   		=	model_class(_a)
															SCREAMING_SNAKE_CASE_:			Any   		=	model(**self._prepare_for_class(_a       ,						_a))

															SCREAMING_SNAKE_CASE_:			Any   		=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															SCREAMING_SNAKE_CASE_:			List[str]   		=	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]       ,						)

									SCREAMING_SNAKE_CASE_:			Optional[int]   		=	self.model_tester.prepare_config_and_inputs_for_common()
									SCREAMING_SNAKE_CASE_:			Any   		=	["basic", "bottleneck"]
									for model_class in self.all_model_classes:
															for layer_type in layers_type:
																					SCREAMING_SNAKE_CASE_:			Union[str, Any]   		=	layer_type
																					SCREAMING_SNAKE_CASE_:			str   		=	True
																					check_hidden_states_output(_a       ,						_a       ,						_a)

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

																					check_hidden_states_output(_a       ,						_a       ,						_a)



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str):
									SCREAMING_SNAKE_CASE_:			str   		=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_a)




			@slow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]):
									for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															SCREAMING_SNAKE_CASE_:			Union[str, Any]   		=	TFResNetModel.from_pretrained(_a)
															self.assertIsNotNone(_a)







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



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




			"""simple docstring"""







			@cached_property
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									return (
									    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
									    if is_vision_available()
									    else None
									)




			@slow
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]):
									SCREAMING_SNAKE_CASE_:			Optional[int]   		=	TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

									SCREAMING_SNAKE_CASE_:			str   		=	self.default_image_processor
									SCREAMING_SNAKE_CASE_:			List[str]   		=	prepare_img()
									SCREAMING_SNAKE_CASE_:			int   		=	image_processor(images=_a       ,						return_tensors="tf")

									# forward pass
									SCREAMING_SNAKE_CASE_:			Tuple   		=	model(**_a)

									# verify the logits
									SCREAMING_SNAKE_CASE_:			Optional[Any]   		=	tf.TensorShape((1, 1000))
									self.assertEqual(outputs.logits.shape       ,						_a)

									SCREAMING_SNAKE_CASE_:			str   		=	tf.constant([-11.1069, -9.7877, -8.3777])

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









import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer


lowerCAmelCase							:  Any            =						logging.get_logger(__name__)

lowerCAmelCase							:  Dict            =						{"""vocab_file""": """vocab.txt"""}

lowerCAmelCase							:  List[str]            =						{
    """vocab_file""": {
        """YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""",
        """YituTech/conv-bert-medium-small""": (
            """https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"""
        ),
        """YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""",
    }
}

lowerCAmelCase							:  List[Any]            =						{
    """YituTech/conv-bert-base""": 512,
    """YituTech/conv-bert-medium-small""": 512,
    """YituTech/conv-bert-small""": 512,
}


lowerCAmelCase							:  Tuple            =						{
    """YituTech/conv-bert-base""": {"""do_lower_case""": True},
    """YituTech/conv-bert-medium-small""": {"""do_lower_case""": True},
    """YituTech/conv-bert-small""": {"""do_lower_case""": True},
}



class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							str      							=					VOCAB_FILES_NAMES
			_UpperCAmelCase       :							List[str]      							=					PRETRAINED_VOCAB_FILES_MAP
			_UpperCAmelCase       :							List[Any]      							=					PRETRAINED_INIT_CONFIGURATION
			_UpperCAmelCase       :							Optional[Any]      							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			_UpperCAmelCase       :							Dict      							=					ConvBertTokenizer



			def __init__(			self  :					Optional[Any]       ,						lowerCAmelCase__  :					Optional[int]=None       ,						lowerCAmelCase__  :					List[str]=None       ,						lowerCAmelCase__  :					str=True       ,						lowerCAmelCase__  :					Any="[UNK]"       ,						lowerCAmelCase__  :					Optional[Any]="[SEP]"       ,						lowerCAmelCase__  :					Any="[PAD]"       ,						lowerCAmelCase__  :					Dict="[CLS]"       ,						lowerCAmelCase__  :					Dict="[MASK]"       ,						lowerCAmelCase__  :					Tuple=True       ,						lowerCAmelCase__  :					str=None       ,						**lowerCAmelCase__  :					Dict       ,						):
									super().__init__(
									    lowerCAmelCase__       ,						tokenizer_file=lowerCAmelCase__       ,						do_lower_case=lowerCAmelCase__       ,						unk_token=lowerCAmelCase__       ,						sep_token=lowerCAmelCase__       ,						pad_token=lowerCAmelCase__       ,						cls_token=lowerCAmelCase__       ,						mask_token=lowerCAmelCase__       ,						tokenize_chinese_chars=lowerCAmelCase__       ,						strip_accents=lowerCAmelCase__       ,						**lowerCAmelCase__       ,						)

									SCREAMING_SNAKE_CASE_:			List[str]  		=	json.loads(self.backend_tokenizer.normalizer.__getstate__())
									if (
									    normalizer_state.get("lowercase"       ,						lowerCAmelCase__) != do_lower_case
									    or normalizer_state.get("strip_accents"       ,						lowerCAmelCase__) != strip_accents
									    or normalizer_state.get("handle_chinese_chars"       ,						lowerCAmelCase__) != tokenize_chinese_chars
									):
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	getattr(lowerCAmelCase__       ,						normalizer_state.pop("type"))
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	do_lower_case
															SCREAMING_SNAKE_CASE_:			List[str]  		=	strip_accents
															SCREAMING_SNAKE_CASE_:			Optional[Any]  		=	tokenize_chinese_chars
															SCREAMING_SNAKE_CASE_:			Optional[int]  		=	normalizer_class(**lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	do_lower_case



			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					Optional[int]       ,						lowerCAmelCase__  :					Union[str, Any]=None):
									SCREAMING_SNAKE_CASE_:			List[str]  		=	[self.cls_token_id] + token_ids_a + [self.sep_token_id]

									if token_ids_a:
															output += token_ids_a + [self.sep_token_id]

									return output



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					List[int]       ,						lowerCAmelCase__  :					Optional[List[int]] = None):
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	[self.sep_token_id]
									SCREAMING_SNAKE_CASE_:			int  		=	[self.cls_token_id]
									if token_ids_a is None:
															return len(cls + token_ids_a + sep) * [0]
									return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1]




			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					Optional[str] = None):
									SCREAMING_SNAKE_CASE_:			Any  		=	self._tokenizer.model.save(lowerCAmelCase__       ,						name=lowerCAmelCase__)
									return tuple(lowerCAmelCase__)






