






'''simple docstring'''




import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
		import jax

		from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel



class       __lowercase					(unittest.TestCase    ):

	def __init__(      self   :						List[Any]  ,					UpperCAmelCase_   :						Any  ,					UpperCAmelCase_   :						Optional[int]=13  ,					UpperCAmelCase_   :						Tuple=30  ,					UpperCAmelCase_   :						List[str]=2  ,					UpperCAmelCase_   :						int=3  ,					UpperCAmelCase_   :						str=True  ,					UpperCAmelCase_   :						Dict=True  ,					UpperCAmelCase_   :						Tuple=32  ,					UpperCAmelCase_   :						Any=5  ,					UpperCAmelCase_   :						Optional[int]=4  ,					UpperCAmelCase_   :						int=37  ,					UpperCAmelCase_   :						Any="gelu"  ,					UpperCAmelCase_   :						List[Any]=0.1  ,					UpperCAmelCase_   :						List[Any]=0.1  ,					UpperCAmelCase_   :						str=10  ,					UpperCAmelCase_   :						Dict=0.02  ,					):
			UpperCamelCase__				:					Optional[Any]					=					parent
			UpperCamelCase__				:					Optional[int]					=					batch_size
			UpperCamelCase__				:					List[str]					=					image_size
			UpperCamelCase__				:					Dict					=					patch_size
			UpperCamelCase__				:					int					=					num_channels
			UpperCamelCase__				:					Any					=					is_training
			UpperCamelCase__				:					Optional[Any]					=					use_labels
			UpperCamelCase__				:					Any					=					hidden_size
			UpperCamelCase__				:					int					=					num_hidden_layers
			UpperCamelCase__				:					Optional[int]					=					num_attention_heads
			UpperCamelCase__				:					Any					=					intermediate_size
			UpperCamelCase__				:					Dict					=					hidden_act
			UpperCamelCase__				:					List[str]					=					hidden_dropout_prob
			UpperCamelCase__				:					str					=					attention_probs_dropout_prob
			UpperCamelCase__				:					Optional[int]					=					type_sequence_label_size
			UpperCamelCase__				:					str					=					initializer_range

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

	def      __UpperCamelCase							(      self   :						Tuple):
			UpperCamelCase__				:					int					=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

			UpperCamelCase__				:					Tuple					=					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=UpperCAmelCase__  ,					initializer_range=self.initializer_range  ,					)

			return config, pixel_values

	def      __UpperCamelCase							(      self   :						List[Any]  ,					UpperCAmelCase_   :						int  ,					UpperCAmelCase_   :						List[str]):
			UpperCamelCase__				:					Optional[Any]					=					FlaxViTModel(config=UpperCAmelCase__)
			UpperCamelCase__				:					Any					=					model(UpperCAmelCase__)
			# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
			UpperCamelCase__				:					List[Any]					=					(self.image_size, self.image_size)
			UpperCamelCase__				:					Tuple					=					(self.patch_size, self.patch_size)
			UpperCamelCase__				:					str					=					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
			self.parent.assertEqual(result.last_hidden_state.shape  ,					(self.batch_size, num_patches + 1, self.hidden_size))

	def      __UpperCamelCase							(      self   :						Union[str, Any]  ,					UpperCAmelCase_   :						Any  ,					UpperCAmelCase_   :						str):
			UpperCamelCase__				:					Union[str, Any]					=					self.type_sequence_label_size
			UpperCamelCase__				:					Dict					=					FlaxViTForImageClassification(config=UpperCAmelCase__)
			UpperCamelCase__				:					Union[str, Any]					=					model(UpperCAmelCase__)
			self.parent.assertEqual(result.logits.shape  ,					(self.batch_size, self.type_sequence_label_size))

			# test greyscale images
			UpperCamelCase__				:					Tuple					=					1
			UpperCamelCase__				:					Any					=					FlaxViTForImageClassification(UpperCAmelCase__)

			UpperCamelCase__				:					Optional[int]					=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
			UpperCamelCase__				:					Optional[Any]					=					model(UpperCAmelCase__)





	def      __UpperCamelCase							(      self   :						List[str]):
			UpperCamelCase__				:					str					=					self.prepare_config_and_inputs()
			(
			    UpperCamelCase__  
			)				:					Optional[Any]					=					config_and_inputs
			UpperCamelCase__				:					List[Any]					=					{'''pixel_values''': pixel_values}
			return config, inputs_dict



