



'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import LevitImageProcessor

class 				SCREAMING_SNAKE_CASE(							unittest.TestCase			):







	"""simple docstring"""






	def __init__(						self			:     int		,			__snake_case			:     int		,			__snake_case			:     Dict=7		,			__snake_case			:     List[str]=3		,			__snake_case			:     Any=18		,			__snake_case			:     Optional[int]=30		,			__snake_case			:     List[Any]=400		,			__snake_case			:     Any=True		,			__snake_case			:     Union[str, Any]=None		,			__snake_case			:     List[str]=True		,			__snake_case			:     Dict=None		,			__snake_case			:     Dict=True		,			__snake_case			:     Any=[0.5, 0.5, 0.5]		,			__snake_case			:     Tuple=[0.5, 0.5, 0.5]		,			)			->		Optional[int]:
								UpperCAmelCase :       List[str] 							=		size if size is not None else {'''shortest_edge''': 18}
								UpperCAmelCase :       Dict 							=		crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
								UpperCAmelCase :       Optional[int] 							=		parent
								UpperCAmelCase :       Union[str, Any] 							=		batch_size
								UpperCAmelCase :       int 							=		num_channels
								UpperCAmelCase :       Union[str, Any] 							=		image_size
								UpperCAmelCase :       Optional[Any] 							=		min_resolution
								UpperCAmelCase :       List[str] 							=		max_resolution
								UpperCAmelCase :       List[Any] 							=		do_resize
								UpperCAmelCase :       List[Any] 							=		size
								UpperCAmelCase :       Dict 							=		do_center_crop
								UpperCAmelCase :       Dict 							=		crop_size
								UpperCAmelCase :       Union[str, Any] 							=		do_normalize
								UpperCAmelCase :       int 							=		image_mean
								UpperCAmelCase :       Union[str, Any] 							=		image_std







	def      A	(						self			:     List[str]		)			->		Tuple:
								return {
								    "image_mean": self.image_mean,
								    "image_std": self.image_std,
								    "do_normalize": self.do_normalize,
								    "do_resize": self.do_resize,
								    "do_center_crop": self.do_center_crop,
								    "size": self.size,
								    "crop_size": self.crop_size,
								}

