

import unittest

import numpy as np

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

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
					from transformers.models.bert.modeling_flax_bert import (
					    FlaxBertForMaskedLM,
					    FlaxBertForMultipleChoice,
					    FlaxBertForNextSentencePrediction,
					    FlaxBertForPreTraining,
					    FlaxBertForQuestionAnswering,
					    FlaxBertForSequenceClassification,
					    FlaxBertForTokenClassification,
					    FlaxBertModel,
					)
class 		SCREAMING_SNAKE_CASE__       (		unittest.TestCase ):







						"""simple docstring"""




						def __init__(					self			,			__UpperCamelCase			,			__UpperCamelCase=13			,			__UpperCamelCase=7			,			__UpperCamelCase=True			,			__UpperCamelCase=True			,			__UpperCamelCase=True			,			__UpperCamelCase=True			,			__UpperCamelCase=99			,			__UpperCamelCase=32			,			__UpperCamelCase=5			,			__UpperCamelCase=4			,			__UpperCamelCase=37			,			__UpperCamelCase="gelu"			,			__UpperCamelCase=0.1			,			__UpperCamelCase=0.1			,			__UpperCamelCase=5_12			,			__UpperCamelCase=16			,			__UpperCamelCase=2			,			__UpperCamelCase=0.02			,			__UpperCamelCase=4			,			)				->						str:




									'''simple docstring'''


									__UpperCamelCase     :     int										=   parent
									__UpperCamelCase     :     List[Any]										=   batch_size
									__UpperCamelCase     :     Union[str, Any]										=   seq_length
									__UpperCamelCase     :     List[Any]										=   is_training
									__UpperCamelCase     :     str										=   use_attention_mask
									__UpperCamelCase     :     List[str]										=   use_token_type_ids
									__UpperCamelCase     :     Optional[Any]										=   use_labels
									__UpperCamelCase     :     List[str]										=   vocab_size
									__UpperCamelCase     :     List[Any]										=   hidden_size
									__UpperCamelCase     :     Any										=   num_hidden_layers
									__UpperCamelCase     :     Optional[int]										=   num_attention_heads
									__UpperCamelCase     :     Dict										=   intermediate_size
									__UpperCamelCase     :     List[Any]										=   hidden_act
									__UpperCamelCase     :     Union[str, Any]										=   hidden_dropout_prob
									__UpperCamelCase     :     List[str]										=   attention_probs_dropout_prob
									__UpperCamelCase     :     str										=   max_position_embeddings
									__UpperCamelCase     :     Union[str, Any]										=   type_vocab_size
									__UpperCamelCase     :     Union[str, Any]										=   type_sequence_label_size
									__UpperCamelCase     :     Dict										=   initializer_range
									__UpperCamelCase     :     List[Any]										=   num_choices

						def __lowerCamelCase       (					self     )				->						int:




									'''simple docstring'''


									__UpperCamelCase     :     int										=   ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size     )

									__UpperCamelCase     :     Dict										=   None
									if self.use_attention_mask:
												__UpperCamelCase     :     Tuple										=   random_attention_mask([self.batch_size, self.seq_length]     )

									__UpperCamelCase     :     Optional[int]										=   None
									if self.use_token_type_ids:
												__UpperCamelCase     :     Optional[int]										=   ids_tensor([self.batch_size, self.seq_length]			,			self.type_vocab_size     )

									__UpperCamelCase     :     Any										=   BertConfig(
									    vocab_size=self.vocab_size			,			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			,			max_position_embeddings=self.max_position_embeddings			,			type_vocab_size=self.type_vocab_size			,			is_decoder=__UpperCAmelCase			,			initializer_range=self.initializer_range			,			)

									return config, input_ids, token_type_ids, attention_mask

						def __lowerCamelCase       (					self     )				->						Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase     :     List[str]										=   self.prepare_config_and_inputs()
									__UpperCamelCase     :     int										=   config_and_inputs
									__UpperCamelCase     :     Optional[Any]										=   {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
									return config, inputs_dict




						def __lowerCamelCase       (					self     )				->						Optional[Any]:




									'''simple docstring'''


									__UpperCamelCase     :     Dict										=   self.prepare_config_and_inputs()
									__UpperCamelCase     :     int										=   config_and_inputs

									__UpperCamelCase     :     Optional[int]										=   True
									__UpperCamelCase     :     Optional[int]										=   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
									__UpperCamelCase     :     int										=   ids_tensor([self.batch_size, self.seq_length]			,			vocab_size=2     )

									return (
									    config,
									    input_ids,
									    attention_mask,
									    encoder_hidden_states,
									    encoder_attention_mask,
									)







@require_flax
class 		SCREAMING_SNAKE_CASE__       (		lowerCamelCase__    ,						unittest.TestCase ):







						"""simple docstring"""




						lowercase	:					int           =				True

						lowercase	:					List[Any]           =				(
						    (
						        FlaxBertModel,
						        FlaxBertForPreTraining,
						        FlaxBertForMaskedLM,
						        FlaxBertForMultipleChoice,
						        FlaxBertForQuestionAnswering,
						        FlaxBertForNextSentencePrediction,
						        FlaxBertForSequenceClassification,
						        FlaxBertForTokenClassification,
						        FlaxBertForQuestionAnswering,
						    )
						    if is_flax_available()
						    else ()
						)

						def __lowerCamelCase       (					self     )				->						List[str]:




									'''simple docstring'''


									__UpperCamelCase     :     Tuple										=   FlaxBertModelTester(self     )




						@slow
						def __lowerCamelCase       (					self     )				->						Any:




									'''simple docstring'''


									__UpperCamelCase     :     Tuple										=   FlaxBertModel.from_pretrained("bert-base-cased"     )
									__UpperCamelCase     :     str										=   model(np.ones((1, 1)     )     )
									self.assertIsNotNone(__UpperCAmelCase     )




import unittest

import numpy as np
import requests

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

						from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
						lowerCamelCase		       =      False

if is_vision_available():
						from PIL import Image

						from transformers import PixaStructImageProcessor


class 				_a						(       unittest.TestCase			):





							'''simple docstring'''

							def __init__(							self ,					__UpperCAmelCase ,					__UpperCAmelCase=7 ,					__UpperCAmelCase=3 ,					__UpperCAmelCase=18 ,					__UpperCAmelCase=30 ,					__UpperCAmelCase=400 ,					__UpperCAmelCase=None ,					__UpperCAmelCase=True ,					__UpperCAmelCase=True ,					__UpperCAmelCase=None ,					):







											"""simple docstring"""



											a__	:							str      						= size if size is not None else {"height": 20, "width": 20}
											a__	:							Optional[int]      						= parent
											a__	:							Union[str, Any]      						= batch_size
											a__	:							List[Any]      						= num_channels
											a__	:							Union[str, Any]      						= image_size
											a__	:							List[str]      						= min_resolution
											a__	:							int      						= max_resolution
											a__	:							int      						= size
											a__	:							List[str]      						= do_normalize
											a__	:							Any      						= do_convert_rgb
											a__	:							Optional[Any]      						= [512, 1024, 2048, 4096]
											a__	:							Any      						= patch_size if patch_size is not None else {"height": 16, "width": 16}



							def 		_A	(							self				):







											"""simple docstring"""



											return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							str      						= "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
											a__	:							Union[str, Any]      						= Image.open(requests.get(__UpperCAmelCase ,					stream=__UpperCAmelCase				).raw				).convert("RGB"				)
											return raw_image





@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11       ,  reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."       ,  )
@require_torch
@require_vision
class 				_a						(       SCREAMING_SNAKE_CASE       ,  unittest.TestCase			):





							'''simple docstring'''

							A				:List[str] =       PixaStructImageProcessor if is_vision_available() else None



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Any      						= PixaStructImageProcessingTester(self				)



							@property
							def 		_A	(							self				):







											"""simple docstring"""



											return self.image_processor_tester.prepare_image_processor_dict()



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Union[str, Any]      						= self.image_processing_class(**self.image_processor_dict				)
											self.assertTrue(hasattr(__UpperCAmelCase ,					"do_normalize"				)				)
											self.assertTrue(hasattr(__UpperCAmelCase ,					"do_convert_rgb"				)				)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Tuple      						= self.image_processor_tester.prepare_dummy_image()

											a__	:							Any      						= self.image_processing_class(**self.image_processor_dict				)
											a__	:							List[str]      						= 2048

											a__	:							Union[str, Any]      						= image_processor(__UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				)
											self.assertTrue(torch.allclose(inputs.flattened_patches.mean() ,					torch.tensor(0.0_6_0_6				) ,					atol=1E-3 ,					rtol=1E-3				)				)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							int      						= self.image_processing_class(**self.image_processor_dict				)
											# create random PIL images
											a__	:							str      						= prepare_image_inputs(self.image_processor_tester ,					equal_resolution=__UpperCAmelCase				)
											for image in image_inputs:
															self.assertIsInstance(__UpperCAmelCase ,					Image.Image				)

											# Test not batched input
											a__	:							List[Any]      						= (
											    (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
											    * self.image_processor_tester.num_channels
											) + 2

											for max_patch in self.image_processor_tester.max_patches:
															# Test not batched input
															a__	:							Optional[Any]      						= image_processor(
															    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(1, max_patch, expected_hidden_dim) ,					)

															# Test batched
															a__	:							Optional[Any]      						= image_processor(
															    __UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) ,					)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Union[str, Any]      						= self.image_processing_class(**self.image_processor_dict				)
											# create random PIL images
											a__	:							Any      						= prepare_image_inputs(self.image_processor_tester ,					equal_resolution=__UpperCAmelCase				)
											for image in image_inputs:
															self.assertIsInstance(__UpperCAmelCase ,					Image.Image				)

											# Test not batched input
											a__	:							Optional[int]      						= (
											    (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
											    * self.image_processor_tester.num_channels
											) + 2

											a__	:							int      						= True

											for max_patch in self.image_processor_tester.max_patches:
															# Test not batched input
															with self.assertRaises(__UpperCAmelCase				):
																			a__	:							List[str]      						= image_processor(
																			    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches

															a__	:							Tuple      						= "Hello"

															a__	:							Union[str, Any]      						= image_processor(
															    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase ,					header_text=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(1, max_patch, expected_hidden_dim) ,					)

															# Test batched
															a__	:							Optional[int]      						= image_processor(
															    __UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase ,					header_text=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) ,					)



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							str      						= self.image_processing_class(**self.image_processor_dict				)
											# create random numpy tensors
											a__	:							Tuple      						= prepare_image_inputs(self.image_processor_tester ,					equal_resolution=__UpperCAmelCase ,					numpify=__UpperCAmelCase				)
											for image in image_inputs:
															self.assertIsInstance(__UpperCAmelCase ,					np.ndarray				)

											a__	:							List[str]      						= (
											    (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
											    * self.image_processor_tester.num_channels
											) + 2

											for max_patch in self.image_processor_tester.max_patches:
															# Test not batched input
															a__	:							Any      						= image_processor(
															    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(1, max_patch, expected_hidden_dim) ,					)

															# Test batched
															a__	:							str      						= image_processor(
															    __UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) ,					)




							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							List[Any]      						= self.image_processing_class(**self.image_processor_dict				)
											# create random PyTorch tensors
											a__	:							Any      						= prepare_image_inputs(self.image_processor_tester ,					equal_resolution=__UpperCAmelCase ,					torchify=__UpperCAmelCase				)
											for image in image_inputs:
															self.assertIsInstance(__UpperCAmelCase ,					torch.Tensor				)

											# Test not batched input
											a__	:							Optional[Any]      						= (
											    (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
											    * self.image_processor_tester.num_channels
											) + 2

											for max_patch in self.image_processor_tester.max_patches:
															# Test not batched input
															a__	:							str      						= image_processor(
															    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(1, max_patch, expected_hidden_dim) ,					)

															# Test batched
															a__	:							Optional[int]      						= image_processor(
															    __UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) ,					)





@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11       ,  reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."       ,  )
@require_torch
@require_vision
class 				_a						(       SCREAMING_SNAKE_CASE       ,  unittest.TestCase			):





							'''simple docstring'''

							A				:List[str] =       PixaStructImageProcessor if is_vision_available() else None



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Dict      						= PixaStructImageProcessingTester(self ,					num_channels=4				)
											a__	:							Tuple      						= 3



							@property
							def 		_A	(							self				):







											"""simple docstring"""



											return self.image_processor_tester.prepare_image_processor_dict()



							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Optional[int]      						= self.image_processing_class(**self.image_processor_dict				)
											self.assertTrue(hasattr(__UpperCAmelCase ,					"do_normalize"				)				)
											self.assertTrue(hasattr(__UpperCAmelCase ,					"do_convert_rgb"				)				)




							def 		_A	(							self				):







											"""simple docstring"""



											a__	:							Dict      						= self.image_processing_class(**self.image_processor_dict				)
											# create random PIL images
											a__	:							Union[str, Any]      						= prepare_image_inputs(self.image_processor_tester ,					equal_resolution=__UpperCAmelCase				)
											for image in image_inputs:
															self.assertIsInstance(__UpperCAmelCase ,					Image.Image				)

											# Test not batched input
											a__	:							str      						= (
											    (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
											    * (self.image_processor_tester.num_channels - 1)
											) + 2

											for max_patch in self.image_processor_tester.max_patches:
															# Test not batched input
															a__	:							List[str]      						= image_processor(
															    image_inputs[0] ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(1, max_patch, expected_hidden_dim) ,					)

															# Test batched
															a__	:							int      						= image_processor(
															    __UpperCAmelCase ,					return_tensors="pt" ,					max_patches=__UpperCAmelCase				).flattened_patches
															self.assertEqual(
															    encoded_images.shape ,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) ,					)


