






'''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 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase=[]				)				->	Dict:
							lowerCamelCase__ :     Union[str, Any]	  =	size[0] - overlap_pixels * 2
							lowerCamelCase__ :     Tuple	  =	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__ :     int	  =	np.ones((size_y, size_x)    ,      dtype=np.uinta				) * 255
							lowerCamelCase__ :     Any	  =	np.pad(UpperCamelCase    ,      mode="""linear_ramp"""    ,      pad_width=UpperCamelCase    ,      end_values=0				)

							if "l" in remove_borders:
														lowerCamelCase__ :     Optional[int]	  =	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__ :     Optional[int]	  =	mask[overlap_pixels : mask.shape[0], :]
							if "b" in remove_borders:
														lowerCamelCase__ :     List[str]	  =	mask[0 : mask.shape[0] - overlap_pixels, :]
							return mask





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase				)				->	Optional[Any]:
							return max(UpperCamelCase    ,      min(UpperCamelCase    ,      UpperCamelCase				)				)





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





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase				)				->	int:
							lowerCamelCase__ :     Tuple	  =	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(UpperCamelCase    ,      (original_slice, 0)				)
							return result





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	Dict:
							lowerCamelCase__ :     Optional[int]	  =	(original_image_slice * 4, 0, tile.size[0], tile.size[1])
							lowerCamelCase__ :     Any	  =	tile.crop(UpperCamelCase				)
							return tile





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase				)				->	int:
							lowerCamelCase__ :     Tuple	  =	n % d
							return n - divisor

class _lowercase     (    _lowercase		):




							def __init__(							self:    Tuple      ,							UpperCamelCase__:    AutoencoderKL      ,							UpperCamelCase__:    CLIPTextModel      ,							UpperCamelCase__:    CLIPTokenizer      ,							UpperCamelCase__:    UNetaDConditionModel      ,							UpperCamelCase__:    DDPMScheduler      ,							UpperCamelCase__:    Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,							UpperCamelCase__:    int = 350      ,							):
														super().__init__(
														    vae=UpperCamelCase__      ,							text_encoder=UpperCamelCase__      ,							tokenizer=UpperCamelCase__      ,							unet=UpperCamelCase__      ,							low_res_scheduler=UpperCamelCase__      ,							scheduler=UpperCamelCase__      ,							max_noise_level=UpperCamelCase__      ,							)




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




							@torch.no_grad()
							def __call__(							self:    List[str]      ,							UpperCamelCase__:    Union[str, List[str]]      ,							UpperCamelCase__:    Union[PIL.Image.Image, List[PIL.Image.Image]]      ,							UpperCamelCase__:    int = 75      ,							UpperCamelCase__:    float = 9.0      ,							UpperCamelCase__:    int = 50      ,							UpperCamelCase__:    Optional[Union[str, List[str]]] = None      ,							UpperCamelCase__:    Optional[int] = 1      ,							UpperCamelCase__:    float = 0.0      ,							UpperCamelCase__:    Optional[torch.Generator] = None      ,							UpperCamelCase__:    Optional[torch.FloatTensor] = None      ,							UpperCamelCase__:    Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,							UpperCamelCase__:    int = 1      ,							UpperCamelCase__:    int = 128      ,							UpperCamelCase__:    int = 32      ,							UpperCamelCase__:    int = 32      ,							):
														lowerCamelCase__ :     int	  =	Image.new("""RGB"""      ,							(image.size[0] * 4, image.size[1] * 4)					)
														lowerCamelCase__ :     int	  =	math.ceil(image.size[0] / tile_size					)
														lowerCamelCase__ :     Optional[Any]	  =	math.ceil(image.size[1] / tile_size					)
														lowerCamelCase__ :     List[Any]	  =	tcx * tcy
														lowerCamelCase__ :     Optional[int]	  =	0
														for y in range(UpperCamelCase__					):
																					for x in range(UpperCamelCase__					):
																												self._process_tile(
																												    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							prompt=UpperCamelCase__      ,							num_inference_steps=UpperCamelCase__      ,							guidance_scale=UpperCamelCase__      ,							noise_level=UpperCamelCase__      ,							negative_prompt=UpperCamelCase__      ,							num_images_per_prompt=UpperCamelCase__      ,							eta=UpperCamelCase__      ,							generator=UpperCamelCase__      ,							latents=UpperCamelCase__      ,							)
																												current_count += 1
																												if callback is not None:
																																			callback({"""progress""": current_count / total_tile_count, """image""": final_image}					)
														return final_image





def 			SCREAMING_SNAKE_CASE_	()				->	Dict:
							# Run a demo
							lowerCamelCase__ :     Tuple	  =	"""stabilityai/stable-diffusion-x4-upscaler"""
							lowerCamelCase__ :     int	  =	StableDiffusionTiledUpscalePipeline.from_pretrained(UpperCamelCase    ,      revision="""fp16"""    ,      torch_dtype=torch.floataa				)
							lowerCamelCase__ :     Union[str, Any]	  =	pipe.to("""cuda"""				)
							lowerCamelCase__ :     int	  =	Image.open("""../../docs/source/imgs/diffusers_library.jpg"""				)

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

							lowerCamelCase__ :     Tuple	  =	pipe(image=UpperCamelCase    ,      prompt="""Black font, white background, vector"""    ,      noise_level=40    ,      callback=UpperCamelCase				)
							final_image.save("""diffusers_library.jpg"""				)


if __name__ == "__main__":
			main()









'''simple docstring'''







from math import asin, atan, cos, radians, sin, sqrt, tan

_A     :      List[str]   					=637_8137.0
_A     :      Dict   					=635_6752.31_4245
_A     :      int   					=6_378_137





def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase    ,      UpperCamelCase				)				->	float:
							lowerCamelCase__ :     str	  =	(AXIS_A - AXIS_B) / AXIS_A
							lowerCamelCase__ :     Dict	  =	atan((1 - flattening) * tan(radians(UpperCamelCase				)				)				)
							lowerCamelCase__ :     Dict	  =	atan((1 - flattening) * tan(radians(UpperCamelCase				)				)				)
							lowerCamelCase__ :     Optional[Any]	  =	radians(UpperCamelCase				)
							lowerCamelCase__ :     List[Any]	  =	radians(UpperCamelCase				)
							# Equation
							lowerCamelCase__ :     Tuple	  =	sin((phi_a - phi_a) / 2				)
							lowerCamelCase__ :     List[Any]	  =	sin((lambda_a - lambda_a) / 2				)
							# Square both values
							sin_sq_phi *= sin_sq_phi
							sin_sq_lambda *= sin_sq_lambda
							lowerCamelCase__ :     Tuple	  =	sqrt(sin_sq_phi + (cos(UpperCamelCase				) * cos(UpperCamelCase				) * sin_sq_lambda)				)
							return 2 * RADIUS * asin(UpperCamelCase				)


if __name__ == "__main__":
			import doctest

			doctest.testmod()