@require_torch
@require_vision
class 				SCREAMING_SNAKE_CASE(							A__							,		unittest.TestCase			):







	"""simple docstring"""






	lowerCamelCase__			 =       LevitImageProcessor if is_vision_available() else None







	def      A	(						self			:     Tuple		)			->		Any:
								UpperCAmelCase :       List[Any] 							=		LevitImageProcessingTester(self		)







	@property
	def      A	(						self			:     int		)			->		int:
								return self.image_processor_tester.prepare_image_processor_dict()







	def      A	(						self			:     Optional[Any]		)			->		Tuple:
								UpperCAmelCase :       int 							=		self.image_processing_class(**self.image_processor_dict		)
								self.assertTrue(hasattr(__snake_case		,			'''image_mean'''		)		)
								self.assertTrue(hasattr(__snake_case		,			'''image_std'''		)		)
								self.assertTrue(hasattr(__snake_case		,			'''do_normalize'''		)		)
								self.assertTrue(hasattr(__snake_case		,			'''do_resize'''		)		)
								self.assertTrue(hasattr(__snake_case		,			'''do_center_crop'''		)		)
								self.assertTrue(hasattr(__snake_case		,			'''size'''		)		)







	def      A	(						self			:     int		)			->		Any:
								UpperCAmelCase :       Dict 							=		self.image_processing_class.from_dict(self.image_processor_dict		)
								self.assertEqual(image_processor.size		,			{'''shortest_edge''': 18}		)
								self.assertEqual(image_processor.crop_size		,			{'''height''': 18, '''width''': 18}		)

								UpperCAmelCase :       List[str] 							=		self.image_processing_class.from_dict(self.image_processor_dict		,			size=42		,			crop_size=84		)
								self.assertEqual(image_processor.size		,			{'''shortest_edge''': 42}		)
								self.assertEqual(image_processor.crop_size		,			{'''height''': 84, '''width''': 84}		)







	def      A	(						self			:     Tuple		)			->		Dict:
								pass







	def      A	(						self			:     Optional[int]		)			->		Dict:
								# Initialize image_processing
								UpperCAmelCase :       Dict 							=		self.image_processing_class(**self.image_processor_dict		)
								# create random PIL images
								UpperCAmelCase :       List[Any] 							=		prepare_image_inputs(self.image_processor_tester		,			equal_resolution=__snake_case		)
								for image in image_inputs:
															self.assertIsInstance(__snake_case		,			Image.Image		)

								# Test not batched input
								UpperCAmelCase :       Tuple 							=		image_processing(image_inputs[0]		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)

								# Test batched
								UpperCAmelCase :       Any 							=		image_processing(__snake_case		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)







	def      A	(						self			:     Optional[Any]		)			->		Optional[int]:
								# Initialize image_processing
								UpperCAmelCase :       List[str] 							=		self.image_processing_class(**self.image_processor_dict		)
								# create random numpy tensors
								UpperCAmelCase :       Union[str, Any] 							=		prepare_image_inputs(self.image_processor_tester		,			equal_resolution=__snake_case		,			numpify=__snake_case		)
								for image in image_inputs:
															self.assertIsInstance(__snake_case		,			np.ndarray		)

								# Test not batched input
								UpperCAmelCase :       List[str] 							=		image_processing(image_inputs[0]		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)

								# Test batched
								UpperCAmelCase :       Tuple 							=		image_processing(__snake_case		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)







	def      A	(						self			:     Optional[int]		)			->		Dict:
								# Initialize image_processing
								UpperCAmelCase :       List[Any] 							=		self.image_processing_class(**self.image_processor_dict		)
								# create random PyTorch tensors
								UpperCAmelCase :       Optional[Any] 							=		prepare_image_inputs(self.image_processor_tester		,			equal_resolution=__snake_case		,			torchify=__snake_case		)
								for image in image_inputs:
															self.assertIsInstance(__snake_case		,			torch.Tensor		)

								# Test not batched input
								UpperCAmelCase :       Dict 							=		image_processing(image_inputs[0]		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        1,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)

								# Test batched
								UpperCAmelCase :       Dict 							=		image_processing(__snake_case		,			return_tensors='''pt'''		).pixel_values
								self.assertEqual(
								    encoded_images.shape		,			(
								        self.image_processor_tester.batch_size,
								        self.image_processor_tester.num_channels,
								        self.image_processor_tester.crop_size['''height'''],
								        self.image_processor_tester.crop_size['''width'''],
								    )		,			)










'''simple docstring'''






import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
						import os

						from flax.core.frozen_dict import unfreeze
						from flax.traverse_util import flatten_dict

						from transformers import FlaxBertModel

						UpperCamelCase__:   Tuple								=			"0.12"  # assumed parallelism: 8

