



'''simple docstring'''





import math
from typing import Callable, List, Optional, Union

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

from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler




def lowerCAmelCase						(__A						,			__A						,			__A=[]):



     """simple docstring"""



     _a											=						size[0] - overlap_pixels * 2
     _a											=						size[1] - overlap_pixels * 2
     for letter in ["l", "r"]:
          if letter in remove_borders:
               size_x += overlap_pixels
     for letter in ["t", "b"]:
          if letter in remove_borders:
               size_y += overlap_pixels
     _a											=						np.ones((size_y, size_x)						,			dtype=np.uinta) * 255
     _a											=						np.pad(__A						,			mode='''linear_ramp'''						,			pad_width=__A						,			end_values=0)

     if "l" in remove_borders:
          _a											=						mask[:, overlap_pixels : mask.shape[1]]
     if "r" in remove_borders:
          _a											=						mask[:, 0 : mask.shape[1] - overlap_pixels]
     if "t" in remove_borders:
          _a											=						mask[overlap_pixels : mask.shape[0], :]
     if "b" in remove_borders:
          _a											=						mask[0 : mask.shape[0] - overlap_pixels, :]
     return mask




def lowerCAmelCase						(__A						,			__A						,			__A):



     """simple docstring"""



     return max(__A						,			min(__A						,			__A))




def lowerCAmelCase						(__A						,			__A						,			__A):



     """simple docstring"""



     return (
         clamp(rect[0]						,			min[0]						,			max[0]),
         clamp(rect[1]						,			min[1]						,			max[1]),
         clamp(rect[2]						,			min[0]						,			max[0]),
         clamp(rect[3]						,			min[1]						,			max[1]),
     )




def lowerCAmelCase						(__A						,			__A						,			__A):



     """simple docstring"""



     _a											=						list(__A)
     rect[0] -= overlap
     rect[1] -= overlap
     rect[2] += overlap
     rect[3] += overlap
     _a											=						clamp_rect(__A						,			[0, 0]						,			[image_size[0], image_size[1]])
     return rect




def lowerCAmelCase						(__A						,			__A						,			__A						,			__A):



     """simple docstring"""



     _a											=						Image.new('''RGB'''						,			(tile.size[0] + original_slice, tile.size[1]))
     result.paste(
         original_image.resize((tile.size[0], tile.size[1])						,			Image.BICUBIC).crop(
             (slice_x, 0, slice_x + original_slice, tile.size[1]))						,			(0, 0)						,			)
     result.paste(__A						,			(original_slice, 0))
     return result




def lowerCAmelCase						(__A						,			__A):



     """simple docstring"""



     _a											=						(original_image_slice * 4, 0, tile.size[0], tile.size[1])
     _a											=						tile.crop(__A)
     return tile




def lowerCAmelCase						(__A						,			__A):



     """simple docstring"""



     _a											=						n % d
     return n - divisor






