

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

if is_vision_available():
  from PIL import Image

  from transformers import PixaStructImageProcessor





class A__    ( unittest.TestCase ):



 """simple docstring"""







 def __init__(		self :	str     ,						A_ :	Union[str, Any]     ,						A_ :	str=7     ,						A_ :	Union[str, Any]=3     ,						A_ :	List[Any]=1_8     ,						A_ :	int=3_0     ,						A_ :	Optional[Any]=4_0_0     ,						A_ :	Tuple=None     ,						A_ :	Optional[int]=True     ,						A_ :	Any=True     ,						A_ :	Any=None     ,						):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    size if size is not None else {"height": 2_0, "width": 2_0}
      _lowerCAmelCase   :					Any        =    parent
      _lowerCAmelCase   :					str        =    batch_size
      _lowerCAmelCase   :					Tuple        =    num_channels
      _lowerCAmelCase   :					str        =    image_size
      _lowerCAmelCase   :					Tuple        =    min_resolution
      _lowerCAmelCase   :					Any        =    max_resolution
      _lowerCAmelCase   :					Optional[Any]        =    size
      _lowerCAmelCase   :					List[Any]        =    do_normalize
      _lowerCAmelCase   :					Any        =    do_convert_rgb
      _lowerCAmelCase   :					List[str]        =    [5_1_2, 1_0_2_4, 2_0_4_8, 4_0_9_6]
      _lowerCAmelCase   :					Dict        =    patch_size if patch_size is not None else {"height": 1_6, "width": 1_6}

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




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


 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      _lowerCAmelCase   :					int        =    "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 A__    ( A  ,		unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					Tuple      =						PixaStructImageProcessor if is_vision_available() else None

 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    PixaStructImageProcessingTester(self       )

 @property
 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()

 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    self.image_processing_class(**self.image_processor_dict       )
      self.assertTrue(hasattr(A_     ,						"do_normalize"       )       )
      self.assertTrue(hasattr(A_     ,						"do_convert_rgb"       )       )

 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.image_processor_tester.prepare_dummy_image()

      _lowerCAmelCase   :					int        =    self.image_processing_class(**self.image_processor_dict       )
      _lowerCAmelCase   :					str        =    2_0_4_8

      _lowerCAmelCase   :					int        =    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    __magic_name__       (		self :	int       ):






      '''simple docstring'''




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

 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    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   :					List[Any]        =    (
          (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
          * self.image_processor_tester.num_channels
      ) + 2

      _lowerCAmelCase   :					Tuple        =    True

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

           _lowerCAmelCase   :					str        =    "Hello"

           _lowerCAmelCase   :					List[Any]        =    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   :					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    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    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   :					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   :					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    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    self.image_processing_class(**self.image_processor_dict       )
      # create random PyTorch tensors
      _lowerCAmelCase   :					Tuple        =    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   :					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__    ( A  ,		unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					Any      =						PixaStructImageProcessor if is_vision_available() else None

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Union[str, Any]        =    PixaStructImageProcessingTester(self     ,						num_channels=4       )
      _lowerCAmelCase   :					Dict        =    3

 @property
 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    self.image_processing_class(**self.image_processor_dict       )
      self.assertTrue(hasattr(A_     ,						"do_normalize"       )       )
      self.assertTrue(hasattr(A_     ,						"do_convert_rgb"       )       )


 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					int        =    self.image_processing_class(**self.image_processor_dict       )
      # create random PIL images
      _lowerCAmelCase   :					List[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   :					Tuple        =    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_tensorflow_text_available, is_torch_available


__UpperCAmelCase    				=     {
    'configuration_ernie': ['ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieConfig', 'ErnieOnnxConfig'],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __UpperCAmelCase    				=     [
      'ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST',
      'ErnieForCausalLM',
      'ErnieForMaskedLM',
      'ErnieForMultipleChoice',
      'ErnieForNextSentencePrediction',
      'ErnieForPreTraining',
      'ErnieForQuestionAnswering',
      'ErnieForSequenceClassification',
      'ErnieForTokenClassification',
      'ErnieModel',
      'ErniePreTrainedModel',
  ]

if TYPE_CHECKING:
  from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_ernie import (
        ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
        ErnieForCausalLM,
        ErnieForMaskedLM,
        ErnieForMultipleChoice,
        ErnieForNextSentencePrediction,
        ErnieForPreTraining,
        ErnieForQuestionAnswering,
        ErnieForSequenceClassification,
        ErnieForTokenClassification,
        ErnieModel,
        ErniePreTrainedModel,
    )

else:
  import sys

  __UpperCAmelCase    				=     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)






