





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     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__=[]						):
		lowerCamelCase_	:     Union[str, 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_	:     List[str] 						=      np.ones((size_y, size_x)							,dtype=np.uinta						) * 2_55
		lowerCamelCase_	:     Tuple 						=      np.pad(lowerCAmelCase__							,mode='linear_ramp'							,pad_width=lowerCAmelCase__							,end_values=0						)

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


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		return max(lowerCAmelCase__							,min(lowerCAmelCase__							,lowerCAmelCase__						)						)


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		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     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		lowerCamelCase_	:     List[str] 						=      list(lowerCAmelCase__						)
		rect[0] -= overlap
		rect[1] -= overlap
		rect[2] += overlap
		rect[3] += overlap
		lowerCamelCase_	:     Optional[int] 						=      clamp_rect(lowerCAmelCase__							,[0, 0]							,[image_size[0], image_size[1]]						)
		return rect


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		lowerCamelCase_	:     List[str] 						=      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(lowerCAmelCase__							,(original_slice, 0)						)
		return result


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__						):
		lowerCamelCase_	:     List[str] 						=      (original_image_slice * 4, 0, tile.size[0], tile.size[1])
		lowerCamelCase_	:     Dict 						=      tile.crop(lowerCAmelCase__						)
		return tile


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__						):
		lowerCamelCase_	:     Union[str, Any] 						=      n % d
		return n - divisor






class 						UpperCamelCase_  (  snake_case__							):



					def __init__(		self     :     Union[str, Any]       ,      lowerCamelCase     :     AutoencoderKL       ,      lowerCamelCase     :     CLIPTextModel       ,      lowerCamelCase     :     CLIPTokenizer       ,      lowerCamelCase     :     UNetaDConditionModel       ,      lowerCamelCase     :     DDPMScheduler       ,      lowerCamelCase     :     Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       ,      lowerCamelCase     :     int = 3_50       ,      ):
							super().__init__(
							    vae=lowerCamelCase       ,      text_encoder=lowerCamelCase       ,      tokenizer=lowerCamelCase       ,      unet=lowerCamelCase       ,      low_res_scheduler=lowerCamelCase       ,      scheduler=lowerCamelCase       ,      max_noise_level=lowerCamelCase       ,      )



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





					@torch.no_grad()
					def __call__(		self     :     Optional[int]       ,      lowerCamelCase     :     Union[str, List[str]]       ,      lowerCamelCase     :     Union[PIL.Image.Image, List[PIL.Image.Image]]       ,      lowerCamelCase     :     int = 75       ,      lowerCamelCase     :     float = 9.0       ,      lowerCamelCase     :     int = 50       ,      lowerCamelCase     :     Optional[Union[str, List[str]]] = None       ,      lowerCamelCase     :     Optional[int] = 1       ,      lowerCamelCase     :     float = 0.0       ,      lowerCamelCase     :     Optional[torch.Generator] = None       ,      lowerCamelCase     :     Optional[torch.FloatTensor] = None       ,      lowerCamelCase     :     Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,      lowerCamelCase     :     int = 1       ,      lowerCamelCase     :     int = 1_28       ,      lowerCamelCase     :     int = 32       ,      lowerCamelCase     :     int = 32       ,      ):
							lowerCamelCase_	:     Union[str, Any] 						=      Image.new('RGB'       ,      (image.size[0] * 4, image.size[1] * 4)						)
							lowerCamelCase_	:     List[Any] 						=      math.ceil(image.size[0] / tile_size						)
							lowerCamelCase_	:     List[Any] 						=      math.ceil(image.size[1] / tile_size						)
							lowerCamelCase_	:     List[Any] 						=      tcx * tcy
							lowerCamelCase_	:     List[str] 						=      0
							for y in range(lowerCamelCase						):
									for x in range(lowerCamelCase						):
											self._process_tile(
											    lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      prompt=lowerCamelCase       ,      num_inference_steps=lowerCamelCase       ,      guidance_scale=lowerCamelCase       ,      noise_level=lowerCamelCase       ,      negative_prompt=lowerCamelCase       ,      num_images_per_prompt=lowerCamelCase       ,      eta=lowerCamelCase       ,      generator=lowerCamelCase       ,      latents=lowerCamelCase       ,      )
											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     ( ):
		# Run a demo
		lowerCamelCase_	:     str 						=      'stabilityai/stable-diffusion-x4-upscaler'
		lowerCamelCase_	:     List[str] 						=      StableDiffusionTiledUpscalePipeline.from_pretrained(lowerCAmelCase__							,revision='fp16'							,torch_dtype=torch.floataa						)
		lowerCamelCase_	:     Optional[Any] 						=      pipe.to('cuda'						)
		lowerCamelCase_	:     List[Any] 						=      Image.open('../../docs/source/imgs/diffusers_library.jpg'						)

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

		lowerCamelCase_	:     List[str] 						=      pipe(image=lowerCAmelCase__							,prompt='Black font, white background, vector'							,noise_level=40							,callback=lowerCAmelCase__						)
		final_image.save('diffusers_library.jpg'						)