class __A    (						A		):



 '''simple docstring'''







 def __init__(self				,     A				,     A				,     A				,     A				,     A				,     A				,     A = 350				,     )					->  List[Any]:


      """simple docstring"""



      super().__init__(
          vae=A				,     text_encoder=A				,     tokenizer=A				,     unet=A				,     low_res_scheduler=A				,     scheduler=A				,     max_noise_level=A				,     )



 def       a__						(self				,     A				,     A				,     A				,     A				,     A				,     A				,     A				,     **A )					->  Union[str, Any]:


      """simple docstring"""



      torch.manual_seed(0 )
      _a											=						(
          min(image.size[0] - (tile_size + original_image_slice)				,     x * tile_size ),
          min(image.size[1] - (tile_size + original_image_slice)				,     y * tile_size ),
          min(image.size[0]				,     (x + 1) * tile_size ),
          min(image.size[1]				,     (y + 1) * tile_size ),
      )
      _a											=						add_overlap_rect(A				,     A				,     image.size )
      _a											=						image.crop(A )
      _a											=						((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
      _a											=						translated_slice_x - (original_image_slice / 2)
      _a											=						max(0				,     A )
      _a											=						squeeze_tile(A				,     A				,     A				,     A )
      _a											=						to_input.size
      _a											=						to_input.resize((tile_size, tile_size)				,     Image.BICUBIC )
      _a											=						super(A				,     self ).__call__(image=A				,     **A ).images[0]
      _a											=						upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)				,     Image.BICUBIC )
      _a											=						unsqueeze_tile(A				,     A )
      _a											=						upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)				,     Image.BICUBIC )
      _a											=						[]
      if x == 0:
           remove_borders.append('''l''' )
      elif crop_rect[2] == image.size[0]:
           remove_borders.append('''r''' )
      if y == 0:
           remove_borders.append('''t''' )
      elif crop_rect[3] == image.size[1]:
           remove_borders.append('''b''' )
      _a											=						Image.fromarray(
          make_transparency_mask(
              (upscaled_tile.size[0], upscaled_tile.size[1])				,     tile_border * 4				,     remove_borders=A )				,     mode='''L'''				,     )
      final_image.paste(
          A				,     (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4)				,     A )



 @torch.no_grad()
 def __call__(self				,     A				,     A				,     A = 75				,     A = 9.0				,     A = 50				,     A = None				,     A = 1				,     A = 0.0				,     A = None				,     A = None				,     A = None				,     A = 1				,     A = 128				,     A = 32				,     A = 32				,     )					->  int:


      """simple docstring"""



      _a											=						Image.new('''RGB'''				,     (image.size[0] * 4, image.size[1] * 4) )
      _a											=						math.ceil(image.size[0] / tile_size )
      _a											=						math.ceil(image.size[1] / tile_size )
      _a											=						tcx * tcy
      _a											=						0
      for y in range(A ):
           for x in range(A ):
                self._process_tile(
                    A				,     A				,     A				,     A				,     A				,     A				,     A				,     prompt=A				,     num_inference_steps=A				,     guidance_scale=A				,     noise_level=A				,     negative_prompt=A				,     num_images_per_prompt=A				,     eta=A				,     generator=A				,     latents=A				,     )
                current_count += 1
                if callback is not None:
                     callback({'''progress''': current_count / total_tile_count, '''image''': final_image} )
      return final_image





def lowerCAmelCase						():



     """simple docstring"""



     _a											=						'''stabilityai/stable-diffusion-x4-upscaler'''
     _a											=						StableDiffusionTiledUpscalePipeline.from_pretrained(__A						,			revision='''fp16'''						,			torch_dtype=torch.floataa)
     _a											=						pipe.to('''cuda''')
     _a											=						Image.open('''../../docs/source/imgs/diffusers_library.jpg''')

     def callback(__A):
          print(F'''progress: {obj['progress']:.4f}''')
          obj["image"].save('''diffusers_library_progress.jpg''')

     _a											=						pipe(image=__A						,			prompt='''Black font, white background, vector'''						,			noise_level=40						,			callback=__A)
     final_image.save('''diffusers_library.jpg''')


if __name__ == "__main__":
  main()











'''simple docstring'''





import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
  import onnxruntime as ort






