import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu

class       snake_case					(      unittest.TestCase						):




  def 	__lowercase(      self     :	List[Any]				)->       Optional[int]:




       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




  @property
  def 	__lowercase(      self     :	Tuple				)->       List[str]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		1
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		3
       SCREAMING_SNAKE_CASE__				:				Dict			=		(32, 32)

       SCREAMING_SNAKE_CASE__				:				List[Any]			=		floats_tensor((batch_size, num_channels) + sizes     , rng=random.Random(0				)				).to(lowerCAmelCase__				)
       return image




  @property
  def 	__lowercase(      self     :	List[str]				)->       Any:




       """simple docstring"""
       torch.manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		UNetaDConditionModel(
           block_out_channels=(32, 64)     , layers_per_block=2     , sample_size=32     , in_channels=4     , out_channels=4     , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')     , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')     , cross_attention_dim=32     , )
       return model




  @property
  def 	__lowercase(      self     :	Union[str, Any]				)->       Tuple:




       """simple docstring"""
       torch.manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				int			=		AutoencoderKL(
           block_out_channels=[32, 64]     , in_channels=3     , out_channels=3     , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']     , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']     , latent_channels=4     , )
       return model




  @property
  def 	__lowercase(      self     :	Dict				)->       List[Any]:




       """simple docstring"""
       torch.manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				int			=		CLIPTextConfig(
           bos_token_id=0     , eos_token_id=2     , hidden_size=32     , intermediate_size=37     , layer_norm_eps=1e-0_5     , num_attention_heads=4     , num_hidden_layers=5     , pad_token_id=1     , vocab_size=1000     , )
       return CLIPTextModel(lowerCAmelCase__				)




  @property
  def 	__lowercase(      self     :	Optional[Any]				)->       Optional[int]:




       """simple docstring"""
       def extract(*a_     :	Any     , **a_     :	List[Any]				):

            class       snake_case					:




              def __init__(      self     :	List[Any]				)->       List[str]:




                   """simple docstring"""
                   SCREAMING_SNAKE_CASE__				:				Dict			=		torch.ones([0]				)




              def 	__lowercase(      self     :	Union[str, Any]     , a_     :	Optional[int]				)->       str:




                   """simple docstring"""
                   self.pixel_values.to(lowerCAmelCase__				)
                   return self




            return Out()

       return extract




  def 	__lowercase(      self     :	Any				)->       Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		'cpu'  # ensure determinism for the device-dependent torch.Generator
       SCREAMING_SNAKE_CASE__				:				str			=		self.dummy_cond_unet
       SCREAMING_SNAKE_CASE__				:				int			=		DDIMScheduler(
           beta_start=0.0_0085     , beta_end=0.012     , beta_schedule='scaled_linear'     , clip_sample=lowerCAmelCase__     , set_alpha_to_one=lowerCAmelCase__     , )

       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.dummy_vae
       SCREAMING_SNAKE_CASE__				:				str			=		self.dummy_text_encoder
       SCREAMING_SNAKE_CASE__				:				Any			=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE__				:				int			=		StableDiffusionPipeline(
           unet=lowerCAmelCase__     , scheduler=lowerCAmelCase__     , vae=lowerCAmelCase__     , text_encoder=lowerCAmelCase__     , tokenizer=lowerCAmelCase__     , safety_checker=lowerCAmelCase__     , feature_extractor=self.dummy_extractor     , )
       SCREAMING_SNAKE_CASE__				:				str			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				int			=		'A painting of a squirrel eating a burger'

       SCREAMING_SNAKE_CASE__				:				str			=		torch.Generator(device=lowerCAmelCase__				).manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		sd_pipe([prompt]     , generator=lowerCAmelCase__     , guidance_scale=6.0     , num_inference_steps=2     , output_type='np'				)
       SCREAMING_SNAKE_CASE__				:				int			=		output.images

       SCREAMING_SNAKE_CASE__				:				Dict			=		torch.Generator(device=lowerCAmelCase__				).manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=6.0     , num_inference_steps=2     , output_type='np'     , return_dict=lowerCAmelCase__     , )[0]

       SCREAMING_SNAKE_CASE__				:				str			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				Tuple			=		image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864]				)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1e-2




  def 	__lowercase(      self     :	List[str]				)->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		'cpu'  # ensure determinism for the device-dependent torch.Generator
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		self.dummy_cond_unet
       SCREAMING_SNAKE_CASE__				:				List[str]			=		PNDMScheduler(skip_prk_steps=lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.dummy_vae
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		self.dummy_text_encoder
       SCREAMING_SNAKE_CASE__				:				List[str]			=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		StableDiffusionPipeline(
           unet=lowerCAmelCase__     , scheduler=lowerCAmelCase__     , vae=lowerCAmelCase__     , text_encoder=lowerCAmelCase__     , tokenizer=lowerCAmelCase__     , safety_checker=lowerCAmelCase__     , feature_extractor=self.dummy_extractor     , )
       SCREAMING_SNAKE_CASE__				:				Tuple			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		'A painting of a squirrel eating a burger'
       SCREAMING_SNAKE_CASE__				:				str			=		torch.Generator(device=lowerCAmelCase__				).manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		sd_pipe([prompt]     , generator=lowerCAmelCase__     , guidance_scale=6.0     , num_inference_steps=2     , output_type='np'				)

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		output.images

       SCREAMING_SNAKE_CASE__				:				Any			=		torch.Generator(device=lowerCAmelCase__				).manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=6.0     , num_inference_steps=2     , output_type='np'     , return_dict=lowerCAmelCase__     , )[0]

       SCREAMING_SNAKE_CASE__				:				int			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				int			=		image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993]				)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2
       assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1e-2




  def 	__lowercase(      self     :	Optional[Any]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		StableDiffusionPipeline.from_pretrained(
           'hf-internal-testing/tiny-stable-diffusion-lms-pipe'     , safety_checker=lowerCAmelCase__				)
       assert isinstance(lowerCAmelCase__     , lowerCAmelCase__				)
       assert isinstance(pipe.scheduler     , lowerCAmelCase__				)
       assert pipe.safety_checker is None

       SCREAMING_SNAKE_CASE__				:				List[str]			=		pipe('example prompt'     , num_inference_steps=2				).images[0]
       assert image is not None

       # check that there's no error when saving a pipeline with one of the models being None
       with tempfile.TemporaryDirectory() as tmpdirname:
            pipe.save_pretrained(lowerCAmelCase__				)
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		StableDiffusionPipeline.from_pretrained(lowerCAmelCase__				)

       # sanity check that the pipeline still works
       assert pipe.safety_checker is None
       SCREAMING_SNAKE_CASE__				:				Tuple			=		pipe('example prompt'     , num_inference_steps=2				).images[0]
       assert image is not None




  @unittest.skipIf(torch_device != 'cuda'     , 'This test requires a GPU'				)
  def 	__lowercase(      self     :	List[str]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.dummy_cond_unet
       SCREAMING_SNAKE_CASE__				:				Any			=		PNDMScheduler(skip_prk_steps=lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.dummy_vae
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.dummy_text_encoder
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

       # put models in fp16
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		unet.half()
       SCREAMING_SNAKE_CASE__				:				int			=		vae.half()
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		bert.half()

       # make sure here that pndm scheduler skips prk
       SCREAMING_SNAKE_CASE__				:				List[str]			=		StableDiffusionPipeline(
           unet=lowerCAmelCase__     , scheduler=lowerCAmelCase__     , vae=lowerCAmelCase__     , text_encoder=lowerCAmelCase__     , tokenizer=lowerCAmelCase__     , safety_checker=lowerCAmelCase__     , feature_extractor=self.dummy_extractor     , )
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				str			=		'A painting of a squirrel eating a burger'
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		sd_pipe([prompt]     , num_inference_steps=2     , output_type='np'				).images

       assert image.shape == (1, 64, 64, 3)




@nightly
@require_torch_gpu
class       snake_case					(      unittest.TestCase						):




  def 	__lowercase(      self     :	int				)->       int:




       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




  def 	__lowercase(      self     :	str				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'     , safety_checker=lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				Tuple			=		(
           'portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle'
           ' coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with'
           ' anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and'
           ' children from bahnhof zoo, detailed '
       )
       SCREAMING_SNAKE_CASE__				:				str			=		40_0366_0346
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		7

       # without safety guidance (sld_guidance_scale = 0)
       SCREAMING_SNAKE_CASE__				:				Dict			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=0     , )

       SCREAMING_SNAKE_CASE__				:				Dict			=		output.images
       SCREAMING_SNAKE_CASE__				:				Tuple			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		[0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176]

       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2

       # without safety guidance (strong configuration)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=2000     , sld_warmup_steps=7     , sld_threshold=0.025     , sld_momentum_scale=0.5     , sld_mom_beta=0.7     , )

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		output.images
       SCREAMING_SNAKE_CASE__				:				Dict			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				int			=		[0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719]

       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2




  def 	__lowercase(      self     :	List[str]				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'     , safety_checker=lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				str			=		LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				str			=		'padme amidala taking a bath artwork, safe for work, no nudity'
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		27_3497_1755
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		7

       SCREAMING_SNAKE_CASE__				:				Dict			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=0     , )

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		output.images
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				str			=		[0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297]

       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=2000     , sld_warmup_steps=7     , sld_threshold=0.025     , sld_momentum_scale=0.5     , sld_mom_beta=0.7     , )

       SCREAMING_SNAKE_CASE__				:				Tuple			=		output.images
       SCREAMING_SNAKE_CASE__				:				List[str]			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				Dict			=		[0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443]

       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2




  def 	__lowercase(      self     :	Optional[Any]				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		StableDiffusionPipeline.from_pretrained('runwayml/stable-diffusion-v1-5'				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		sd_pipe.to(lowerCAmelCase__				)
       sd_pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

       SCREAMING_SNAKE_CASE__				:				int			=		(
           'the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.'
           ' leyendecker'
       )
       SCREAMING_SNAKE_CASE__				:				Any			=		10_4435_5234
       SCREAMING_SNAKE_CASE__				:				Any			=		12

       SCREAMING_SNAKE_CASE__				:				Any			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=0     , )

       SCREAMING_SNAKE_CASE__				:				int			=		output.images
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				int			=		np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]				)

       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-7

       SCREAMING_SNAKE_CASE__				:				int			=		torch.manual_seed(lowerCAmelCase__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		sd_pipe(
           [prompt]     , generator=lowerCAmelCase__     , guidance_scale=lowerCAmelCase__     , num_inference_steps=50     , output_type='np'     , width=512     , height=512     , sld_guidance_scale=2000     , sld_warmup_steps=7     , sld_threshold=0.025     , sld_momentum_scale=0.5     , sld_mom_beta=0.7     , )

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		output.images
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		image[0, -3:, -3:, -1]
       SCREAMING_SNAKE_CASE__				:				int			=		np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561]				)
       assert image.shape == (1, 512, 512, 3)

       assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2




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:
      SCREAMING_SNAKE_CASE__		:					Any						=					False

