





import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      UpperCAmelCase__							=   ["""image_processor""", """tokenizer"""]
      UpperCAmelCase__							=   """LayoutLMv2ImageProcessor"""
      UpperCAmelCase__							=   ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""")


      def __init__(		self   ,				a__=None   ,				a__=None   ,				**a__):



             """simple docstring"""





             if "feature_extractor" in kwargs:
                    warnings.warn(
                        '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                        ''' instead.'''   ,				a__   ,				)
                    _lowerCamelCase				:  Optional[Any]						=		kwargs.pop('''feature_extractor''')

             _lowerCamelCase				:  Optional[int]						=		image_processor if image_processor is not None else feature_extractor
             if image_processor is None:
                    raise ValueError('''You need to specify an `image_processor`.''')
             if tokenizer is None:
                    raise ValueError('''You need to specify a `tokenizer`.''')

             super().__init__(a__   ,				a__)


      def __call__(		self   ,				a__   ,				a__ = None   ,				a__ = None   ,				a__ = None   ,				a__ = None   ,				a__ = True   ,				a__ = False   ,				a__ = None   ,				a__ = None   ,				a__ = 0   ,				a__ = None   ,				a__ = None   ,				a__ = None   ,				a__ = False   ,				a__ = False   ,				a__ = False   ,				a__ = False   ,				a__ = True   ,				a__ = None   ,				**a__   ,				):



             """simple docstring"""





             if self.image_processor.apply_ocr and (boxes is not None):
                    raise ValueError(
                        '''You cannot provide bounding boxes '''
                        '''if you initialized the image processor with apply_ocr set to True.''')

             if self.image_processor.apply_ocr and (word_labels is not None):
                    raise ValueError(
                        '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''')

             if return_overflowing_tokens is True and return_offsets_mapping is False:
                    raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''')

             # first, apply the image processor
             _lowerCamelCase				:  Any						=		self.image_processor(images=a__   ,				return_tensors=a__)

             # second, apply the tokenizer
             if text is not None and self.image_processor.apply_ocr and text_pair is None:
                    if isinstance(a__   ,				a__):
                           _lowerCamelCase				:  Tuple						=		[text]  # add batch dimension (as the image processor always adds a batch dimension)
                    _lowerCamelCase				:  Tuple						=		features['''words''']

             _lowerCamelCase				:  Union[str, Any]						=		self.tokenizer(
                 text=text if text is not None else features['''words''']   ,				text_pair=text_pair if text_pair is not None else None   ,				boxes=boxes if boxes is not None else features['''boxes''']   ,				word_labels=a__   ,				add_special_tokens=a__   ,				padding=a__   ,				truncation=a__   ,				max_length=a__   ,				stride=a__   ,				pad_to_multiple_of=a__   ,				return_token_type_ids=a__   ,				return_attention_mask=a__   ,				return_overflowing_tokens=a__   ,				return_special_tokens_mask=a__   ,				return_offsets_mapping=a__   ,				return_length=a__   ,				verbose=a__   ,				return_tensors=a__   ,				**a__   ,				)

             # add pixel values
             _lowerCamelCase				:  int						=		features.pop('''pixel_values''')
             if return_overflowing_tokens is True:
                    _lowerCamelCase				:  Tuple						=		self.get_overflowing_images(a__   ,				encoded_inputs['''overflow_to_sample_mapping'''])
             _lowerCamelCase				:  Union[str, Any]						=		images

             return encoded_inputs


      def 					__snake_case      (		self   ,				a__   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  Tuple						=		[]
             for sample_idx in overflow_to_sample_mapping:
                    images_with_overflow.append(images[sample_idx])

             if len(a__) != len(a__):
                    raise ValueError(
                        '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'''
                        F""" {len(a__)} and {len(a__)}""")

             return images_with_overflow


      def 					__snake_case      (		self   ,				*a__   ,				**a__):



             """simple docstring"""





             return self.tokenizer.batch_decode(*a__   ,				**a__)


      def 					__snake_case      (		self   ,				*a__   ,				**a__):



             """simple docstring"""





             return self.tokenizer.decode(*a__   ,				**a__)


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return ["input_ids", "bbox", "attention_mask", "image"]


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             warnings.warn(
                 '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''   ,				a__   ,				)
             return self.image_processor_class



      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             warnings.warn(
                 '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''   ,				a__   ,				)
             return self.image_processor








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   ,				a__   ,				a__=7   ,				a__=3   ,				a__=18   ,				a__=30   ,				a__=400   ,				a__=None   ,				a__=True   ,				a__=True   ,				a__=None   ,				):



             """simple docstring"""





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


      def 					__snake_case      (		self):



             """simple docstring"""





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



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
             _lowerCamelCase				:  Union[str, 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       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		PixaStructImageProcessingTester(self)


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		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):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.image_processor_tester.prepare_dummy_image()

             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             _lowerCamelCase				:  Optional[int]						=		2048

             _lowerCamelCase				:  Any						=		image_processor(a__   ,				return_tensors='''pt'''   ,				max_patches=a__)
             self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,				torch.tensor(0.0606)   ,				atol=1e-3   ,				rtol=1e-3))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  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				:  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
                    _lowerCamelCase				:  Optional[int]						=		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):



             """simple docstring"""





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

             _lowerCamelCase				:  Dict						=		True

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

                    _lowerCamelCase				:  List[Any]						=		'''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				:  Dict						=		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):



             """simple docstring"""





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

             _lowerCamelCase				:  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[str]						=		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				:  Tuple						=		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):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PyTorch tensors
             _lowerCamelCase				:  str						=		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				:  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				:  Optional[int]						=		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				:  List[str]						=		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       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





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


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		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):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  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				:  List[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
                    _lowerCamelCase				:  Union[str, 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				:  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)   ,				)