@require_flax
@is_staging_test
class 				SCREAMING_SNAKE_CASE(							unittest.TestCase			):







	"""simple docstring"""






	@classmethod
	def      A	(						cls			:     Union[str, Any]		)			->		int:
								UpperCAmelCase :       Optional[Any] 							=		TOKEN
								HfFolder.save_token(__snake_case		)







	@classmethod
	def      A	(						cls			:     List[str]		)			->		Tuple:
								try:
															delete_repo(token=cls._token		,			repo_id='''test-model-flax'''		)
								except HTTPError:
															pass

								try:
															delete_repo(token=cls._token		,			repo_id='''valid_org/test-model-flax-org'''		)
								except HTTPError:
															pass







	def      A	(						self			:     int		)			->		Tuple:
								UpperCAmelCase :       List[Any] 							=		BertConfig(
								    vocab_size=99		,			hidden_size=32		,			num_hidden_layers=5		,			num_attention_heads=4		,			intermediate_size=37		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)
								model.push_to_hub('''test-model-flax'''		,			use_auth_token=self._token		)

								UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""		)

								UpperCAmelCase :       List[Any] 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       Tuple 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Union[str, Any] 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)

								# Reset repo
								delete_repo(token=self._token		,			repo_id='''test-model-flax'''		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(__snake_case		,			repo_id='''test-model-flax'''		,			push_to_hub=__snake_case		,			use_auth_token=self._token		)

								UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax"""		)

								UpperCAmelCase :       Any 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       str 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Optional[Any] 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)







	def      A	(						self			:     Optional[Any]		)			->		Union[str, Any]:
								UpperCAmelCase :       Dict 							=		BertConfig(
								    vocab_size=99		,			hidden_size=32		,			num_hidden_layers=5		,			num_attention_heads=4		,			intermediate_size=37		)
								UpperCAmelCase :       Optional[Any] 							=		FlaxBertModel(__snake_case		)
								model.push_to_hub('''valid_org/test-model-flax-org'''		,			use_auth_token=self._token		)

								UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''		)

								UpperCAmelCase :       List[Any] 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       int 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       Any 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)

								# Reset repo
								delete_repo(token=self._token		,			repo_id='''valid_org/test-model-flax-org'''		)

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(
															    __snake_case		,			repo_id='''valid_org/test-model-flax-org'''		,			push_to_hub=__snake_case		,			use_auth_token=self._token		)

								UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org'''		)

								UpperCAmelCase :       Any 							=		flatten_dict(unfreeze(model.params		)		)
								UpperCAmelCase :       Optional[Any] 							=		flatten_dict(unfreeze(new_model.params		)		)

								for key in base_params.keys():
															UpperCAmelCase :       int 							=		(base_params[key] - new_params[key]).sum().item()
															self.assertLessEqual(__snake_case		,			1E-3		,			msg=F"""{key} not identical"""		)


def  snake_case_     (					_lowerCAmelCase  :						Optional[Any]   ,      _lowerCAmelCase  :						Any  )      ->   Union[str, Any]:
							UpperCAmelCase :       str 							=		True
							UpperCAmelCase :       int 							=		flatten_dict(modela.params  )
							UpperCAmelCase :       Dict 							=		flatten_dict(modela.params  )
							for key in flat_params_a.keys():
														if np.sum(np.abs(flat_params_a[key] - flat_params_a[key]  )  ) > 1e-4:
																					UpperCAmelCase :       Dict 							=		False

							return models_are_equal




@require_flax
class 				SCREAMING_SNAKE_CASE(							unittest.TestCase			):







	"""simple docstring"""






	def      A	(						self			:     Tuple		)			->		Union[str, Any]:
								UpperCAmelCase :       List[Any] 							=		BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)

								UpperCAmelCase :       int 							=		'''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(os.path.join(__snake_case		,			__snake_case		)		)

															with self.assertRaises(__snake_case		):
																						UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(__snake_case		)

															UpperCAmelCase :       str 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertTrue(check_models_equal(__snake_case		,			__snake_case		)		)







	def      A	(						self			:     List[str]		)			->		Dict:
								UpperCAmelCase :       Dict 							=		BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''		)
								UpperCAmelCase :       Dict 							=		FlaxBertModel(__snake_case		)

								UpperCAmelCase :       Optional[int] 							=		'''bert'''
								with tempfile.TemporaryDirectory() as tmp_dir:
															model.save_pretrained(os.path.join(__snake_case		,			__snake_case		)		,			max_shard_size='''10KB'''		)

															with self.assertRaises(__snake_case		):
																						UpperCAmelCase :       Any 							=		FlaxBertModel.from_pretrained(__snake_case		)

															UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertTrue(check_models_equal(__snake_case		,			__snake_case		)		)







	def      A	(						self			:     Optional[int]		)			->		str:
								UpperCAmelCase :       Dict 							=		'''bert'''
								UpperCAmelCase :       int 							=		'''hf-internal-testing/tiny-random-bert-subfolder'''

								with self.assertRaises(__snake_case		):
															UpperCAmelCase :       Optional[Any] 							=		FlaxBertModel.from_pretrained(__snake_case		)

								UpperCAmelCase :       Tuple 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertIsNotNone(__snake_case		)







	def      A	(						self			:     Dict		)			->		List[Any]:
								UpperCAmelCase :       Optional[int] 							=		'''bert'''
								UpperCAmelCase :       int 							=		'''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
								with self.assertRaises(__snake_case		):
															UpperCAmelCase :       Dict 							=		FlaxBertModel.from_pretrained(__snake_case		)

								UpperCAmelCase :       Union[str, Any] 							=		FlaxBertModel.from_pretrained(__snake_case		,			subfolder=__snake_case		)

								self.assertIsNotNone(__snake_case		)





