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=[]						):
						SCREAMING_SNAKE_CASE							:    int							=							size[0] - overlap_pixels * 2
						SCREAMING_SNAKE_CASE							:    Optional[Any]							=							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
						SCREAMING_SNAKE_CASE							:    List[str]							=							np.ones((size_y, size_x)		,  dtype=np.uinta						) * 255
						SCREAMING_SNAKE_CASE							:    Tuple							=							np.pad(_lowercase		,  mode='''linear_ramp'''		,  pad_width=_lowercase		,  end_values=0						)

						if "l" in remove_borders:
												SCREAMING_SNAKE_CASE							:    List[Any]							=							mask[:, overlap_pixels : mask.shape[1]]
						if "r" in remove_borders:
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							mask[:, 0 : mask.shape[1] - overlap_pixels]
						if "t" in remove_borders:
												SCREAMING_SNAKE_CASE							:    Dict							=							mask[overlap_pixels : mask.shape[0], :]
						if "b" in remove_borders:
												SCREAMING_SNAKE_CASE							:    str							=							mask[0 : mask.shape[0] - overlap_pixels, :]
						return mask
def       A	(    _lowercase		,  _lowercase		,  _lowercase						):
						return max(_lowercase		,  min(_lowercase		,  _lowercase						)						)
def       A	(    _lowercase		,  _lowercase		,  _lowercase						):
						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						):
						SCREAMING_SNAKE_CASE							:    Dict							=							list(_lowercase						)
						rect[0] -= overlap
						rect[1] -= overlap
						rect[2] += overlap
						rect[3] += overlap
						SCREAMING_SNAKE_CASE							:    List[Any]							=							clamp_rect(_lowercase		,  [0, 0]		,  [image_size[0], image_size[1]]						)
						return rect
def       A	(    _lowercase		,  _lowercase		,  _lowercase		,  _lowercase						):
						SCREAMING_SNAKE_CASE							:    List[Any]							=							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						):
						SCREAMING_SNAKE_CASE							:    List[str]							=							(original_image_slice * 4, 0, tile.size[0], tile.size[1])
						SCREAMING_SNAKE_CASE							:    Any							=							tile.crop(_lowercase						)
						return tile
def       A	(    _lowercase		,  _lowercase						):
						SCREAMING_SNAKE_CASE							:    str							=							n % d
						return n - divisor





class 					lowercase__						(   UpperCamelCase_):


						def __init__(       self	:				Optional[Any]    ,		UpperCamelCase__	:				AutoencoderKL    ,		UpperCamelCase__	:				CLIPTextModel    ,		UpperCamelCase__	:				CLIPTokenizer    ,		UpperCamelCase__	:				UNetaDConditionModel    ,		UpperCamelCase__	:				DDPMScheduler    ,		UpperCamelCase__	:				Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]    ,		UpperCamelCase__	:				int = 350    ,		):





												'''simple docstring'''





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


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





												'''simple docstring'''





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





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Any							=							Image.new('''RGB'''    ,		(image.size[0] * 4, image.size[1] * 4)						)
												SCREAMING_SNAKE_CASE							:    Optional[int]							=							math.ceil(image.size[0] / tile_size						)
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							math.ceil(image.size[1] / tile_size						)
												SCREAMING_SNAKE_CASE							:    str							=							tcx * tcy
												SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							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       A	(    ):
						# Run a demo
						SCREAMING_SNAKE_CASE							:    Optional[int]							=							'''stabilityai/stable-diffusion-x4-upscaler'''
						SCREAMING_SNAKE_CASE							:    Dict							=							StableDiffusionTiledUpscalePipeline.from_pretrained(_lowercase		,  revision='''fp16'''		,  torch_dtype=torch.floataa						)
						SCREAMING_SNAKE_CASE							:    Dict							=							pipe.to('''cuda'''						)
						SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							Image.open('''../../docs/source/imgs/diffusers_library.jpg'''						)

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

						SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							pipe(image=_lowercase		,  prompt='''Black font, white background, vector'''		,  noise_level=40		,  callback=_lowercase						)
						final_image.save('''diffusers_library.jpg'''						)


if __name__ == "__main__":
					main()






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402





