




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__					:  Tuple      							=				False

if is_vision_available():
   from PIL import Image

   from transformers import PixaStructImageProcessor





class 			lowerCamelCase_				( unittest.TestCase   ):


 '''simple docstring'''







 def __init__(				self    :						Tuple							,							_lowerCAmelCase    :						Tuple							,							_lowerCAmelCase    :						Optional[Any]=7							,							_lowerCAmelCase    :						List[Any]=3							,							_lowerCAmelCase    :						Tuple=18							,							_lowerCAmelCase    :						str=30							,							_lowerCAmelCase    :						str=400							,							_lowerCAmelCase    :						Union[str, Any]=None							,							_lowerCAmelCase    :						int=True							,							_lowerCAmelCase    :						List[Any]=True							,							_lowerCAmelCase    :						Any=None							,							):
       SCREAMING_SNAKE_CASE_      		=     size if size is not None else {'height': 20, 'width': 20}
       SCREAMING_SNAKE_CASE_      		=     parent
       SCREAMING_SNAKE_CASE_      		=     batch_size
       SCREAMING_SNAKE_CASE_      		=     num_channels
       SCREAMING_SNAKE_CASE_      		=     image_size
       SCREAMING_SNAKE_CASE_      		=     min_resolution
       SCREAMING_SNAKE_CASE_      		=     max_resolution
       SCREAMING_SNAKE_CASE_      		=     size
       SCREAMING_SNAKE_CASE_      		=     do_normalize
       SCREAMING_SNAKE_CASE_      		=     do_convert_rgb
       SCREAMING_SNAKE_CASE_      		=     [512, 1_024, 2_048, 4_096]
       SCREAMING_SNAKE_CASE_      		=     patch_size if patch_size is not None else {'height': 16, 'width': 16}



 def  lowerCAmelCase_    (				self    :						List[str]		):
       return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




 def  lowerCAmelCase_    (				self    :						List[Any]		):
       SCREAMING_SNAKE_CASE_      		=     'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       SCREAMING_SNAKE_CASE_      		=     Image.open(requests.get(_lowerCAmelCase							,							stream=_lowerCAmelCase		).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   ):


 '''simple docstring'''







 lowercase_							       =       PixaStructImageProcessor if is_vision_available() else None



 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     PixaStructImageProcessingTester(self		)



 @property
 def  lowerCAmelCase_    (				self    :						int		):
       return self.image_processor_tester.prepare_image_processor_dict()



 def  lowerCAmelCase_    (				self    :						Any		):
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_lowerCAmelCase							,							'do_normalize'		)		)
       self.assertTrue(hasattr(_lowerCAmelCase							,							'do_convert_rgb'		)		)



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.image_processor_tester.prepare_dummy_image()

       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       SCREAMING_SNAKE_CASE_      		=     2_048

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



 def  lowerCAmelCase_    (				self    :						str		):
       # Initialize image_processor
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       SCREAMING_SNAKE_CASE_      		=     prepare_image_inputs(self.image_processor_tester							,							equal_resolution=_lowerCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_lowerCAmelCase							,							Image.Image		)

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

             # Test batched
             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 _lowerCAmelCase							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase		).flattened_patches
             self.assertEqual(
                 encoded_images.shape							,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,							)



 def  lowerCAmelCase_    (				self    :						int		):
       # Initialize image_processor
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       SCREAMING_SNAKE_CASE_      		=     prepare_image_inputs(self.image_processor_tester							,							equal_resolution=_lowerCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_lowerCAmelCase							,							Image.Image		)

       # Test not batched input
       SCREAMING_SNAKE_CASE_      		=     (
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       SCREAMING_SNAKE_CASE_      		=     True

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

             SCREAMING_SNAKE_CASE_      		=     'Hello'

             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 image_inputs[0]							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase							,							header_text=_lowerCAmelCase		).flattened_patches
             self.assertEqual(
                 encoded_images.shape							,							(1, max_patch, expected_hidden_dim)							,							)

             # Test batched
             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 _lowerCAmelCase							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase							,							header_text=_lowerCAmelCase		).flattened_patches
             self.assertEqual(
                 encoded_images.shape							,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,							)



 def  lowerCAmelCase_    (				self    :						str		):
       # Initialize image_processor
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       # create random numpy tensors
       SCREAMING_SNAKE_CASE_      		=     prepare_image_inputs(self.image_processor_tester							,							equal_resolution=_lowerCAmelCase							,							numpify=_lowerCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_lowerCAmelCase							,							np.ndarray		)

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

             # Test batched
             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 _lowerCAmelCase							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase		).flattened_patches
             self.assertEqual(
                 encoded_images.shape							,							(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)							,							)




 def  lowerCAmelCase_    (				self    :						str		):
       # Initialize image_processor
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       # create random PyTorch tensors
       SCREAMING_SNAKE_CASE_      		=     prepare_image_inputs(self.image_processor_tester							,							equal_resolution=_lowerCAmelCase							,							torchify=_lowerCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_lowerCAmelCase							,							torch.Tensor		)

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

             # Test batched
             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 _lowerCAmelCase							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase		).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   ):


 '''simple docstring'''







 lowercase_							       =       PixaStructImageProcessor if is_vision_available() else None



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       SCREAMING_SNAKE_CASE_      		=     PixaStructImageProcessingTester(self							,							num_channels=4		)
       SCREAMING_SNAKE_CASE_      		=     3



 @property
 def  lowerCAmelCase_    (				self    :						Any		):
       return self.image_processor_tester.prepare_image_processor_dict()



 def  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       self.assertTrue(hasattr(_lowerCAmelCase							,							'do_normalize'		)		)
       self.assertTrue(hasattr(_lowerCAmelCase							,							'do_convert_rgb'		)		)




 def  lowerCAmelCase_    (				self    :						List[str]		):
       # Initialize image_processor
       SCREAMING_SNAKE_CASE_      		=     self.image_processing_class(**self.image_processor_dict		)
       # create random PIL images
       SCREAMING_SNAKE_CASE_      		=     prepare_image_inputs(self.image_processor_tester							,							equal_resolution=_lowerCAmelCase		)
       for image in image_inputs:
             self.assertIsInstance(_lowerCAmelCase							,							Image.Image		)

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

             # Test batched
             SCREAMING_SNAKE_CASE_      		=     image_processor(
                 _lowerCAmelCase							,							return_tensors='pt'							,							max_patches=_lowerCAmelCase		).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_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