class __A    (						A     ,     unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase					: Dict    = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'



 def       a__						(self				,     A=0 )					->  str:


      """simple docstring"""



      _a											=						floats_tensor((1, 3, 128, 128)				,     rng=random.Random(A ) )
      _a											=						np.random.RandomState(A )
      _a											=						{
          '''prompt''': '''A painting of a squirrel eating a burger''',
          '''image''': image,
          '''generator''': generator,
          '''num_inference_steps''': 3,
          '''strength''': 0.75,
          '''guidance_scale''': 7.5,
          '''output_type''': '''numpy''',
      }
      return inputs



 def       a__						(self )					->  str:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.69643, 0.58484, 0.50314, 0.58760, 0.55368, 0.59643, 0.51529, 0.41217, 0.49087] )
      assert np.abs(image_slice - expected_slice ).max() < 1E-1



 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						PNDMScheduler.from_config(pipe.scheduler.config				,     skip_prk_steps=A )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.61737, 0.54642, 0.53183, 0.54465, 0.52742, 0.60525, 0.49969, 0.40655, 0.48154] )

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



 def       a__						(self )					->  int:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						LMSDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      # warmup pass to apply optimizations
      _a											=						pipe(**self.get_dummy_inputs() )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52761, 0.59977, 0.49033, 0.49619, 0.54282, 0.50311, 0.47600, 0.40918, 0.45203] )

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



 def       a__						(self )					->  Dict:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						EulerDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] )

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



 def       a__						(self )					->  Tuple:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304] )

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



 def       a__						(self )					->  List[str]:


      """simple docstring"""



      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint				,     provider='''CPUExecutionProvider''' )
      _a											=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
      pipe.set_progress_bar_config(disable=A )

      _a											=						self.get_dummy_inputs()
      _a											=						pipe(**A ).images
      _a											=						image[0, -3:, -3:, -1]

      assert image.shape == (1, 128, 128, 3)
      _a											=						np.array([0.65331, 0.58277, 0.48204, 0.56059, 0.53665, 0.56235, 0.50969, 0.40009, 0.46552] )

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






@nightly
@require_onnxruntime
@require_torch_gpu
class __A    (						unittest.TestCase		):



 '''simple docstring'''







 @property
 def       a__						(self )					->  Tuple:


      """simple docstring"""



      return (
          "CUDAExecutionProvider",
          {
              "gpu_mem_limit": "15000000000",  # 15GB
              "arena_extend_strategy": "kSameAsRequested",
          },
      )



 @property
 def       a__						(self )					->  Any:


      """simple docstring"""



      _a											=						ort.SessionOptions()
      _a											=						False
      return options



 def       a__						(self )					->  str:


      """simple docstring"""



      _a											=						load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
          '''/img2img/sketch-mountains-input.jpg''' )
      _a											=						init_image.resize((768, 512) )
      # using the PNDM scheduler by default
      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
          '''CompVis/stable-diffusion-v1-4'''				,     revision='''onnx'''				,     safety_checker=A				,     feature_extractor=A				,     provider=self.gpu_provider				,     sess_options=self.gpu_options				,     )
      pipe.set_progress_bar_config(disable=A )

      _a											=						'''A fantasy landscape, trending on artstation'''

      _a											=						np.random.RandomState(0 )
      _a											=						pipe(
          prompt=A				,     image=A				,     strength=0.75				,     guidance_scale=7.5				,     num_inference_steps=10				,     generator=A				,     output_type='''np'''				,     )
      _a											=						output.images
      _a											=						images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 768, 3)
      _a											=						np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019] )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



 def       a__						(self )					->  Optional[int]:


      """simple docstring"""



      _a											=						load_image(
          '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
          '''/img2img/sketch-mountains-input.jpg''' )
      _a											=						init_image.resize((768, 512) )
      _a											=						LMSDiscreteScheduler.from_pretrained(
          '''runwayml/stable-diffusion-v1-5'''				,     subfolder='''scheduler'''				,     revision='''onnx''' )
      _a											=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
          '''runwayml/stable-diffusion-v1-5'''				,     revision='''onnx'''				,     scheduler=A				,     safety_checker=A				,     feature_extractor=A				,     provider=self.gpu_provider				,     sess_options=self.gpu_options				,     )
      pipe.set_progress_bar_config(disable=A )

      _a											=						'''A fantasy landscape, trending on artstation'''

      _a											=						np.random.RandomState(0 )
      _a											=						pipe(
          prompt=A				,     image=A				,     strength=0.75				,     guidance_scale=7.5				,     num_inference_steps=20				,     generator=A				,     output_type='''np'''				,     )
      _a											=						output.images
      _a											=						images[0, 255:258, 383:386, -1]

      assert images.shape == (1, 512, 768, 3)
      _a											=						np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431] )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