class 					lowercase__						(   unittest.TestCase):


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    Dict							=							0


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''						)
												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    str							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Tuple							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Dict							=							CLIPConfig()

																		# Create a dummy config file with image_proceesor_type
																		SCREAMING_SNAKE_CASE							:    Dict							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		SCREAMING_SNAKE_CASE							:    List[str]							=							Path(UpperCamelCase__						) / '''config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																		json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																		# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						).to_dict()

																		config_dict.pop('''image_processor_type'''						)
																		SCREAMING_SNAKE_CASE							:    str							=							CLIPImageProcessor(**UpperCamelCase__						)

																		# save in new folder
																		model_config.save_pretrained(UpperCamelCase__						)
																		config.save_pretrained(UpperCamelCase__						)

																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)

																		# make sure private variable is not incorrectly saved
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							json.loads(config.to_json_string()						)
																		self.assertTrue('''_processor_class''' not in dict_as_saved						)

												self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				Tuple						):





												'''simple docstring'''





												with tempfile.TemporaryDirectory() as tmpdirname:
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																		json.dump(
																		    {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)

																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																		self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)


						def        __A       (       self	:				int						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''clip-base is not a local folder and is not a valid model identifier'''						):
																		SCREAMING_SNAKE_CASE							:    List[str]							=							AutoImageProcessor.from_pretrained('''clip-base'''						)


						def        __A       (       self	:				List[str]						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''						):
																		SCREAMING_SNAKE_CASE							:    Tuple							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		revision='''aaaaaa'''						)


						def        __A       (       self	:				Dict						):





												'''simple docstring'''





												with self.assertRaisesRegex(
												    UpperCamelCase__    ,		'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''    ,		):
																		SCREAMING_SNAKE_CASE							:    Dict							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''						)


						def        __A       (       self	:				List[Any]						):





												'''simple docstring'''





												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(UpperCamelCase__						):
																		SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)

												SCREAMING_SNAKE_CASE							:    List[Any]							=							AutoImageProcessor.from_pretrained(
												    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)

												# Test image processor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																		image_processor.save_pretrained(UpperCamelCase__						)
																		SCREAMING_SNAKE_CASE							:    Optional[int]							=							AutoImageProcessor.from_pretrained(UpperCamelCase__    ,		trust_remote_code=UpperCamelCase__						)
												self.assertEqual(reloaded_image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)


						def        __A       (       self	:				Optional[Any]						):





												'''simple docstring'''





												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# Trying to register something existing in the Transformers library will raise an error
																		with self.assertRaises(UpperCamelCase__						):
																								AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)

																		with tempfile.TemporaryDirectory() as tmpdirname:
																								SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							Path(UpperCamelCase__						) / '''preprocessor_config.json'''
																								SCREAMING_SNAKE_CASE							:    Any							=							Path(UpperCamelCase__						) / '''config.json'''
																								json.dump(
																								    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}    ,		open(UpperCamelCase__    ,		'''w'''						)    ,		)
																								json.dump({'''model_type''': '''clip'''}    ,		open(UpperCamelCase__    ,		'''w'''						)						)

																								SCREAMING_SNAKE_CASE							:    Tuple							=							CustomImageProcessor.from_pretrained(UpperCamelCase__						)

																		# Now that the config is registered, it can be used as any other config with the auto-API
																		with tempfile.TemporaryDirectory() as tmp_dir:
																								image_processor.save_pretrained(UpperCamelCase__						)
																								SCREAMING_SNAKE_CASE							:    Any							=							AutoImageProcessor.from_pretrained(UpperCamelCase__						)
																								self.assertIsInstance(UpperCamelCase__    ,		UpperCamelCase__						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



						def        __A       (       self	:				Any						):





												'''simple docstring'''





												class 					lowercase__						(   UpperCamelCase_):
																		UpperCamelCase_     =		True

												try:
																		AutoConfig.register('''custom'''    ,		UpperCamelCase__						)
																		AutoImageProcessor.register(UpperCamelCase__    ,		UpperCamelCase__						)
																		# If remote code is not set, the default is to use local
																		SCREAMING_SNAKE_CASE							:    str							=							AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote code is disabled, we load the local one.
																		SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(image_processor.is_local						)

																		# If remote is enabled, we load from the Hub
																		SCREAMING_SNAKE_CASE							:    Optional[Any]							=							AutoImageProcessor.from_pretrained(
																		    '''hf-internal-testing/test_dynamic_image_processor'''    ,		trust_remote_code=UpperCamelCase__						)
																		self.assertEqual(image_processor.__class__.__name__    ,		'''NewImageProcessor'''						)
																		self.assertTrue(not hasattr(UpperCamelCase__    ,		'''is_local'''						)						)

												finally:
																		if "custom" in CONFIG_MAPPING._extra_content:
																								del CONFIG_MAPPING._extra_content["custom"]
																		if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
																								del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]





