



"""simple docstring"""






from importlib import import_module

from .logging import get_logger


lowerCAmelCase__        =				get_logger(__name__)






class        __snake_case       :




  def __init__( self     :						int						,					__lowerCAmelCase     :						List[str]						,					__lowerCAmelCase     :						List[Any]=None		):






         """simple docstring"""






         _lowerCamelCase						:				Tuple    			= attrs or []
         if module is not None:
                for key in module.__dict__:
                       if key in attrs or not key.startswith('''__'''		):
                              setattr(self						,					__lowerCAmelCase						,					getattr(__lowerCAmelCase						,					__lowerCAmelCase		)		)
         _lowerCamelCase						:				Any    			= module._original_module if isinstance(__lowerCAmelCase						,					_PatchedModuleObj		) else module






class        __snake_case       :
  snake_case__				:   Dict  			=						[]




  def __init__( self     :						Union[str, Any]						,					__lowerCAmelCase     :						Optional[int]						,					__lowerCAmelCase     :						str						,					__lowerCAmelCase     :						Dict						,					__lowerCAmelCase     :						List[str]=None		):






         """simple docstring"""






         _lowerCamelCase						:				Optional[Any]    			= obj
         _lowerCamelCase						:				int    			= target
         _lowerCamelCase						:				int    			= new
         _lowerCamelCase						:				Tuple    			= target.split('''.'''		)[0]
         _lowerCamelCase						:				Optional[Any]    			= {}
         _lowerCamelCase						:				Optional[int]    			= attrs or []




  def __enter__( self     :						Optional[Any]		):






         """simple docstring"""






         *_lowerCamelCase			,    _lowerCamelCase						:				Optional[int]    			= self.target.split('''.'''		)

         # Patch modules:
         # it's used to patch attributes of submodules like "os.path.join";
         # in this case we need to patch "os" and "os.path"

         for i in range(len(__lowerCAmelCase		)		):
                try:
                       _lowerCamelCase						:				Union[str, Any]    			= import_module('''.'''.join(submodules[: i + 1]		)		)
                except ModuleNotFoundError:
                       continue
                # We iterate over all the globals in self.obj in case we find "os" or "os.path"
                for attr in self.obj.__dir__():
                       _lowerCamelCase						:				Dict    			= getattr(self.obj						,					__lowerCAmelCase		)
                       # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
                       # This allows to patch renamed modules like "from os import path as ospath".
                       if obj_attr is submodule or (
                           (isinstance(__lowerCAmelCase						,					_PatchedModuleObj		) and obj_attr._original_module is submodule)
                       ):
                              _lowerCamelCase						:				Dict    			= obj_attr
                              # patch at top level
                              setattr(self.obj						,					__lowerCAmelCase						,					_PatchedModuleObj(__lowerCAmelCase						,					attrs=self.attrs		)		)
                              _lowerCamelCase						:				Tuple    			= getattr(self.obj						,					__lowerCAmelCase		)
                              # construct lower levels patches
                              for key in submodules[i + 1 :]:
                                     setattr(__lowerCAmelCase						,					__lowerCAmelCase						,					_PatchedModuleObj(getattr(__lowerCAmelCase						,					__lowerCAmelCase						,					__lowerCAmelCase		)						,					attrs=self.attrs		)		)
                                     _lowerCamelCase						:				int    			= getattr(__lowerCAmelCase						,					__lowerCAmelCase		)
                              # finally set the target attribute
                              setattr(__lowerCAmelCase						,					__lowerCAmelCase						,					self.new		)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

         if submodules:  # if it's an attribute of a submodule like "os.path.join"
                try:
                       _lowerCamelCase						:				Optional[int]    			= getattr(import_module('''.'''.join(__lowerCAmelCase		)		)						,					__lowerCAmelCase		)
                except (AttributeError, ModuleNotFoundError):
                       return
                # We iterate over all the globals in self.obj in case we find "os.path.join"
                for attr in self.obj.__dir__():
                       # We don't check for the name of the global, but rather if its value *is* "os.path.join".
                       # This allows to patch renamed attributes like "from os.path import join as pjoin".
                       if getattr(self.obj						,					__lowerCAmelCase		) is attr_value:
                              _lowerCamelCase						:				str    			= getattr(self.obj						,					__lowerCAmelCase		)
                              setattr(self.obj						,					__lowerCAmelCase						,					self.new		)
         elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
                _lowerCamelCase						:				List[str]    			= globals()['''__builtins__'''][target_attr]
                setattr(self.obj						,					__lowerCAmelCase						,					self.new		)
         else:
                raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''		)




  def __exit__( self     :						Any						,					*__lowerCAmelCase     :						Dict		):






         """simple docstring"""






         for attr in list(self.original		):
                setattr(self.obj						,					__lowerCAmelCase						,					self.original.pop(__lowerCAmelCase		)		)




  def 						SCREAMING_SNAKE_CASE				( self     :						Dict		):






         """simple docstring"""






         self.__enter__()
         self._active_patches.append(self		)




  def 						SCREAMING_SNAKE_CASE				( self     :						List[str]		):






         """simple docstring"""






         try:
                self._active_patches.remove(self		)
         except ValueError:
                # If the patch hasn't been started this will fail
                return None

         return self.__exit__()






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 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_=[]	):


  '''simple docstring'''

  lowerCamelCase :					Optional[Any]    =				size[0] - overlap_pixels * 2
  lowerCamelCase :					int    =				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
  lowerCamelCase :					Tuple    =				np.ones((size_y, size_x)      ,						dtype=np.uinta	) * 255
  lowerCamelCase :					List[Any]    =				np.pad(SCREAMING_SNAKE_CASE_      ,						mode="linear_ramp"      ,						pad_width=SCREAMING_SNAKE_CASE_      ,						end_values=0	)

  if "l" in remove_borders:
    lowerCamelCase :					Optional[Any]    =				mask[:, overlap_pixels : mask.shape[1]]
  if "r" in remove_borders:
    lowerCamelCase :					List[Any]    =				mask[:, 0 : mask.shape[1] - overlap_pixels]
  if "t" in remove_borders:
    lowerCamelCase :					List[Any]    =				mask[overlap_pixels : mask.shape[0], :]
  if "b" in remove_borders:
    lowerCamelCase :					Tuple    =				mask[0 : mask.shape[0] - overlap_pixels, :]
  return mask