if is_sentencepiece_available():
   from ..ta.tokenization_ta import TaTokenizer
else:
   from ...utils.dummy_sentencepiece_objects import TaTokenizer

lowerCamelCase__					:  List[Any]      							=				TaTokenizer

if is_tokenizers_available():
   from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
   from ...utils.dummy_tokenizers_objects import TaTokenizerFast

lowerCamelCase__					:  Union[str, Any]      							=				TaTokenizerFast

lowerCamelCase__					:  Dict      							=				{'configuration_mt5': ['MT5Config', 'MT5OnnxConfig']}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase__					:  Tuple      							=				[
       'MT5EncoderModel',
       'MT5ForConditionalGeneration',
       'MT5ForQuestionAnswering',
       'MT5Model',
       'MT5PreTrainedModel',
       'MT5Stack',
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase__					:  Tuple      							=				['TFMT5EncoderModel', 'TFMT5ForConditionalGeneration', 'TFMT5Model']

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase__					:  Tuple      							=				['FlaxMT5EncoderModel', 'FlaxMT5ForConditionalGeneration', 'FlaxMT5Model']


if TYPE_CHECKING:
   from .configuration_mta import MTaConfig, MTaOnnxConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_mta import (
          MTaEncoderModel,
          MTaForConditionalGeneration,
          MTaForQuestionAnswering,
          MTaModel,
          MTaPreTrainedModel,
          MTaStack,
      )

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel

   try:
      if not is_flax_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel

else:
   import sys

   lowerCamelCase__					:  int      							=				_LazyModule(
       __name__,
       globals()['__file__'],
       _import_structure,
       extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast},
       module_spec=__spec__,
   )