


'''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    lowerCamelCase__   ( A     :    Dict   ,     A     :    Dict   ,     A     :    Optional[int]=[]  ):




						'''simple docstring'''






						UpperCAmelCase         =			size[0] - overlap_pixels * 2
						UpperCAmelCase         =			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
						UpperCAmelCase         =			np.ones((size_y, size_x)   ,     dtype=np.uinta  ) * 2_55
						UpperCAmelCase         =			np.pad(A   ,     mode='''linear_ramp'''   ,     pad_width=A   ,     end_values=0  )

						if "l" in remove_borders:
												UpperCAmelCase         =			mask[:, overlap_pixels : mask.shape[1]]
						if "r" in remove_borders:
												UpperCAmelCase         =			mask[:, 0 : mask.shape[1] - overlap_pixels]
						if "t" in remove_borders:
												UpperCAmelCase         =			mask[overlap_pixels : mask.shape[0], :]
						if "b" in remove_borders:
												UpperCAmelCase         =			mask[0 : mask.shape[0] - overlap_pixels, :]
						return mask


def    lowerCamelCase__   ( A     :    List[Any]   ,     A     :    Union[str, Any]   ,     A     :    Union[str, Any]  ):




						'''simple docstring'''






						return max(A   ,     min(A   ,     A  )  )


def    lowerCamelCase__   ( A     :    [int]   ,     A     :    [int]   ,     A     :    [int]  ):




						'''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     :    [int]   ,     A     :    int   ,     A     :    [int]  ):




						'''simple docstring'''






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


def    lowerCamelCase__   ( A     :    Tuple   ,     A     :    List[str]   ,     A     :    List[str]   ,     A     :    Dict  ):




						'''simple docstring'''






						UpperCAmelCase         =			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     :    str   ,     A     :    Union[str, Any]  ):




						'''simple docstring'''






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


def    lowerCamelCase__   ( A     :    Dict   ,     A     :    Union[str, Any]  ):




						'''simple docstring'''






						UpperCAmelCase         =			n % d
						return n - divisor






class  UpperCamelCase__(     lowerCAmelCase ):




				def __init__(	self    :				Dict   ,					lowerCAmelCase    :				AutoencoderKL   ,					lowerCAmelCase    :				CLIPTextModel   ,					lowerCAmelCase    :				CLIPTokenizer   ,					lowerCAmelCase    :				UNetaDConditionModel   ,					lowerCAmelCase    :				DDPMScheduler   ,					lowerCAmelCase    :				Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]   ,					lowerCAmelCase    :				int = 350   ,					)->  List[Any]:

										"""simple docstring"""




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




				def   a__(	self    :				List[str]   ,					lowerCAmelCase    :				Any   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				Optional[Any]   ,					lowerCAmelCase    :				Optional[int]   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				List[Any]   ,					lowerCAmelCase    :				List[Any]   ,					**lowerCAmelCase    :				Optional[Any]   )->  Optional[int]:

										"""simple docstring"""




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

										"""simple docstring"""




										UpperCAmelCase         =			Image.new('''RGB'''   ,					(image.size[0] * 4, image.size[1] * 4)   )
										UpperCAmelCase         =			math.ceil(image.size[0] / tile_size   )
										UpperCAmelCase         =			math.ceil(image.size[1] / tile_size   )
										UpperCAmelCase         =			tcx * tcy
										UpperCAmelCase         =			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    lowerCamelCase__   ( ):




						'''simple docstring'''






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

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

						UpperCAmelCase         =			pipe(image=A   ,     prompt='''Black font, white background, vector'''   ,     noise_level=40   ,     callback=A  )
						final_image.save('''diffusers_library.jpg'''  )


if __name__ == "__main__":
						main()









'''simple docstring'''



import time
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device

from ..test_modeling_common import ids_tensor


if is_torch_available():
	import torch

	from transformers.generation import (
	    MaxLengthCriteria,
	    MaxNewTokensCriteria,
	    MaxTimeCriteria,
	    StoppingCriteriaList,
	    validate_stopping_criteria,
	)






@require_torch
class  UpperCamelCase__(     unittest.TestCase ):




				def   a__(	self    :				List[Any]   ,					lowerCAmelCase    :				Optional[Any]   )->  Optional[int]:

										"""simple docstring"""




										UpperCAmelCase         =			3
										UpperCAmelCase         =			250

										UpperCAmelCase         =			ids_tensor((batch_size, length)   ,					lowerCAmelCase   )
										UpperCAmelCase         =			torch.ones((batch_size, length)   ,					device=lowerCAmelCase   ,					dtype=torch.float   ) / length
										return input_ids, scores




				def   a__(	self    :				Dict   )->  Optional[int]:

										"""simple docstring"""




										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(5   )

										UpperCAmelCase         =			StoppingCriteriaList(
										    [
										        MaxLengthCriteria(max_length=10   ),
										        MaxTimeCriteria(max_time=0.1   ),
										    ]   )

										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(9   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(10   )
										self.assertTrue(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )




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

										"""simple docstring"""




										UpperCAmelCase         =			MaxLengthCriteria(max_length=10   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(5   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(9   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(10   )
										self.assertTrue(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )




				def   a__(	self    :				Optional[Any]   )->  List[Any]:

										"""simple docstring"""




										UpperCAmelCase         =			MaxNewTokensCriteria(start_length=5   ,					max_new_tokens=5   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(5   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(9   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(10   )
										self.assertTrue(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase         =			StoppingCriteriaList([criteria]   )
										self.assertEqual(criteria_list.max_length   ,					10   )




				def   a__(	self    :				Tuple   )->  Optional[Any]:

										"""simple docstring"""




										UpperCAmelCase       ,       UpperCAmelCase         =			self._get_tensors(5   )

										UpperCAmelCase         =			MaxTimeCriteria(max_time=0.1   )
										self.assertFalse(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )

										UpperCAmelCase         =			MaxTimeCriteria(max_time=0.1   ,					initial_timestamp=time.time() - 0.2   )
										self.assertTrue(criteria(lowerCAmelCase   ,					lowerCAmelCase   )   )





				def   a__(	self    :				int   )->  Any:

										"""simple docstring"""




										validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )   ,					10   )

										with self.assertWarns(lowerCAmelCase   ):
																validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10   )]   )   ,					11   )

										UpperCAmelCase         =			validate_stopping_criteria(StoppingCriteriaList()   ,					11   )

										self.assertEqual(len(lowerCAmelCase   )   ,					1   )





