




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'''





	snake_case_		    =     size[0] - overlap_pixels * 2
	snake_case_		    =     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
	snake_case_		    =     np.ones((size_y, size_x)     ,	dtype=np.uinta							) * 255
	snake_case_		    =     np.pad(_A     ,	mode="linear_ramp"     ,	pad_width=_A     ,	end_values=0							)

	if "l" in remove_borders:
		snake_case_		    =     mask[:, overlap_pixels : mask.shape[1]]
	if "r" in remove_borders:
		snake_case_		    =     mask[:, 0 : mask.shape[1] - overlap_pixels]
	if "t" in remove_borders:
		snake_case_		    =     mask[overlap_pixels : mask.shape[0], :]
	if "b" in remove_borders:
		snake_case_		    =     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'''





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


def 						lowerCamelCase__    (		_A     ,	_A     ,	_A     ,	_A							):







	'''simple docstring'''





	snake_case_		    =     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'''





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


def 						lowerCamelCase__    (		_A     ,	_A							):







	'''simple docstring'''





	snake_case_		    =     n % d
	return n - divisor
class 		UpperCAmelCase   (				UpperCAmelCase__			):







						'''simple docstring'''





						def __init__(						self							:     List[Any]       ,	__lowercase							:     AutoencoderKL       ,	__lowercase							:     CLIPTextModel       ,	__lowercase							:     CLIPTokenizer       ,	__lowercase							:     UNetaDConditionModel       ,	__lowercase							:     DDPMScheduler       ,	__lowercase							:     Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       ,	__lowercase							:     int = 3_50       ,	):






							"""simple docstring"""






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






						def        snake_case__						(						self							:     Optional[int]       ,	__lowercase							:     Union[str, Any]       ,	__lowercase							:     int       ,	__lowercase							:     Tuple       ,	__lowercase							:     List[str]       ,	__lowercase							:     int       ,	__lowercase							:     int       ,	__lowercase							:     str       ,	**__lowercase							:     str						):






							"""simple docstring"""






							torch.manual_seed(0						)
							snake_case_		    =     (
							    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						),
							)
							snake_case_		    =     add_overlap_rect(__lowercase       ,	__lowercase       ,	image.size						)
							snake_case_		    =     image.crop(__lowercase						)
							snake_case_		    =     ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
							snake_case_		    =     translated_slice_x - (original_image_slice / 2)
							snake_case_		    =     max(0       ,	__lowercase						)
							snake_case_		    =     squeeze_tile(__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase						)
							snake_case_		    =     to_input.size
							snake_case_		    =     to_input.resize((tile_size, tile_size)       ,	Image.BICUBIC						)
							snake_case_		    =     super(__lowercase       ,	self						).__call__(image=__lowercase       ,	**__lowercase						).images[0]
							snake_case_		    =     upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)       ,	Image.BICUBIC						)
							snake_case_		    =     unsqueeze_tile(__lowercase       ,	__lowercase						)
							snake_case_		    =     upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)       ,	Image.BICUBIC						)
							snake_case_		    =     []
							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"						)
							snake_case_		    =     Image.fromarray(
							    make_transparency_mask(
							        (upscaled_tile.size[0], upscaled_tile.size[1])       ,	tile_border * 4       ,	remove_borders=__lowercase						)       ,	mode="L"       ,	)
							final_image.paste(
							    __lowercase       ,	(crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4)       ,	__lowercase						)






						@torch.no_grad()
						def __call__(						self							:     str       ,	__lowercase							:     Union[str, List[str]]       ,	__lowercase							:     Union[PIL.Image.Image, List[PIL.Image.Image]]       ,	__lowercase							:     int = 75       ,	__lowercase							:     float = 9.0       ,	__lowercase							:     int = 50       ,	__lowercase							:     Optional[Union[str, List[str]]] = None       ,	__lowercase							:     Optional[int] = 1       ,	__lowercase							:     float = 0.0       ,	__lowercase							:     Optional[torch.Generator] = None       ,	__lowercase							:     Optional[torch.FloatTensor] = None       ,	__lowercase							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,	__lowercase							:     int = 1       ,	__lowercase							:     int = 1_28       ,	__lowercase							:     int = 32       ,	__lowercase							:     int = 32       ,	):






							"""simple docstring"""






							snake_case_		    =     Image.new("RGB"       ,	(image.size[0] * 4, image.size[1] * 4)						)
							snake_case_		    =     math.ceil(image.size[0] / tile_size						)
							snake_case_		    =     math.ceil(image.size[1] / tile_size						)
							snake_case_		    =     tcx * tcy
							snake_case_		    =     0
							for y in range(__lowercase						):
								for x in range(__lowercase						):
									self._process_tile(
									    __lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	prompt=__lowercase       ,	num_inference_steps=__lowercase       ,	guidance_scale=__lowercase       ,	noise_level=__lowercase       ,	negative_prompt=__lowercase       ,	num_images_per_prompt=__lowercase       ,	eta=__lowercase       ,	generator=__lowercase       ,	latents=__lowercase       ,	)
									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'''





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

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

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


if __name__ == "__main__":
		main()






from timeit import timeit

lowercase__				:     Union[str, Any] 		=						{
    "MALAYALAM": True,
    "String": False,
    "rotor": True,
    "level": True,
    "A": True,
    "BB": True,
    "ABC": False,
    "amanaplanacanalpanama": True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     0
	snake_case_		    =     len(_A							) - 1
	while start_i < end_i:
		if s[start_i] == s[end_i]:
			start_i += 1
			end_i -= 1
		else:
			return False
	return True


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     len(_A							) // 2
	snake_case_		    =     len(_A							)

	# We need to traverse till half of the length of string
	# as we can get access of the i'th last element from
	# i'th index.
	# eg: [0,1,2,3,4,5] => 4th index can be accessed
	# with the help of 1st index (i==n-i-1)
	# where n is length of string
	return all(s[i] == s[n - i - 1] for i in range(_A							)							)


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	if len(_A							) <= 2:
		return True
	if s[0] == s[len(_A							) - 1]:
		return is_palindrome_recursive(s[1:-1]							)
	else:
		return False


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	return s == s[::-1]


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	snake_case_		    =     f"all({name}(key) is value for key, value in test_data.items())"
	snake_case_		    =     f"from __main__ import test_data, {name}"
	snake_case_		    =     500000
	snake_case_		    =     timeit(stmt=_A     ,	setup=_A     ,	number=_A							)
	print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds"							)


if __name__ == "__main__":
		for key, value in test_data.items():
				assert is_palindrome(key) is is_palindrome_recursive(key)
				assert is_palindrome(key) is is_palindrome_slice(key)
				print(f'''{key:21} {value}''')
		print("a man a plan a canal panama")

		# finished 500,000 runs in 0.46793 seconds
		benchmark_function("is_palindrome_slice")
		# finished 500,000 runs in 0.85234 seconds
		benchmark_function("is_palindrome")
		# finished 500,000 runs in 1.32028 seconds
		benchmark_function("is_palindrome_recursive")
		# finished 500,000 runs in 2.08679 seconds
		benchmark_function("is_palindrome_traversal")