@require_flax
class       __lowercase					(lowercase__   ,				unittest.TestCase    ):
	_lowerCamelCase              =  (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()

	def      __UpperCamelCase							(      self   :						Optional[int]):
			UpperCamelCase__				:					Optional[Any]					=					FlaxViTModelTester(self)
			UpperCamelCase__				:					List[str]					=					ConfigTester(self  ,					config_class=UpperCAmelCase__  ,					has_text_modality=UpperCAmelCase__  ,					hidden_size=37)

	def      __UpperCamelCase							(      self   :						Dict):
			self.config_tester.run_common_tests()

	def      __UpperCamelCase							(      self   :						Tuple):
			UpperCamelCase__				:					Dict					=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*UpperCAmelCase__)

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

	def      __UpperCamelCase							(      self   :						str):
			UpperCamelCase__				:					Optional[Any]					=					self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					UpperCamelCase__				:					Dict					=					model_class(UpperCAmelCase__)
					UpperCamelCase__				:					Tuple					=					inspect.signature(model.__call__)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					UpperCamelCase__				:					Tuple					=					[*signature.parameters.keys()]

					UpperCamelCase__				:					List[str]					=					['''pixel_values''']
					self.assertListEqual(arg_names[:1]  ,					UpperCAmelCase__)

	def      __UpperCamelCase							(      self   :						str):
			UpperCamelCase__				:					int					=					self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					with self.subTest(model_class.__name__):
							UpperCamelCase__				:					Dict					=					self._prepare_for_class(UpperCAmelCase__  ,					UpperCAmelCase__)
							UpperCamelCase__				:					Union[str, Any]					=					model_class(UpperCAmelCase__)

							@jax.jit
							def model_jitted(UpperCAmelCase_   :						Tuple  ,					**UpperCAmelCase_   :						Dict):
									return model(pixel_values=UpperCAmelCase__  ,					**UpperCAmelCase__)

							with self.subTest('JIT Enabled'):
									UpperCamelCase__				:					Dict					=					model_jitted(**UpperCAmelCase__).to_tuple()

							with self.subTest('JIT Disabled'):
									with jax.disable_jit():
											UpperCamelCase__				:					Tuple					=					model_jitted(**UpperCAmelCase__).to_tuple()

							self.assertEqual(len(UpperCAmelCase__)  ,					len(UpperCAmelCase__))
							for jitted_output, output in zip(UpperCAmelCase__  ,					UpperCAmelCase__):
									self.assertEqual(jitted_output.shape  ,					output.shape)





	@slow
	def      __UpperCamelCase							(      self   :						Tuple):
			for model_class_name in self.all_model_classes:
					UpperCamelCase__				:					Union[str, Any]					=					model_class_name.from_pretrained('google/vit-base-patch16-224')
					UpperCamelCase__				:					Tuple					=					model(np.ones((1, 3, 224, 224)))
					self.assertIsNotNone(UpperCAmelCase__)












'''simple docstring'''




import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
		from PIL import Image

		from transformers import CLIPImageProcessor, CLIPProcessor