def 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''simple docstring'''

  return max(SCREAMING_SNAKE_CASE_      ,						min(SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	)	)






def 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''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 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''simple docstring'''

  lowerCamelCase :					Optional[Any]    =				list(SCREAMING_SNAKE_CASE_	)
  rect[0] -= overlap
  rect[1] -= overlap
  rect[2] += overlap
  rect[3] += overlap
  lowerCamelCase :					Any    =				clamp_rect(SCREAMING_SNAKE_CASE_      ,						[0, 0]      ,						[image_size[0], image_size[1]]	)
  return rect






def 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''simple docstring'''

  lowerCamelCase :					Dict    =				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(SCREAMING_SNAKE_CASE_      ,						(original_slice, 0)	)
  return result






def 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''simple docstring'''

  lowerCamelCase :					Union[str, Any]    =				(original_image_slice * 4, 0, tile.size[0], tile.size[1])
  lowerCamelCase :					int    =				tile.crop(SCREAMING_SNAKE_CASE_	)
  return tile






def 		lowercase_(  SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_	):


  '''simple docstring'''

  lowerCamelCase :					int    =				n % d
  return n - divisor
class 	UpperCAmelCase_					(					UpperCamelCase    ):

   '''simple docstring'''




   def __init__(		self						,				__A						,				__A						,				__A						,				__A						,				__A						,				__A						,				__A = 350						,				):






     """simple docstring"""





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






   def _snake_case    (		self						,				__A						,				__A						,				__A						,				__A						,				__A						,				__A						,				__A						,				**__A ):






     """simple docstring"""





     torch.manual_seed(0 )
     lowerCamelCase :					Tuple    =				(
         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 ),
     )
     lowerCamelCase :					Union[str, Any]    =				add_overlap_rect(__A						,				__A						,				image.size )
     lowerCamelCase :					List[str]    =				image.crop(__A )
     lowerCamelCase :					Optional[int]    =				((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
     lowerCamelCase :					int    =				translated_slice_x - (original_image_slice / 2)
     lowerCamelCase :					Optional[Any]    =				max(0						,				__A )
     lowerCamelCase :					Tuple    =				squeeze_tile(__A						,				__A						,				__A						,				__A )
     lowerCamelCase :					Dict    =				to_input.size
     lowerCamelCase :					Optional[int]    =				to_input.resize((tile_size, tile_size)						,				Image.BICUBIC )
     lowerCamelCase :					Dict    =				super(__A						,				self ).__call__(image=__A						,				**__A ).images[0]
     lowerCamelCase :					Tuple    =				upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)						,				Image.BICUBIC )
     lowerCamelCase :					Optional[Any]    =				unsqueeze_tile(__A						,				__A )
     lowerCamelCase :					Optional[Any]    =				upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)						,				Image.BICUBIC )
     lowerCamelCase :					int    =				[]
     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" )
     lowerCamelCase :					int    =				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						,				):






     """simple docstring"""





     lowerCamelCase :					Dict    =				Image.new("RGB"						,				(image.size[0] * 4, image.size[1] * 4) )
     lowerCamelCase :					Union[str, Any]    =				math.ceil(image.size[0] / tile_size )
     lowerCamelCase :					Dict    =				math.ceil(image.size[1] / tile_size )
     lowerCamelCase :					str    =				tcx * tcy
     lowerCamelCase :					int    =				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 		lowercase_(  ):


  '''simple docstring'''

  lowerCamelCase :					Dict    =				"stabilityai/stable-diffusion-x4-upscaler"
  lowerCamelCase :					Union[str, Any]    =				StableDiffusionTiledUpscalePipeline.from_pretrained(SCREAMING_SNAKE_CASE_      ,						revision="fp16"      ,						torch_dtype=torch.floataa	)
  lowerCamelCase :					Optional[Any]    =				pipe.to("cuda"	)
  lowerCamelCase :					List[str]    =				Image.open("../../docs/source/imgs/diffusers_library.jpg"	)

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

  lowerCamelCase :					int    =				pipe(image=SCREAMING_SNAKE_CASE_      ,						prompt="Black font, white background, vector"      ,						noise_level=40      ,						callback=SCREAMING_SNAKE_CASE_	)
  final_image.save("diffusers_library.jpg"	)


if __name__ == "__main__":
   main()