if is_vision_available():
      from PIL import Image

      from transformers import PixaStructImageProcessor

class       snake_case					(      unittest.TestCase						):




  def __init__(      self     :	List[Any]     , a_     :	Optional[int]     , a_     :	Dict=7     , a_     :	Any=3     , a_     :	Any=18     , a_     :	int=30     , a_     :	int=400     , a_     :	List[Any]=None     , a_     :	int=True     , a_     :	int=True     , a_     :	Dict=None     , )->       Optional[int]:




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




  def 	__lowercase(      self     :	Optional[Any]				)->       str:




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




  def 	__lowercase(      self     :	Dict				)->       Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
       SCREAMING_SNAKE_CASE__				:				str			=		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       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PixaStructImageProcessor if is_vision_available() else None




  def 	__lowercase(      self     :	List[str]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		PixaStructImageProcessingTester(self				)




  @property
  def 	__lowercase(      self     :	Dict				)->       Tuple:




       """simple docstring"""
       return self.image_processor_tester.prepare_image_processor_dict()




  def 	__lowercase(      self     :	Any				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.image_processing_class(**self.image_processor_dict				)
       self.assertTrue(hasattr(a_     , 'do_normalize'				)				)
       self.assertTrue(hasattr(a_     , 'do_convert_rgb'				)				)




  def 	__lowercase(      self     :	List[Any]				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		self.image_processor_tester.prepare_dummy_image()

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processing_class(**self.image_processor_dict				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		2048

       SCREAMING_SNAKE_CASE__				:				Optional[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 	__lowercase(      self     :	Any				)->       Tuple:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				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
       SCREAMING_SNAKE_CASE__				:				str			=		(
           (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__				:				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
            SCREAMING_SNAKE_CASE__				:				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 	__lowercase(      self     :	Any				)->       Any:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				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
       SCREAMING_SNAKE_CASE__				:				str			=		(
           (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
           * self.image_processor_tester.num_channels
       ) + 2

       SCREAMING_SNAKE_CASE__				:				int			=		True

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

            SCREAMING_SNAKE_CASE__				:				List[Any]			=		'Hello'

            SCREAMING_SNAKE_CASE__				:				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
            SCREAMING_SNAKE_CASE__				:				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 	__lowercase(      self     :	List[Any]				)->       Dict:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.image_processing_class(**self.image_processor_dict				)
       # create random numpy tensors
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_     , numpify=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , np.ndarray				)

       SCREAMING_SNAKE_CASE__				:				str			=		(
           (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__				:				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
            SCREAMING_SNAKE_CASE__				:				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)     , )




  def 	__lowercase(      self     :	str				)->       Optional[Any]:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				Any			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PyTorch tensors
       SCREAMING_SNAKE_CASE__				:				List[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
       SCREAMING_SNAKE_CASE__				:				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
            SCREAMING_SNAKE_CASE__				:				Optional[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
            SCREAMING_SNAKE_CASE__				:				List[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       snake_case					(      UpperCamelCase_   ,						unittest.TestCase						):
  lowercase_			=     PixaStructImageProcessor if is_vision_available() else None




  def 	__lowercase(      self     :	Union[str, Any]				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		PixaStructImageProcessingTester(self     , num_channels=4				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		3




  @property
  def 	__lowercase(      self     :	Any				)->       Any:




       """simple docstring"""
       return self.image_processor_tester.prepare_image_processor_dict()




  def 	__lowercase(      self     :	Dict				)->       Optional[int]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				int			=		self.image_processing_class(**self.image_processor_dict				)
       self.assertTrue(hasattr(a_     , 'do_normalize'				)				)
       self.assertTrue(hasattr(a_     , 'do_convert_rgb'				)				)




  def 	__lowercase(      self     :	str				)->       Union[str, Any]:




       """simple docstring"""
       # Initialize image_processor
       SCREAMING_SNAKE_CASE__				:				str			=		self.image_processing_class(**self.image_processor_dict				)
       # create random PIL images
       SCREAMING_SNAKE_CASE__				:				Tuple			=		prepare_image_inputs(self.image_processor_tester     , equal_resolution=a_				)
       for image in image_inputs:
            self.assertIsInstance(a_     , Image.Image				)

       # Test not batched input
       SCREAMING_SNAKE_CASE__				:				Dict			=		(
           (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__				:				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
            SCREAMING_SNAKE_CASE__				:				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)     , )