@require_vision
class       __lowercase					(unittest.TestCase    ):

	def      __UpperCamelCase							(      self   :						List[Any]):
			UpperCamelCase__				:					int					=					tempfile.mkdtemp()

			# fmt: off
			UpperCamelCase__				:					Union[str, Any]					=					['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
			# fmt: on
			UpperCamelCase__				:					Dict					=					dict(zip(UpperCAmelCase_  ,					range(len(UpperCAmelCase_))))
			UpperCamelCase__				:					Optional[Any]					=					['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
			UpperCamelCase__				:					Union[str, Any]					=					{'unk_token': '<unk>'}

			UpperCamelCase__				:					Union[str, Any]					=					os.path.join(self.tmpdirname  ,					VOCAB_FILES_NAMES['vocab_file'])
			UpperCamelCase__				:					Optional[Any]					=					os.path.join(self.tmpdirname  ,					VOCAB_FILES_NAMES['merges_file'])
			with open(self.vocab_file  ,					'w'  ,					encoding='utf-8') as fp:
					fp.write(json.dumps(UpperCAmelCase_) + '\n')
			with open(self.merges_file  ,					'w'  ,					encoding='utf-8') as fp:
					fp.write('\n'.join(UpperCAmelCase_))

			UpperCamelCase__				:					Dict					=					{
			    'do_resize': True,
			    'size': 20,
			    'do_center_crop': True,
			    'crop_size': 18,
			    'do_normalize': True,
			    'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],
			    'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],
			}
			UpperCamelCase__				:					Any					=					os.path.join(self.tmpdirname  ,					UpperCAmelCase_)
			with open(self.image_processor_file  ,					'w'  ,					encoding='utf-8') as fp:
					json.dump(UpperCAmelCase_  ,					UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Dict  ,					**UpperCAmelCase_   :						Union[str, Any]):
			return CLIPTokenizer.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Optional[int]  ,					**UpperCAmelCase_   :						str):
			return CLIPTokenizerFast.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						Optional[Any]  ,					**UpperCAmelCase_   :						Union[str, Any]):
			return CLIPImageProcessor.from_pretrained(self.tmpdirname  ,					**UpperCAmelCase_)

	def      __UpperCamelCase							(      self   :						str):
			shutil.rmtree(self.tmpdirname)

	def      __UpperCamelCase							(      self   :						Tuple):
			UpperCamelCase__				:					List[str]					=					[np.random.randint(255  ,					size=(3, 30, 400)  ,					dtype=np.uinta)]

			UpperCamelCase__				:					List[str]					=					[Image.fromarray(np.moveaxis(UpperCAmelCase_  ,					0  ,					-1)) for x in image_inputs]

			return image_inputs

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Union[str, Any]					=					self.get_tokenizer()
			UpperCamelCase__				:					Optional[Any]					=					self.get_rust_tokenizer()
			UpperCamelCase__				:					Any					=					self.get_image_processor()

			UpperCamelCase__				:					str					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)
			processor_slow.save_pretrained(self.tmpdirname)
			UpperCamelCase__				:					Any					=					CLIPProcessor.from_pretrained(self.tmpdirname  ,					use_fast=UpperCAmelCase_)

			UpperCamelCase__				:					str					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)
			processor_fast.save_pretrained(self.tmpdirname)
			UpperCamelCase__				:					Optional[int]					=					CLIPProcessor.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  ,					UpperCAmelCase_)
			self.assertIsInstance(processor_fast.tokenizer  ,					UpperCAmelCase_)

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

	def      __UpperCamelCase							(      self   :						List[str]):
			UpperCamelCase__				:					Union[str, Any]					=					CLIPProcessor(tokenizer=self.get_tokenizer()  ,					image_processor=self.get_image_processor())
			processor.save_pretrained(self.tmpdirname)

			UpperCamelCase__				:					List[str]					=					self.get_tokenizer(bos_token='(BOS)'  ,					eos_token='(EOS)')
			UpperCamelCase__				:					Tuple					=					self.get_image_processor(do_normalize=UpperCAmelCase_  ,					padding_value=1.0)

			UpperCamelCase__				:					Dict					=					CLIPProcessor.from_pretrained(
			    self.tmpdirname  ,					bos_token='(BOS)'  ,					eos_token='(EOS)'  ,					do_normalize=UpperCAmelCase_  ,					padding_value=1.0)

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

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

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Optional[Any]					=					self.get_image_processor()
			UpperCamelCase__				:					int					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					int					=					self.prepare_image_inputs()

			UpperCamelCase__				:					int					=					image_processor(UpperCAmelCase_  ,					return_tensors='np')
			UpperCamelCase__				:					Optional[int]					=					processor(images=UpperCAmelCase_  ,					return_tensors='np')

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

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Optional[Any]					=					self.get_image_processor()
			UpperCamelCase__				:					Dict					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Any					=					'lower newer'

			UpperCamelCase__				:					Union[str, Any]					=					processor(text=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					tokenizer(UpperCAmelCase_)

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

	def      __UpperCamelCase							(      self   :						int):
			UpperCamelCase__				:					Optional[int]					=					self.get_image_processor()
			UpperCamelCase__				:					List[str]					=					self.get_tokenizer()

			UpperCamelCase__				:					List[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					'lower newer'
			UpperCamelCase__				:					List[Any]					=					self.prepare_image_inputs()

			UpperCamelCase__				:					str					=					processor(text=UpperCAmelCase_  ,					images=UpperCAmelCase_)

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

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

	def      __UpperCamelCase							(      self   :						Dict):
			UpperCamelCase__				:					Any					=					self.get_image_processor()
			UpperCamelCase__				:					Dict					=					self.get_tokenizer()

			UpperCamelCase__				:					Optional[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					Optional[Any]					=					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

			UpperCamelCase__				:					List[Any]					=					processor.batch_decode(UpperCAmelCase_)
			UpperCamelCase__				:					Optional[int]					=					tokenizer.batch_decode(UpperCAmelCase_)

			self.assertListEqual(UpperCAmelCase_  ,					UpperCAmelCase_)





	def      __UpperCamelCase							(      self   :						str):
			UpperCamelCase__				:					Union[str, Any]					=					self.get_image_processor()
			UpperCamelCase__				:					List[str]					=					self.get_tokenizer()

			UpperCamelCase__				:					Optional[Any]					=					CLIPProcessor(tokenizer=UpperCAmelCase_  ,					image_processor=UpperCAmelCase_)

			UpperCamelCase__				:					List[Any]					=					'lower newer'
			UpperCamelCase__				:					Optional[int]					=					self.prepare_image_inputs()

			UpperCamelCase__				:					List[str]					=					processor(text=UpperCAmelCase_  ,					images=UpperCAmelCase_)

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




