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:
			A__           =							False

if is_vision_available():
			from PIL import Image

			from transformers import PixaStructImageProcessor
class   _lowerCAmelCase		(     unittest.TestCase				):







							def __init__(				self     :    Tuple	,					__snake_case     :    str	,					__snake_case     :    Dict=7	,					__snake_case     :    Tuple=3	,					__snake_case     :    Dict=18	,					__snake_case     :    Dict=30	,					__snake_case     :    Tuple=400	,					__snake_case     :    Optional[int]=None	,					__snake_case     :    List[Any]=True	,					__snake_case     :    int=True	,					__snake_case     :    Optional[int]=None	,					):
										lowerCamelCase						:Optional[int]						  =     size if size is not None else {'''height''': 20, '''width''': 20}
										lowerCamelCase						:Dict						  =     parent
										lowerCamelCase						:List[Any]						  =     batch_size
										lowerCamelCase						:Union[str, Any]						  =     num_channels
										lowerCamelCase						:str						  =     image_size
										lowerCamelCase						:Optional[Any]						  =     min_resolution
										lowerCamelCase						:int						  =     max_resolution
										lowerCamelCase						:Optional[int]						  =     size
										lowerCamelCase						:int						  =     do_normalize
										lowerCamelCase						:Optional[Any]						  =     do_convert_rgb
										lowerCamelCase						:Optional[int]						  =     [512, 1024, 2048, 4096]
										lowerCamelCase						:List[str]						  =     patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}







							def 				snake_case  (				self     :    Tuple		):
										return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:Tuple						  =     '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
										lowerCamelCase						:Optional[Any]						  =     Image.open(requests.get(__A	,					stream=__A		).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   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     PixaStructImageProcessor if is_vision_available() else None







							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase						:Optional[int]						  =     PixaStructImageProcessingTester(self		)







							@property
							def 				snake_case  (				self     :    List[Any]		):
										return self.image_processor_tester.prepare_image_processor_dict()







							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase						:Optional[Any]						  =     self.image_processing_class(**self.image_processor_dict		)
										self.assertTrue(hasattr(__A	,					'''do_normalize'''		)		)
										self.assertTrue(hasattr(__A	,					'''do_convert_rgb'''		)		)







							def 				snake_case  (				self     :    Any		):
										lowerCamelCase						:List[Any]						  =     self.image_processor_tester.prepare_dummy_image()

										lowerCamelCase						:Any						  =     self.image_processing_class(**self.image_processor_dict		)
										lowerCamelCase						:str						  =     2048

										lowerCamelCase						:Union[str, Any]						  =     image_processor(__A	,					return_tensors='''pt'''	,					max_patches=__A		)
										self.assertTrue(torch.allclose(inputs.flattened_patches.mean()	,					torch.tensor(0.0_6_0_6		)	,					atol=1e-3	,					rtol=1e-3		)		)







							def 				snake_case  (				self     :    Optional[int]		):
										# Initialize image_processor
										lowerCamelCase						:Optional[int]						  =     self.image_processing_class(**self.image_processor_dict		)
										# create random PIL images
										lowerCamelCase						:List[str]						  =     prepare_image_inputs(self.image_processor_tester	,					equal_resolution=__A		)
										for image in image_inputs:
													self.assertIsInstance(__A	,					Image.Image		)

										# Test not batched input
										lowerCamelCase						:Tuple						  =     (
										    (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
													lowerCamelCase						:Dict						  =     image_processor(
													    image_inputs[0]	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(1, max_patch, expected_hidden_dim)	,					)

													# Test batched
													lowerCamelCase						:Union[str, Any]						  =     image_processor(
													    __A	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,					)







							def 				snake_case  (				self     :    Any		):
										# Initialize image_processor
										lowerCamelCase						:Optional[Any]						  =     self.image_processing_class(**self.image_processor_dict		)
										# create random PIL images
										lowerCamelCase						:Optional[Any]						  =     prepare_image_inputs(self.image_processor_tester	,					equal_resolution=__A		)
										for image in image_inputs:
													self.assertIsInstance(__A	,					Image.Image		)

										# Test not batched input
										lowerCamelCase						:Union[str, Any]						  =     (
										    (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
										    * self.image_processor_tester.num_channels
										) + 2

										lowerCamelCase						:Union[str, Any]						  =     True

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

													lowerCamelCase						:int						  =     '''Hello'''

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

													# Test batched
													lowerCamelCase						:Optional[Any]						  =     image_processor(
													    __A	,					return_tensors='''pt'''	,					max_patches=__A	,					header_text=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,					)







							def 				snake_case  (				self     :    Optional[int]		):
										# Initialize image_processor
										lowerCamelCase						:Any						  =     self.image_processing_class(**self.image_processor_dict		)
										# create random numpy tensors
										lowerCamelCase						:Union[str, Any]						  =     prepare_image_inputs(self.image_processor_tester	,					equal_resolution=__A	,					numpify=__A		)
										for image in image_inputs:
													self.assertIsInstance(__A	,					np.ndarray		)

										lowerCamelCase						:Union[str, 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
													lowerCamelCase						:Any						  =     image_processor(
													    image_inputs[0]	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(1, max_patch, expected_hidden_dim)	,					)

													# Test batched
													lowerCamelCase						:Dict						  =     image_processor(
													    __A	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)	,					)







							def 				snake_case  (				self     :    Tuple		):
										# Initialize image_processor
										lowerCamelCase						:str						  =     self.image_processing_class(**self.image_processor_dict		)
										# create random PyTorch tensors
										lowerCamelCase						:Any						  =     prepare_image_inputs(self.image_processor_tester	,					equal_resolution=__A	,					torchify=__A		)
										for image in image_inputs:
													self.assertIsInstance(__A	,					torch.Tensor		)

										# Test not batched input
										lowerCamelCase						: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
													lowerCamelCase						:List[Any]						  =     image_processor(
													    image_inputs[0]	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(1, max_patch, expected_hidden_dim)	,					)

													# Test batched
													lowerCamelCase						:Optional[Any]						  =     image_processor(
													    __A	,					return_tensors='''pt'''	,					max_patches=__A		).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   _lowerCAmelCase		(     __SCREAMING_SNAKE_CASE      ,   unittest.TestCase				):
							_UpperCAmelCase						    =     PixaStructImageProcessor if is_vision_available() else None







							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase						:Tuple						  =     PixaStructImageProcessingTester(self	,					num_channels=4		)
										lowerCamelCase						:Any						  =     3







							@property
							def 				snake_case  (				self     :    List[Any]		):
										return self.image_processor_tester.prepare_image_processor_dict()







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:Any						  =     self.image_processing_class(**self.image_processor_dict		)
										self.assertTrue(hasattr(__A	,					'''do_normalize'''		)		)
										self.assertTrue(hasattr(__A	,					'''do_convert_rgb'''		)		)







							def 				snake_case  (				self     :    List[Any]		):
										# Initialize image_processor
										lowerCamelCase						:Union[str, Any]						  =     self.image_processing_class(**self.image_processor_dict		)
										# create random PIL images
										lowerCamelCase						:Dict						  =     prepare_image_inputs(self.image_processor_tester	,					equal_resolution=__A		)
										for image in image_inputs:
													self.assertIsInstance(__A	,					Image.Image		)

										# Test not batched input
										lowerCamelCase						:Optional[int]						  =     (
										    (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
													lowerCamelCase						:Any						  =     image_processor(
													    image_inputs[0]	,					return_tensors='''pt'''	,					max_patches=__A		).flattened_patches
													self.assertEqual(
													    encoded_images.shape	,					(1, max_patch, expected_hidden_dim)	,					)

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





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


A__           =							{
    """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""],
    """processing_layoutlmv2""": ["""LayoutLMv2Processor"""],
    """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""],
}

try:
			if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A__           =							["""LayoutLMv2TokenizerFast"""]

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A__           =							["""LayoutLMv2FeatureExtractor"""]
			A__           =							["""LayoutLMv2ImageProcessor"""]

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A__           =							[
			    """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""",
			    """LayoutLMv2ForQuestionAnswering""",
			    """LayoutLMv2ForSequenceClassification""",
			    """LayoutLMv2ForTokenClassification""",
			    """LayoutLMv2Layer""",
			    """LayoutLMv2Model""",
			    """LayoutLMv2PreTrainedModel""",
			]

if TYPE_CHECKING:
			from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
			from .processing_layoutlmva import LayoutLMvaProcessor
			from .tokenization_layoutlmva import LayoutLMvaTokenizer

			try:
						if not is_tokenizers_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_layoutlmva import (
						    LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
						    LayoutLMvaForQuestionAnswering,
						    LayoutLMvaForSequenceClassification,
						    LayoutLMvaForTokenClassification,
						    LayoutLMvaLayer,
						    LayoutLMvaModel,
						    LayoutLMvaPreTrainedModel,
						)
else:
			import sys

			A__           =							_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



