



"""simple docstring"""






import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
     from PIL import Image

     from transformers.image_utils import load_image
else:



     class     UpperCAmelCase    :



        @staticmethod
        def    __UpperCAmelCase    (       *__lowerCamelCase    :	List[str]							,       **__lowerCamelCase    :	Any				):



          """simple docstring"""
          pass




     def 			snake_case		(		lowerCAmelCase_	)						->				Dict:
       return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
snake_case   					=				(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)



@is_pipeline_test
@require_torch
@require_vision
class     UpperCAmelCase    (	unittest.TestCase  ):
   A__		:	Dict           =  MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING



   @require_pytesseract
   @require_vision
   def    __UpperCAmelCase    (       self    :	Tuple							,       __lowerCamelCase    :	Dict							,       __lowerCamelCase    :	List[Any]							,       __lowerCamelCase    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model=__lowerCamelCase							,       tokenizer=__lowerCamelCase							,       image_processor=__lowerCamelCase				)

     _snake_case   	=      INVOICE_URL
     _snake_case   	=      list(zip(*apply_tesseract(load_image(__lowerCamelCase				)							,       __lowerCamelCase							,       ''''''				)				)				)
     _snake_case   	=      '''What is the placebo?'''
     _snake_case   	=      [
         {
             '''image''': load_image(__lowerCamelCase				),
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
             '''word_boxes''': word_boxes,
         },
     ]
     return dqa_pipeline, examples



   def    __UpperCAmelCase    (       self    :	Union[str, Any]							,       __lowerCamelCase    :	Any							,       __lowerCamelCase    :	Optional[Any]				):



     """simple docstring"""
     _snake_case   	=      dqa_pipeline(__lowerCamelCase							,       top_k=2				)
     self.assertEqual(
         __lowerCamelCase							,       [
             [
                 {'''score''': ANY(__lowerCamelCase				), '''answer''': ANY(__lowerCamelCase				), '''start''': ANY(__lowerCamelCase				), '''end''': ANY(__lowerCamelCase				)},
                 {'''score''': ANY(__lowerCamelCase				), '''answer''': ANY(__lowerCamelCase				), '''start''': ANY(__lowerCamelCase				), '''end''': ANY(__lowerCamelCase				)},
             ]
         ]
         * 3							,       )



   @require_torch
   @require_detectrona
   @require_pytesseract
   def    __UpperCAmelCase    (       self    :	Union[str, Any]				):



     """simple docstring"""
     _snake_case   	=      pipeline('''document-question-answering'''							,       model='''hf-internal-testing/tiny-random-layoutlmv2'''				)
     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''How many cats are there?'''

     _snake_case   	=      [
         {'''score''': 0.0_0_0_1, '''answer''': '''oy 2312/2019''', '''start''': 3_8, '''end''': 3_9},
         {'''score''': 0.0_0_0_1, '''answer''': '''oy 2312/2019 DUE''', '''start''': 3_8, '''end''': 4_0},
     ]
     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(nested_simplify(__lowerCamelCase							,       decimals=4				)							,       __lowerCamelCase				)

     _snake_case   	=      dqa_pipeline({'''image''': image, '''question''': question}							,       top_k=2				)
     self.assertEqual(nested_simplify(__lowerCamelCase							,       decimals=4				)							,       __lowerCamelCase				)

     # This image does not detect ANY text in it, meaning layoutlmv2 should fail.
     # Empty answer probably
     _snake_case   	=      '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(__lowerCamelCase							,       []				)

     # We can optionnally pass directly the words and bounding boxes
     _snake_case   	=      '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
     _snake_case   	=      []
     _snake_case   	=      []
     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       words=__lowerCamelCase							,       boxes=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(__lowerCamelCase							,       []				)



   @slow
   @require_torch
   @require_detectrona
   @require_pytesseract
   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''							,       revision='''9977165'''							,       )
     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''What is the invoice number?'''

     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )

     _snake_case   	=      dqa_pipeline({'''image''': image, '''question''': question}							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )

     _snake_case   	=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             [
                 {'''score''': 0.9_9_4_4, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
                 {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             ],
         ]
         * 2							,       )



   @slow
   @require_torch
   @require_detectrona
   @require_pytesseract
   def    __UpperCAmelCase    (       self    :	str				):



     """simple docstring"""
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''							,       revision='''9977165'''							,       max_seq_len=5_0							,       )
     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''What is the invoice number?'''

     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
             {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )

     _snake_case   	=      dqa_pipeline({'''image''': image, '''question''': question}							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
             {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )

     _snake_case   	=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             [
                 {'''score''': 0.9_9_7_4, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
                 {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             ]
         ]
         * 2							,       )



   @slow
   @require_torch
   @require_pytesseract
   @require_vision
   def    __UpperCAmelCase    (       self    :	int				):



     """simple docstring"""
     _snake_case   	=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''							,       revision='''3dc6de3'''							,       add_prefix_space=__lowerCamelCase				)
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model='''impira/layoutlm-document-qa'''							,       tokenizer=__lowerCamelCase							,       revision='''3dc6de3'''							,       )
     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''What is the invoice number?'''

     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
         ]							,       )

     _snake_case   	=      dqa_pipeline({'''image''': image, '''question''': question}							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
         ]							,       )

     _snake_case   	=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             [
                 {'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
                 {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
             ]
         ]
         * 2							,       )

     _snake_case   	=      list(zip(*apply_tesseract(load_image(__lowerCamelCase				)							,       __lowerCamelCase							,       ''''''				)				)				)

     # This model should also work if `image` is set to None
     _snake_case   	=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.4_2_5_1, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
         ]							,       )



   @slow
   @require_torch
   @require_pytesseract
   @require_vision
   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''							,       revision='''3dc6de3'''							,       add_prefix_space=__lowerCamelCase				)
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model='''impira/layoutlm-document-qa'''							,       tokenizer=__lowerCamelCase							,       revision='''3dc6de3'''							,       max_seq_len=5_0							,       )
     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''What is the invoice number?'''

     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )

     _snake_case   	=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             [
                 {'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
                 {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             ]
         ]
         * 2							,       )

     _snake_case   	=      list(zip(*apply_tesseract(load_image(__lowerCamelCase				)							,       __lowerCamelCase							,       ''''''				)				)				)

     # This model should also work if `image` is set to None
     _snake_case   	=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}							,       top_k=2				)
     self.assertEqual(
         nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [
             {'''score''': 0.9_9_9_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
             {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
         ]							,       )



   @slow
   @require_torch
   def    __UpperCAmelCase    (       self    :	Union[str, Any]				):



     """simple docstring"""
     _snake_case   	=      pipeline(
         '''document-question-answering'''							,       model='''naver-clova-ix/donut-base-finetuned-docvqa'''							,       tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa'''				)							,       feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa'''							,       )

     _snake_case   	=      INVOICE_URL
     _snake_case   	=      '''What is the invoice number?'''
     _snake_case   	=      dqa_pipeline(image=__lowerCamelCase							,       question=__lowerCamelCase							,       top_k=2				)
     self.assertEqual(nested_simplify(__lowerCamelCase							,       decimals=4				)							,       [{'''answer''': '''us-001'''}]				)





   @require_tf
   @unittest.skip('''Document question answering not implemented in TF'''				)
   def    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     pass










import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







     @property
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		1
           lowerCamelCase             =		3
           lowerCamelCase             =		(32, 32)

           lowerCamelCase             =		floats_tensor((batch_size, num_channels) + sizes					,      rng=random.Random(0     )     ).to(__a     )
           return image







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		UNetaDConditionModel(
               block_out_channels=(32, 32, 64)					,      layers_per_block=2					,      sample_size=32					,      in_channels=7					,      out_channels=4					,      down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")					,      up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")					,      cross_attention_dim=32					,      attention_head_dim=8					,      use_linear_projection=__a					,      only_cross_attention=(True, True, False)					,      num_class_embeds=1_00					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		AutoencoderKL(
               block_out_channels=[32, 32, 64]					,      in_channels=3					,      out_channels=3					,      down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]					,      up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]					,      latent_channels=4					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		CLIPTextConfig(
               bos_token_id=0					,      eos_token_id=2					,      hidden_size=32					,      intermediate_size=37					,      layer_norm_eps=1E-05					,      num_attention_heads=4					,      num_hidden_layers=5					,      pad_token_id=1					,      vocab_size=10_00					,      hidden_act="gelu"					,      projection_dim=5_12					,      )
           return CLIPTextModel(__a     )







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )

           lowerCamelCase             =		output.images

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      return_dict=__a					,      )[0]

           lowerCamelCase             =		image[0, -3:, -3:, -1]
           lowerCamelCase             =		image_from_tuple[0, -3:, -3:, -1]

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)
           lowerCamelCase             =		np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]     )

           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     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		sd_pipe(
               2 * [prompt]					,      image=2 * [low_res_image]					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_images_per_prompt=2					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2







     @unittest.skipIf(torch_device != "cuda"					,      "This test requires a GPU"     )
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # put models in fp16, except vae as it overflows in fp16
           lowerCamelCase             =		unet.half()
           lowerCamelCase             =		text_encoder.half()

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_inference_steps=2					,      output_type="np"					,      ).images

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(__a     )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 1E-3







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat_fp16.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 5E-1







     def     _a   (self     ):






           '''simple docstring'''



           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing(1     )
           pipe.enable_sequential_cpu_offload()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      num_inference_steps=5					,      output_type="np"					,      )

           lowerCamelCase             =		torch.cuda.max_memory_allocated()
           # make sure that less than 2.9 GB is allocated
           assert mem_bytes < 2.9 * 10**9