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:
					__UpperCamelCase	: Union[str, Any]    		=  False

if is_vision_available():
					from PIL import Image

					from transformers import PixaStructImageProcessor





class       lowercase__		(     unittest.TestCase):


						def __init__( self			:       Optional[Any]					,	UpperCamelCase__			:       Any					,	UpperCamelCase__			:       Optional[Any]=7					,	UpperCamelCase__			:       Union[str, Any]=3					,	UpperCamelCase__			:       List[str]=18					,	UpperCamelCase__			:       List[str]=30					,	UpperCamelCase__			:       List[str]=400					,	UpperCamelCase__			:       Any=None					,	UpperCamelCase__			:       Optional[int]=True					,	UpperCamelCase__			:       Optional[int]=True					,	UpperCamelCase__			:       Optional[int]=None					,	):





												'''simple docstring'''





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


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





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



						def  __A ( self			:       Dict		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[str]           =							'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
												SCREAMING_SNAKE_CASE							:					List[Any]           =							Image.open(requests.get(snake_case_					,	stream=snake_case_		).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       lowercase__		(     _a			,							unittest.TestCase):
						UpperCamelCase_  =	PixaStructImageProcessor if is_vision_available() else None


						def  __A ( self			:       Dict		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[Any]           =							PixaStructImageProcessingTester(self		)


						@property
						def  __A ( self			:       int		):





												'''simple docstring'''





												return self.image_processor_tester.prepare_image_processor_dict()


						def  __A ( self			:       str		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							self.image_processing_class(**self.image_processor_dict		)
												self.assertTrue(hasattr(snake_case_					,	'''do_normalize'''		)		)
												self.assertTrue(hasattr(snake_case_					,	'''do_convert_rgb'''		)		)


						def  __A ( self			:       str		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Dict           =							self.image_processor_tester.prepare_dummy_image()

												SCREAMING_SNAKE_CASE							:					Any           =							self.image_processing_class(**self.image_processor_dict		)
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							2048

												SCREAMING_SNAKE_CASE							:					Tuple           =							image_processor(snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_		)
												self.assertTrue(torch.allclose(inputs.flattened_patches.mean()					,	torch.tensor(0.0606		)					,	atol=1E-3					,	rtol=1E-3		)		)


						def  __A ( self			:       Optional[int]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							self.image_processing_class(**self.image_processor_dict		)
												# create random PIL images
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							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
												SCREAMING_SNAKE_CASE							:					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
																		SCREAMING_SNAKE_CASE							:					Tuple           =							image_processor(
																		    image_inputs[0]					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(1, max_patch, expected_hidden_dim)					,	)

																		# Test batched
																		SCREAMING_SNAKE_CASE							:					str           =							image_processor(
																		    snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,	)


						def  __A ( self			:       str		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Tuple           =							self.image_processing_class(**self.image_processor_dict		)
												# create random PIL images
												SCREAMING_SNAKE_CASE							:					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
												SCREAMING_SNAKE_CASE							:					int           =							(
												    (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
												    * self.image_processor_tester.num_channels
												) + 2

												SCREAMING_SNAKE_CASE							:					Dict           =							True

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

																		SCREAMING_SNAKE_CASE							:					int           =							'''Hello'''

																		SCREAMING_SNAKE_CASE							:					str           =							image_processor(
																		    image_inputs[0]					,	return_tensors='''pt'''					,	max_patches=snake_case_					,	header_text=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(1, max_patch, expected_hidden_dim)					,	)

																		# Test batched
																		SCREAMING_SNAKE_CASE							:					str           =							image_processor(
																		    snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_					,	header_text=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,	)


						def  __A ( self			:       Dict		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[str]           =							self.image_processing_class(**self.image_processor_dict		)
												# create random numpy tensors
												SCREAMING_SNAKE_CASE							:					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		)

												SCREAMING_SNAKE_CASE							:					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
																		SCREAMING_SNAKE_CASE							:					Dict           =							image_processor(
																		    image_inputs[0]					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(1, max_patch, expected_hidden_dim)					,	)

																		# Test batched
																		SCREAMING_SNAKE_CASE							:					List[str]           =							image_processor(
																		    snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,	)



						def  __A ( self			:       List[str]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Any           =							self.image_processing_class(**self.image_processor_dict		)
												# create random PyTorch tensors
												SCREAMING_SNAKE_CASE							:					List[str]           =							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
												SCREAMING_SNAKE_CASE							:					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
																		SCREAMING_SNAKE_CASE							:					List[str]           =							image_processor(
																		    image_inputs[0]					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(1, max_patch, expected_hidden_dim)					,	)

																		# Test batched
																		SCREAMING_SNAKE_CASE							:					str           =							image_processor(
																		    snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_		).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       lowercase__		(     _a			,							unittest.TestCase):
						UpperCamelCase_  =	PixaStructImageProcessor if is_vision_available() else None


						def  __A ( self			:       Optional[Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							PixaStructImageProcessingTester(self					,	num_channels=4		)
												SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							3


						@property
						def  __A ( self			:       int		):





												'''simple docstring'''





												return self.image_processor_tester.prepare_image_processor_dict()


						def  __A ( self			:       Union[str, Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[str]           =							self.image_processing_class(**self.image_processor_dict		)
												self.assertTrue(hasattr(snake_case_					,	'''do_normalize'''		)		)
												self.assertTrue(hasattr(snake_case_					,	'''do_convert_rgb'''		)		)



						def  __A ( self			:       List[Any]		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Tuple           =							self.image_processing_class(**self.image_processor_dict		)
												# create random PIL images
												SCREAMING_SNAKE_CASE							:					int           =							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
												SCREAMING_SNAKE_CASE							:					Any           =							(
												    (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
																		SCREAMING_SNAKE_CASE							:					Any           =							image_processor(
																		    image_inputs[0]					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(1, max_patch, expected_hidden_dim)					,	)

																		# Test batched
																		SCREAMING_SNAKE_CASE							:					Any           =							image_processor(
																		    snake_case_					,	return_tensors='''pt'''					,	max_patches=snake_case_		).flattened_patches
																		self.assertEqual(
																		    encoded_images.shape					,	(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)					,	)






# Copyright 2021 The HuggingFace 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 argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


__UpperCamelCase	: Dict    		=  [
    'EAGER',
    'AOT_EAGER',
    'INDUCTOR',
    'NVFUSER',
    'AOT_NVFUSER',
    'AOT_CUDAGRAPHS',
    'OFI',
    'FX2TRT',
    'ONNXRT',
    'IPEX',
]
def    A			(					_lowercase	,						_lowercase=None	,						_lowercase=None	,						_lowercase=None		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							True
						while ask_again:
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							input(_lowercase		)
												try:
																		if default is not None and len(_lowercase		) == 0:
																								return default
																		return convert_value(_lowercase		) if convert_value is not None else result
												except Exception:
																		if error_message is not None:
																								print(_lowercase		)
def    A			(					_lowercase	,						_lowercase=[]	,						_lowercase=None	,						_lowercase=0		):
						SCREAMING_SNAKE_CASE							:					Dict           =							BulletMenu(_lowercase	,						_lowercase		)
						SCREAMING_SNAKE_CASE							:					str           =							menu.run(default_choice=_lowercase		)
						return convert_value(_lowercase		) if convert_value is not None else result
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Dict           =							int(_lowercase		)
						return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Any           =							int(_lowercase		)
						return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							int(_lowercase		)
						return DynamoBackend(DYNAMO_BACKENDS[value]		).value
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Union[str, Any]           =							int(_lowercase		)
						return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value]		)
def    A			(					_lowercase		):
						SCREAMING_SNAKE_CASE							:					Dict           =							int(_lowercase		)
						return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value]		)
def    A			(					_lowercase		):
						return {"yes": True, "no": False}[value.lower()]





class       lowercase__		(     argparse.RawDescriptionHelpFormatter):


						def  __A ( self			:       List[str]					,	UpperCamelCase__			:       List[str]					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       Dict					,	UpperCamelCase__			:       Dict		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							super()._format_usage(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Optional[Any]           =							usage.replace('''<command> [<args>] '''					,	''''''		)
												return usage