if __name__ == "__main__":
		main()







import json
import os
import tempfile

import datasets
from utils import generate_example_dataset, get_duration


_lowercase		:  List[str]			       =5_0000
_lowercase		:  str			       =5000

_lowercase       , _lowercase		:  List[str]			       =os.path.split(__file__)
_lowercase		:  Union[str, Any]			       =os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))


@get_duration
def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__						):
		for i in range(lowerCAmelCase__						):
				lowerCamelCase_	:     Tuple 						=      dataset[i]


@get_duration
def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		for i in range(0							,len(lowerCAmelCase__						)							,lowerCAmelCase__						):
				lowerCamelCase_	:     Tuple 						=      dataset[i : i + batch_size]


@get_duration
def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		with dataset.formatted_as(type=lowerCAmelCase__						):
				for i in range(lowerCAmelCase__						):
						lowerCamelCase_	:     Tuple 						=      dataset[i]


@get_duration
def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__						):
		with dataset.formatted_as(type=lowerCAmelCase__						):
				for i in range(0							,lowerCAmelCase__							,lowerCAmelCase__						):
						lowerCamelCase_	:     Optional[int] 						=      dataset[i : i + batch_size]


def 		_SCREAMING_SNAKE_CASE     ( ):
		lowerCamelCase_	:     Any 						=      {'num examples': SPEED_TEST_N_EXAMPLES}
		lowerCamelCase_	:     Optional[Any] 						=      [
		    (read, {'length': SMALL_TEST}),
		    (read, {'length': SPEED_TEST_N_EXAMPLES}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_00}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10_00}),
		    (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}),
		    (read_formatted, {'type': 'pandas', 'length': SMALL_TEST}),
		    (read_formatted, {'type': 'torch', 'length': SMALL_TEST}),
		    (read_formatted, {'type': 'tensorflow', 'length': SMALL_TEST}),
		    (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}),
		    (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10_00}),
		]

		lowerCamelCase_	:     Optional[Any] 						=      [
		    (read, {'length': SMALL_TEST}),
		    (read, {'length': SPEED_TEST_N_EXAMPLES}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_00}),
		    (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10_00}),
		    (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}),
		    (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}),
		    (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10_00}),
		]
		with tempfile.TemporaryDirectory() as tmp_dir:
				print('generating dataset'						)
				lowerCamelCase_	:     List[Any] 						=      datasets.Features(
				    {'list': datasets.Sequence(datasets.Value('float32'						)						), 'numbers': datasets.Value('float32'						)}						)
				lowerCamelCase_	:     Union[str, Any] 						=      generate_example_dataset(
				    os.path.join(lowerCAmelCase__							,'dataset.arrow'						)							,lowerCAmelCase__							,num_examples=lowerCAmelCase__							,seq_shapes={'list': (1_00,)}							,)
				print('first set of iterations'						)
				for func, kwargs in functions:
						print(func.__name__							,str(lowerCAmelCase__						)						)
						lowerCamelCase_	:     Optional[int] 						=      func(lowerCAmelCase__							,**lowerCAmelCase__						)

				print('shuffling dataset'						)
				lowerCamelCase_	:     int 						=      dataset.shuffle()
				print('Second set of iterations (after shuffling'						)
				for func, kwargs in functions_shuffled:
						print('shuffled '							,func.__name__							,str(lowerCAmelCase__						)						)
						lowerCamelCase_	:     Optional[Any] 						=      func(
						    lowerCAmelCase__							,**lowerCAmelCase__						)

		with open(lowerCAmelCase__							,'wb'						) as f:
				f.write(json.dumps(lowerCAmelCase__						).encode('utf-8'						)						)


if __name__ == "__main__":  # useful to run the profiler
		benchmark_iterating()
