




'''simple docstring'''




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   lowerCAmelCase_      (       unittest.TestCase      ):







  '''simple docstring'''







  def __init__(  self			:		Tuple  ,						_UpperCAmelCase			:		Union[str, Any]  ,						_UpperCAmelCase			:		List[Any]=7  ,						_UpperCAmelCase			:		List[str]=3  ,						_UpperCAmelCase			:		Tuple=18  ,						_UpperCAmelCase			:		int=30  ,						_UpperCAmelCase			:		Any=4_00  ,						_UpperCAmelCase			:		Any=None  ,						_UpperCAmelCase			:		str=True  ,						_UpperCAmelCase			:		str=True  ,						_UpperCAmelCase			:		Optional[Any]=None  ,						):






   """simple docstring"""






   UpperCAmelCase__								=			size if size is not None else {"""height""": 20, """width""": 20}
   UpperCAmelCase__								=			parent
   UpperCAmelCase__								=			batch_size
   UpperCAmelCase__								=			num_channels
   UpperCAmelCase__								=			image_size
   UpperCAmelCase__								=			min_resolution
   UpperCAmelCase__								=			max_resolution
   UpperCAmelCase__								=			size
   UpperCAmelCase__								=			do_normalize
   UpperCAmelCase__								=			do_convert_rgb
   UpperCAmelCase__								=			[5_12, 10_24, 20_48, 40_96]
   UpperCAmelCase__								=			patch_size if patch_size is not None else {"""height""": 16, """width""": 16}


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






   """simple docstring"""






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



  def 							SCREAMING_SNAKE_CASE__	(  self			:		int       ):






   """simple docstring"""






   UpperCAmelCase__								=			"""https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
   UpperCAmelCase__								=			Image.open(requests.get(SCREAMING_SNAKE_CASE__  ,						stream=SCREAMING_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   lowerCAmelCase_      (       __lowercase	,     unittest.TestCase      ):







  '''simple docstring'''







  lowerCAmelCase_ :    Dict    =  PixaStructImageProcessor if is_vision_available() else None


  def 							SCREAMING_SNAKE_CASE__	(  self			:		Optional[Any]       ):






   """simple docstring"""






   UpperCAmelCase__								=			PixaStructImageProcessingTester(self       )


  @property
  def 							SCREAMING_SNAKE_CASE__	(  self			:		Optional[int]       ):






   """simple docstring"""






   return self.image_processor_tester.prepare_image_processor_dict()


  def 							SCREAMING_SNAKE_CASE__	(  self			:		Tuple       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__  ,						"""do_normalize"""       )       )
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__  ,						"""do_convert_rgb"""       )       )


  def 							SCREAMING_SNAKE_CASE__	(  self			:		int       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processor_tester.prepare_dummy_image()

   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   UpperCAmelCase__								=			20_48

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


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






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   # create random PIL images
   UpperCAmelCase__								=			prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE__       )
   for image in image_inputs:
    self.assertIsInstance(SCREAMING_SNAKE_CASE__  ,						Image.Image       )

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

    # Test batched
    UpperCAmelCase__								=			image_processor(
        SCREAMING_SNAKE_CASE__  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_SNAKE_CASE__       ).flattened_patches
    self.assertEqual(
        encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)


  def 							SCREAMING_SNAKE_CASE__	(  self			:		Dict       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   # create random PIL images
   UpperCAmelCase__								=			prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE__       )
   for image in image_inputs:
    self.assertIsInstance(SCREAMING_SNAKE_CASE__  ,						Image.Image       )

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

   UpperCAmelCase__								=			True

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

    UpperCAmelCase__								=			"""Hello"""

    UpperCAmelCase__								=			image_processor(
        image_inputs[0]  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_SNAKE_CASE__  ,						header_text=SCREAMING_SNAKE_CASE__       ).flattened_patches
    self.assertEqual(
        encoded_images.shape  ,						(1, max_patch, expected_hidden_dim)  ,						)

    # Test batched
    UpperCAmelCase__								=			image_processor(
        SCREAMING_SNAKE_CASE__  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_SNAKE_CASE__  ,						header_text=SCREAMING_SNAKE_CASE__       ).flattened_patches
    self.assertEqual(
        encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)


  def 							SCREAMING_SNAKE_CASE__	(  self			:		List[str]       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   # create random numpy tensors
   UpperCAmelCase__								=			prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE__  ,						numpify=SCREAMING_SNAKE_CASE__       )
   for image in image_inputs:
    self.assertIsInstance(SCREAMING_SNAKE_CASE__  ,						np.ndarray       )

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

    # Test batched
    UpperCAmelCase__								=			image_processor(
        SCREAMING_SNAKE_CASE__  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_SNAKE_CASE__       ).flattened_patches
    self.assertEqual(
        encoded_images.shape  ,						(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)  ,						)



  def 							SCREAMING_SNAKE_CASE__	(  self			:		Tuple       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   # create random PyTorch tensors
   UpperCAmelCase__								=			prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE__  ,						torchify=SCREAMING_SNAKE_CASE__       )
   for image in image_inputs:
    self.assertIsInstance(SCREAMING_SNAKE_CASE__  ,						torch.Tensor       )

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

    # Test batched
    UpperCAmelCase__								=			image_processor(
        SCREAMING_SNAKE_CASE__  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_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   lowerCAmelCase_      (       __lowercase	,     unittest.TestCase      ):







  '''simple docstring'''







  lowerCAmelCase_ :    Any    =  PixaStructImageProcessor if is_vision_available() else None


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






   """simple docstring"""






   UpperCAmelCase__								=			PixaStructImageProcessingTester(self  ,						num_channels=4       )
   UpperCAmelCase__								=			3


  @property
  def 							SCREAMING_SNAKE_CASE__	(  self			:		List[Any]       ):






   """simple docstring"""






   return self.image_processor_tester.prepare_image_processor_dict()


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






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__  ,						"""do_normalize"""       )       )
   self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__  ,						"""do_convert_rgb"""       )       )



  def 							SCREAMING_SNAKE_CASE__	(  self			:		Optional[int]       ):






   """simple docstring"""






   UpperCAmelCase__								=			self.image_processing_class(**self.image_processor_dict       )
   # create random PIL images
   UpperCAmelCase__								=			prepare_image_inputs(self.image_processor_tester  ,						equal_resolution=SCREAMING_SNAKE_CASE__       )
   for image in image_inputs:
    self.assertIsInstance(SCREAMING_SNAKE_CASE__  ,						Image.Image       )

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

    # Test batched
    UpperCAmelCase__								=			image_processor(
        SCREAMING_SNAKE_CASE__  ,						return_tensors="""pt"""  ,						max_patches=SCREAMING_SNAKE_CASE__       ).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_tf_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE__   :			List[str]												=    {
    "configuration_blip": [
        "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlipConfig",
        "BlipTextConfig",
        "BlipVisionConfig",
    ],
    "processing_blip": ["BlipProcessor"],
}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			str												=    ["BlipImageProcessor"]


try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			int												=    [
					    "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "BlipModel",
					    "BlipPreTrainedModel",
					    "BlipForConditionalGeneration",
					    "BlipForQuestionAnswering",
					    "BlipVisionModel",
					    "BlipTextModel",
					    "BlipForImageTextRetrieval",
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			Any												=    [
					    "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "TFBlipModel",
					    "TFBlipPreTrainedModel",
					    "TFBlipForConditionalGeneration",
					    "TFBlipForQuestionAnswering",
					    "TFBlipVisionModel",
					    "TFBlipTextModel",
					    "TFBlipForImageTextRetrieval",
					]

if TYPE_CHECKING:
					from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
					from .processing_blip import BlipProcessor

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .image_processing_blip import BlipImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_blip import (
										    BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    BlipForConditionalGeneration,
										    BlipForImageTextRetrieval,
										    BlipForQuestionAnswering,
										    BlipModel,
										    BlipPreTrainedModel,
										    BlipTextModel,
										    BlipVisionModel,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_blip import (
										    TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TFBlipForConditionalGeneration,
										    TFBlipForImageTextRetrieval,
										    TFBlipForQuestionAnswering,
										    TFBlipModel,
										    TFBlipPreTrainedModel,
										    TFBlipTextModel,
										    TFBlipVisionModel,
										)

else:
					import sys

					SCREAMING_SNAKE_CASE__   :			Tuple												=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



