


"""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      a__ (				__lowercase     ,			__lowercase     ,			__lowercase=[]   )	->	Optional[int]:
				_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(__lowercase     ,			mode="linear_ramp"     ,			pad_width=__lowercase     ,			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      a__ (				__lowercase     ,			__lowercase     ,			__lowercase   )	->	Optional[Any]:
				return max(__lowercase     ,			min(__lowercase     ,			__lowercase   )   )






def      a__ (				__lowercase     ,			__lowercase     ,			__lowercase   )	->	str:
				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      a__ (				__lowercase     ,			__lowercase     ,			__lowercase   )	->	Union[str, Any]:
				_A					  =			list(__lowercase   )
				rect[0] -= overlap
				rect[1] -= overlap
				rect[2] += overlap
				rect[3] += overlap
				_A					  =			clamp_rect(__lowercase     ,			[0, 0]     ,			[image_size[0], image_size[1]]   )
				return rect






def      a__ (				__lowercase     ,			__lowercase     ,			__lowercase     ,			__lowercase   )	->	Any:
				_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(__lowercase     ,			(original_slice, 0)   )
				return result






def      a__ (				__lowercase     ,			__lowercase   )	->	Any:
				_A					  =			(original_image_slice * 4, 0, tile.size[0], tile.size[1])
				_A					  =			tile.crop(__lowercase   )
				return tile






def      a__ (				__lowercase     ,			__lowercase   )	->	List[str]:
				_A					  =			n % d
				return n - divisor
class snake_case      (  _UpperCamelCase):







		def __init__(					self      :       Union[str, Any]    ,   a__      :       AutoencoderKL    ,   a__      :       CLIPTextModel    ,   a__      :       CLIPTokenizer    ,   a__      :       UNetaDConditionModel    ,   a__      :       DDPMScheduler    ,   a__      :       Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]    ,   a__      :       int = 3_50    ,   )       ->						Tuple:





						'''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      :       Tuple    ,   a__      :       Dict    ,   a__      :       int    ,   a__      :       List[Any]    ,   a__      :       Optional[int]    ,   a__      :       Tuple    ,   a__      :       int    ,   a__      :       List[Any]    ,   **a__      :       str		)       ->						Dict:





						'''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      :       List[Any]    ,   a__      :       Union[str, List[str]]    ,   a__      :       Union[PIL.Image.Image, List[PIL.Image.Image]]    ,   a__      :       int = 75    ,   a__      :       float = 9.0    ,   a__      :       int = 50    ,   a__      :       Optional[Union[str, List[str]]] = None    ,   a__      :       Optional[int] = 1    ,   a__      :       float = 0.0    ,   a__      :       Optional[torch.Generator] = None    ,   a__      :       Optional[torch.FloatTensor] = None    ,   a__      :       Optional[Callable[[int, int, torch.FloatTensor], None]] = None    ,   a__      :       int = 1    ,   a__      :       int = 1_28    ,   a__      :       int = 32    ,   a__      :       int = 32    ,   )       ->						List[str]:





						'''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      a__ (				)	->	Union[str, Any]:
				# Run a demo
				_A					  =			"stabilityai/stable-diffusion-x4-upscaler"
				_A					  =			StableDiffusionTiledUpscalePipeline.from_pretrained(__lowercase     ,			revision="fp16"     ,			torch_dtype=torch.floataa   )
				_A					  =			pipe.to("cuda"   )
				_A					  =			Image.open("../../docs/source/imgs/diffusers_library.jpg"   )

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

				_A					  =			pipe(image=__lowercase     ,			prompt="Black font, white background, vector"     ,			noise_level=40     ,			callback=__lowercase   )
				final_image.save("diffusers_library.jpg"   )


if __name__ == "__main__":
		main()



"""simple docstring"""


import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a_       							=    logging.get_logger(__name__)

a_       							=    {
    "Salesforce/blip-vqa-base": "https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json",
    "Salesforce/blip-vqa-capfit-large": (
        "https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-base": (
        "https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-large": (
        "https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"
    ),
    "Salesforce/blip-itm-base-coco": "https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json",
    "Salesforce/blip-itm-large-coco": "https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json",
    "Salesforce/blip-itm-base-flikr": "https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json",
    "Salesforce/blip-itm-large-flikr": (
        "https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"
    ),
}
class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			'blip_text_model'







		def __init__(					self      :       int    ,   a__      :       List[str]=3_05_24    ,   a__      :       List[str]=7_68    ,   a__      :       List[Any]=7_68    ,   a__      :       int=30_72    ,   a__      :       List[str]=7_68    ,   a__      :       Dict=12    ,   a__      :       Optional[int]=8    ,   a__      :       Optional[Any]=5_12    ,   a__      :       List[Any]="gelu"    ,   a__      :       Optional[Any]=1E-1_2    ,   a__      :       Any=0.0    ,   a__      :       int=0.0    ,   a__      :       Dict=0.0_2    ,   a__      :       Optional[Any]=3_05_22    ,   a__      :       Any=2    ,   a__      :       int=0    ,   a__      :       Union[str, Any]=1_02    ,   a__      :       Tuple=True    ,   a__      :       Optional[int]=True    ,   **a__      :       Any    ,   )       ->						List[Any]:





						'''simple docstring'''







						super().__init__(
						    pad_token_id=a__    ,   bos_token_id=a__    ,   eos_token_id=a__    ,   sep_token_id=a__    ,   **a__    ,   )

						_A					  =			vocab_size
						_A					  =			hidden_size
						_A					  =			encoder_hidden_size
						_A					  =			intermediate_size
						_A					  =			projection_dim
						_A					  =			hidden_dropout_prob
						_A					  =			num_hidden_layers
						_A					  =			num_attention_heads
						_A					  =			max_position_embeddings
						_A					  =			layer_norm_eps
						_A					  =			hidden_act
						_A					  =			initializer_range
						_A					  =			attention_probs_dropout_prob
						_A					  =			is_decoder
						_A					  =			use_cache







		@classmethod
		def  a_ (					cls      :       Optional[Any]    ,   a__      :       Union[str, os.PathLike]    ,   **a__      :       Optional[Any]		)       ->						"PretrainedConfig":





						'''simple docstring'''







						cls._set_token_in_kwargs(a__		)

						_A  ,		_A					  =			cls.get_config_dict(a__    ,   **a__		)

						# get the text config dict if we are loading from BlipConfig
						if config_dict.get("model_type"		) == "blip":
										_A					  =			config_dict["text_config"]

						if "model_type" in config_dict and hasattr(cls    ,   "model_type"		) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""		)

						return cls.from_dict(a__    ,   **a__		)





class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			'blip_vision_model'







		def __init__(					self      :       Optional[Any]    ,   a__      :       Any=7_68    ,   a__      :       List[str]=30_72    ,   a__      :       str=5_12    ,   a__      :       Any=12    ,   a__      :       int=12    ,   a__      :       int=3_84    ,   a__      :       Tuple=16    ,   a__      :       str="gelu"    ,   a__      :       Tuple=1E-5    ,   a__      :       List[str]=0.0    ,   a__      :       List[Any]=1E-1_0    ,   **a__      :       int    ,   )       ->						List[str]:





						'''simple docstring'''







						super().__init__(**a__		)

						_A					  =			hidden_size
						_A					  =			intermediate_size
						_A					  =			projection_dim
						_A					  =			num_hidden_layers
						_A					  =			num_attention_heads
						_A					  =			patch_size
						_A					  =			image_size
						_A					  =			initializer_range
						_A					  =			attention_dropout
						_A					  =			layer_norm_eps
						_A					  =			hidden_act







		@classmethod
		def  a_ (					cls      :       Any    ,   a__      :       Union[str, os.PathLike]    ,   **a__      :       int		)       ->						"PretrainedConfig":





						'''simple docstring'''







						cls._set_token_in_kwargs(a__		)

						_A  ,		_A					  =			cls.get_config_dict(a__    ,   **a__		)

						# get the vision config dict if we are loading from BlipConfig
						if config_dict.get("model_type"		) == "blip":
										_A					  =			config_dict["vision_config"]

						if "model_type" in config_dict and hasattr(cls    ,   "model_type"		) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""		)

						return cls.from_dict(a__    ,   **a__		)





class snake_case      (  _UpperCamelCase):
		__UpperCamelCase           =			'blip'
		__UpperCamelCase           =			True







		def __init__(					self      :       List[Any]    ,   a__      :       Optional[int]=None    ,   a__      :       str=None    ,   a__      :       List[str]=5_12    ,   a__      :       Any=2.6_5_9_2    ,   a__      :       str=2_56    ,   **a__      :       Optional[int]    ,   )       ->						Dict:





						'''simple docstring'''







						super().__init__(**a__		)

						if text_config is None:
										_A					  =			{}
										logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values."		)

						if vision_config is None:
										_A					  =			{}
										logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values."		)

						_A					  =			BlipTextConfig(**a__		)
						_A					  =			BlipVisionConfig(**a__		)

						_A					  =			self.vision_config.hidden_size

						_A					  =			projection_dim
						_A					  =			logit_scale_init_value
						_A					  =			1.0
						_A					  =			0.0_2
						_A					  =			image_text_hidden_size







		@classmethod
		def  a_ (					cls      :       Tuple    ,   a__      :       BlipTextConfig    ,   a__      :       BlipVisionConfig    ,   **a__      :       Optional[int]		)       ->						str:





						'''simple docstring'''







						return cls(text_config=text_config.to_dict()    ,   vision_config=vision_config.to_dict()    ,   **a__		)







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





						'''simple docstring'''







						_A					  =			copy.deepcopy(self.__dict__		)
						_A					  =			self.text_config.to_dict()
						_A					  =			self.vision_config.to_dict()
						_A					  =			self.__class__.model_type
						return output