"""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      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=[] ):






							"""simple docstring"""





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

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






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							return max(UpperCamelCase__				,			min(UpperCamelCase__				,			UpperCamelCase__ ) )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""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      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





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






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							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      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





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






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							n % d
							return n - divisor
class 			UpperCamelCase__(	__A       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 3_50						,)    -> Optional[int]:
													super().__init__(
													    vae=__UpperCAmelCase						,text_encoder=__UpperCAmelCase						,tokenizer=__UpperCAmelCase						,unet=__UpperCAmelCase						,low_res_scheduler=__UpperCAmelCase						,scheduler=__UpperCAmelCase						,max_noise_level=__UpperCAmelCase						,)





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> Dict:
													torch.manual_seed(0   )
													A__		   =							(
													    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   ),
													)
													A__		   =							add_overlap_rect(__UpperCAmelCase						,__UpperCAmelCase						,image.size   )
													A__		   =							image.crop(__UpperCAmelCase   )
													A__		   =							((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
													A__		   =							translated_slice_x - (original_image_slice / 2)
													A__		   =							max(0						,__UpperCAmelCase   )
													A__		   =							squeeze_tile(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )
													A__		   =							to_input.size
													A__		   =							to_input.resize((tile_size, tile_size)						,Image.BICUBIC   )
													A__		   =							super(__UpperCAmelCase						,self   ).__call__(image=__UpperCAmelCase						,**__UpperCAmelCase   ).images[0]
													A__		   =							upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)						,Image.BICUBIC   )
													A__		   =							unsqueeze_tile(__UpperCAmelCase						,__UpperCAmelCase   )
													A__		   =							upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)						,Image.BICUBIC   )
													A__		   =							[]
													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'   )
													A__		   =							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						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 75						,__UpperCAmelCase = 9.0						,__UpperCAmelCase = 50						,__UpperCAmelCase = None						,__UpperCAmelCase = 1						,__UpperCAmelCase = 0.0						,__UpperCAmelCase = None						,__UpperCAmelCase = None						,__UpperCAmelCase = None						,__UpperCAmelCase = 1						,__UpperCAmelCase = 1_28						,__UpperCAmelCase = 32						,__UpperCAmelCase = 32						,)    -> Union[str, Any]:
													A__		   =							Image.new('RGB'						,(image.size[0] * 4, image.size[1] * 4)   )
													A__		   =							math.ceil(image.size[0] / tile_size   )
													A__		   =							math.ceil(image.size[1] / tile_size   )
													A__		   =							tcx * tcy
													A__		   =							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      UpperCAmelCase    (		):






							"""simple docstring"""





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

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

							A__		   =							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"""




import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
				from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
				from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
				from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__lowerCamelCase							 =     DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__lowerCamelCase							 =     "main"
# Default branch name
__lowerCamelCase							 =     "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
__lowerCamelCase							 =     "aaaaaaa"
# This commit does not exist, so we should 404.

__lowerCamelCase							 =     "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
__lowerCamelCase							 =     "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Welcome!' )
							yield
							print('Bye!' )






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Bonjour!' )
							yield
							print('Au revoir!' )
class 			UpperCamelCase__(	unittest.TestCase       ):





						def  snake_case__		(				self   )    -> List[str]:
													# If the spec is missing, importlib would not be able to import the module dynamically.
													assert transformers.__spec__ is not None
													assert importlib.util.find_spec('transformers'   ) is not None






class 			UpperCamelCase__(	unittest.TestCase       ):





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													with ContextManagers([]   ):
																				print('Transformers are awesome!'   )
													# The print statement adds a new line at the end of the output
													self.assertEqual(mock_stdout.getvalue()						,'Transformers are awesome!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> List[str]:
													with ContextManagers([context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Welcome!\nTransformers are awesome!\nBye!\n'   )





						@unittest.mock.patch('sys.stdout'						,new_callable=io.StringIO   )
						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Any:
													with ContextManagers([context_fr(), context_en()]   ):
																				print('Transformers are awesome!'   )
													# The output should be wrapped with an English and French welcome and goodbye
													self.assertEqual(mock_stdout.getvalue()						,'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n'   )





						@require_torch
						def  snake_case__		(				self   )    -> Union[str, Any]:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_tf
						def  snake_case__		(				self   )    -> str:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_flax
						def  snake_case__		(				self   )    -> List[Any]:
													# Flax models don't have labels
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )





