
'''simple docstring'''


from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
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 TFViTForImageClassification, TFViTModel


if is_vision_available():
					from PIL import Image

					from transformers import ViTImageProcessor

class 						__lowercase					:

			def __init__(self      , A      , A=1_3      , A=3_0      , A=2      , A=3      , A=True      , A=True      , A=3_2      , A=2      , A=4      , A=3_7      , A="gelu"      , A=0.1      , A=0.1      , A=1_0      , A=0.02      , A=3      , A=None      , ):
								lowerCamelCase_       :   Any  =		parent
								lowerCamelCase_       :   Any  =		batch_size
								lowerCamelCase_       :   Optional[int]  =		image_size
								lowerCamelCase_       :   List[Any]  =		patch_size
								lowerCamelCase_       :   int  =		num_channels
								lowerCamelCase_       :   Optional[Any]  =		is_training
								lowerCamelCase_       :   int  =		use_labels
								lowerCamelCase_       :   int  =		hidden_size
								lowerCamelCase_       :   Optional[Any]  =		num_hidden_layers
								lowerCamelCase_       :   str  =		num_attention_heads
								lowerCamelCase_       :   Any  =		intermediate_size
								lowerCamelCase_       :   List[str]  =		hidden_act
								lowerCamelCase_       :   int  =		hidden_dropout_prob
								lowerCamelCase_       :   str  =		attention_probs_dropout_prob
								lowerCamelCase_       :   Tuple  =		type_sequence_label_size
								lowerCamelCase_       :   Any  =		initializer_range
								lowerCamelCase_       :   Dict  =		scope

								# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
								lowerCamelCase_       :   Tuple  =		(image_size // patch_size) ** 2
								lowerCamelCase_       :   List[Any]  =		num_patches + 1

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Tuple  =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

								lowerCamelCase_       :   str  =		None
								if self.use_labels:
													lowerCamelCase_       :   List[str]  =		ids_tensor([self.batch_size]      , self.type_sequence_label_size   )

								lowerCamelCase_       :   Tuple  =		self.get_config()

								return config, pixel_values, labels

			def 							UpperCAmelCase__			(self   ):
								return ViTConfig(
								    image_size=self.image_size      , patch_size=self.patch_size      , num_channels=self.num_channels      , hidden_size=self.hidden_size      , num_hidden_layers=self.num_hidden_layers      , num_attention_heads=self.num_attention_heads      , intermediate_size=self.intermediate_size      , hidden_act=self.hidden_act      , hidden_dropout_prob=self.hidden_dropout_prob      , attention_probs_dropout_prob=self.attention_probs_dropout_prob      , is_decoder=_lowercase      , initializer_range=self.initializer_range      , )

			def 							UpperCAmelCase__			(self      , A      , A      , A   ):
								lowerCamelCase_       :   Optional[int]  =		TFViTModel(config=_lowercase   )
								lowerCamelCase_       :   Optional[Any]  =		model(_lowercase      , training=_lowercase   )
								self.parent.assertEqual(result.last_hidden_state.shape      , (self.batch_size, self.seq_length, self.hidden_size)   )

								# Test with an image with different size than the one specified in config.
								lowerCamelCase_       :   Dict  =		self.image_size // 2
								lowerCamelCase_       :   Any  =		pixel_values[:, :, :image_size, :image_size]
								lowerCamelCase_       :   List[Any]  =		model(_lowercase      , interpolate_pos_encoding=_lowercase      , training=_lowercase   )
								lowerCamelCase_       :   List[Any]  =		(image_size // self.patch_size) ** 2 + 1
								self.parent.assertEqual(result.last_hidden_state.shape      , (self.batch_size, seq_length, self.hidden_size)   )

			def 							UpperCAmelCase__			(self      , A      , A      , A   ):
								lowerCamelCase_       :   Optional[Any]  =		self.type_sequence_label_size
								lowerCamelCase_       :   List[Any]  =		TFViTForImageClassification(_lowercase   )
								lowerCamelCase_       :   int  =		model(_lowercase      , labels=_lowercase      , training=_lowercase   )
								self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.type_sequence_label_size)   )

								# Test with an image with different size than the one specified in config.
								lowerCamelCase_       :   List[str]  =		self.image_size // 2
								lowerCamelCase_       :   Any  =		pixel_values[:, :, :image_size, :image_size]
								lowerCamelCase_       :   int  =		model(_lowercase      , interpolate_pos_encoding=_lowercase      , training=_lowercase   )
								self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.type_sequence_label_size)   )

								# test greyscale images
								lowerCamelCase_       :   List[Any]  =		1
								lowerCamelCase_       :   Any  =		TFViTForImageClassification(_lowercase   )
								lowerCamelCase_       :   Dict  =		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
								lowerCamelCase_       :   Optional[int]  =		model(_lowercase   )
								self.parent.assertEqual(result.logits.shape      , (self.batch_size, self.type_sequence_label_size)   )






			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Union[str, Any]  =		self.prepare_config_and_inputs()
								lowerCamelCase_       :   Union[str, Any]  =		config_and_inputs
								lowerCamelCase_       :   str  =		{"pixel_values": pixel_values}
								return config, inputs_dict

@require_tf
class 						__lowercase					(	SCREAMING_SNAKE_CASE__   ,  SCREAMING_SNAKE_CASE__   ,  unittest.TestCase     ):
			lowerCamelCase      :		Dict						   =      (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
			lowerCamelCase      :		Dict						   =      (
			    {"feature-extraction": TFViTModel, "image-classification": TFViTForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase      :		str						   =      False
			lowerCamelCase      :		Tuple						   =      False
			lowerCamelCase      :		Optional[int]						   =      False

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   int  =		TFViTModelTester(self   )
								lowerCamelCase_       :   List[str]  =		ConfigTester(self      , config_class=_lowercase      , has_text_modality=_lowercase      , hidden_size=3_7   )

			def 							UpperCAmelCase__			(self   ):
								self.config_tester.run_common_tests()

			@unittest.skip(reason='''ViT does not use inputs_embeds'''   )
			def 							UpperCAmelCase__			(self   ):
								pass

			@unittest.skip(reason='''ViT does not use inputs_embeds'''   )
			def 							UpperCAmelCase__			(self   ):
								pass

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Optional[int]  =		self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													lowerCamelCase_       :   List[str]  =		model_class(_lowercase   )
													self.assertIsInstance(model.get_input_embeddings()      , (tf.keras.layers.Layer)   )
													lowerCamelCase_       :   Dict  =		model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_lowercase      , tf.keras.layers.Layer   )   )

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Tuple  =		self.model_tester.prepare_config_and_inputs_for_common()

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

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

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Union[str, Any]  =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowercase   )

			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Union[str, Any]  =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*_lowercase   )






			@slow
			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Optional[Any]  =		TFViTModel.from_pretrained('''google/vit-base-patch16-224'''   )
								self.assertIsNotNone(_lowercase   )




def lowercase_						( )  ->				Optional[Any]:
					'''simple docstring'''

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






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

			@cached_property
			def 							UpperCAmelCase__			(self   ):
								return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''   ) if is_vision_available() else None






			@slow
			def 							UpperCAmelCase__			(self   ):
								lowerCamelCase_       :   Optional[Any]  =		TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''   )

								lowerCamelCase_       :   List[str]  =		self.default_image_processor
								lowerCamelCase_       :   int  =		prepare_img()
								lowerCamelCase_       :   List[str]  =		image_processor(images=_lowercase      , return_tensors='''tf'''   )

								# forward pass
								lowerCamelCase_       :   Union[str, Any]  =		model(**_lowercase   )

								# verify the logits
								lowerCamelCase_       :   int  =		tf.TensorShape((1, 1_0_0_0)   )
								self.assertEqual(outputs.logits.shape      , _lowercase   )

								lowerCamelCase_       :   str  =		tf.constant([-0.27_44, 0.82_15, -0.08_36]   )

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







"""simple docstring"""







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from ..utils import cached_file


# docstyle-ignore
A		=						'\nHuman: <<task>>\n\nAssistant: '


A		=						'huggingface-tools/default-prompts'
A		=						{'chat': 'chat_prompt_template.txt', 'run': 'run_prompt_template.txt'}

def  __SCREAMING_SNAKE_CASE		(			lowerCamelCase_:							Optional[int]     ,		lowerCamelCase_:							str     ,		lowerCamelCase_:							Tuple="run" ):
						"""simple docstring"""






						if prompt_or_repo_id is None:
												snake_case   :			Any						    = DEFAULT_PROMPTS_REPO

						# prompt is considered a repo ID when it does not contain any kind of space
						if re.search("\\s"     ,		lowerCamelCase_ ) is not None:
												return prompt_or_repo_id

						snake_case   :			Optional[int]						    = cached_file(
						    lowerCamelCase_     ,		PROMPT_FILES[mode]     ,		repo_type="dataset"     ,		user_agent={"agent": agent_name} )
						with open(lowerCamelCase_     ,		"r"     ,		encoding="utf-8" ) as f:
												return f.read()



