


"""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        lowercase							(		lowerCAmelCase__ :     Union[str, Any]    ,					lowerCAmelCase__ :     str    ,					lowerCAmelCase__ :     Dict=[]			) ->      List[Any]:
		__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(lowerCAmelCase__    ,					mode='''linear_ramp'''    ,					pad_width=lowerCAmelCase__    ,					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        lowercase							(		lowerCAmelCase__ :     Tuple    ,					lowerCAmelCase__ :     Dict    ,					lowerCAmelCase__ :     Any			) ->      List[str]:
		return max(lowerCAmelCase__    ,					min(lowerCAmelCase__    ,					lowerCAmelCase__			)			)

def        lowercase							(		lowerCAmelCase__ :     [int]    ,					lowerCAmelCase__ :     [int]    ,					lowerCAmelCase__ :     [int]			) ->      Union[str, Any]:
		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        lowercase							(		lowerCAmelCase__ :     [int]    ,					lowerCAmelCase__ :     int    ,					lowerCAmelCase__ :     [int]			) ->      Any:
		__a           =			list(lowerCAmelCase__			)
		rect[0] -= overlap
		rect[1] -= overlap
		rect[2] += overlap
		rect[3] += overlap
		__a           =			clamp_rect(lowerCAmelCase__    ,					[0, 0]    ,					[image_size[0], image_size[1]]			)
		return rect

def        lowercase							(		lowerCAmelCase__ :     Optional[int]    ,					lowerCAmelCase__ :     List[str]    ,					lowerCAmelCase__ :     Union[str, Any]    ,					lowerCAmelCase__ :     Any			) ->      Tuple:
		__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(lowerCAmelCase__    ,					(original_slice, 0)			)
		return result

def        lowercase							(		lowerCAmelCase__ :     Tuple    ,					lowerCAmelCase__ :     str			) ->      str:
		__a           =			(original_image_slice * 4, 0, tile.size[0], tile.size[1])
		__a           =			tile.crop(lowerCAmelCase__			)
		return tile

def        lowercase							(		lowerCAmelCase__ :     str    ,					lowerCAmelCase__ :     Any			) ->      Optional[Any]:
		__a           =			n % d
		return n - divisor
class 					__lowerCAmelCase					(   __SCREAMING_SNAKE_CASE       ):


		'''simple docstring'''



		def __init__(  self							, _a							, _a							, _a							, _a							, _a							, _a							, _a = 350							, ):
				super().__init__(
				    vae=_a							, text_encoder=_a							, tokenizer=_a							, unet=_a							, low_res_scheduler=_a							, scheduler=_a							, max_noise_level=_a							, )

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, _a							, _a							, _a							, **_a      ):
				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(_a							, _a							, image.size      )
				__a           =			image.crop(_a      )
				__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							, _a      )
				__a           =			squeeze_tile(_a							, _a							, _a							, _a      )
				__a           =			to_input.size
				__a           =			to_input.resize((tile_size, tile_size)							, Image.BICUBIC      )
				__a           =			super(_a							, self      ).__call__(image=_a							, **_a      ).images[0]
				__a           =			upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)							, Image.BICUBIC      )
				__a           =			unsqueeze_tile(_a							, _a      )
				__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=_a      )							, mode='''L'''							, )
				final_image.paste(
				    _a							, (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4)							, _a      )





		@torch.no_grad()
		def __call__(  self							, _a							, _a							, _a = 75							, _a = 9.0							, _a = 50							, _a = None							, _a = 1							, _a = 0.0							, _a = None							, _a = None							, _a = None							, _a = 1							, _a = 128							, _a = 32							, _a = 32							, ):
				__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(_a      ):
						for x in range(_a      ):
								self._process_tile(
								    _a							, _a							, _a							, _a							, _a							, _a							, _a							, prompt=_a							, num_inference_steps=_a							, guidance_scale=_a							, noise_level=_a							, negative_prompt=_a							, num_images_per_prompt=_a							, eta=_a							, generator=_a							, latents=_a							, )
								current_count += 1
								if callback is not None:
										callback({'''progress''': current_count / total_tile_count, '''image''': final_image}      )
				return final_image







def        lowercase							(		) ->      Union[str, Any]:
		# Run a demo
		__a           =			'''stabilityai/stable-diffusion-x4-upscaler'''
		__a           =			StableDiffusionTiledUpscalePipeline.from_pretrained(lowerCAmelCase__    ,					revision='''fp16'''    ,					torch_dtype=torch.floataa			)
		__a           =			pipe.to('''cuda'''			)
		__a           =			Image.open('''../../docs/source/imgs/diffusers_library.jpg'''			)

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

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


if __name__ == "__main__":
				main()










"""simple docstring"""




import gc
import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CTRLForSequenceClassification,
				    CTRLLMHeadModel,
				    CTRLModel,
				)
class 					__lowerCAmelCase					:


		'''simple docstring'''



		def __init__(  self							, _a							, _a=14							, _a=7							, _a=True							, _a=True							, _a=True							, _a=True							, _a=True							, _a=99							, _a=32							, _a=5							, _a=4							, _a=37							, _a="gelu"							, _a=0.1							, _a=0.1							, _a=512							, _a=16							, _a=2							, _a=0.02							, _a=3							, _a=4							, _a=None							, ):
				__a           =			parent
				__a           =			batch_size
				__a           =			seq_length
				__a           =			is_training
				__a           =			use_token_type_ids
				__a           =			use_input_mask
				__a           =			use_labels
				__a           =			use_mc_token_ids
				__a           =			vocab_size
				__a           =			hidden_size
				__a           =			num_hidden_layers
				__a           =			num_attention_heads
				__a           =			intermediate_size
				__a           =			hidden_act
				__a           =			hidden_dropout_prob
				__a           =			attention_probs_dropout_prob
				__a           =			max_position_embeddings
				__a           =			type_vocab_size
				__a           =			type_sequence_label_size
				__a           =			initializer_range
				__a           =			num_labels
				__a           =			num_choices
				__a           =			scope
				__a           =			self.vocab_size - 1

		def 			__UpperCAmelCase       (  self      ):
				__a           =			ids_tensor([self.batch_size, self.seq_length]							, self.vocab_size      )

				__a           =			None
				if self.use_input_mask:
						__a           =			random_attention_mask([self.batch_size, self.seq_length]      )

				__a           =			None
				if self.use_token_type_ids:
						__a           =			ids_tensor([self.batch_size, self.seq_length]							, self.type_vocab_size      )

				__a           =			None
				if self.use_mc_token_ids:
						__a           =			ids_tensor([self.batch_size, self.num_choices]							, self.seq_length      )

				__a           =			None
				__a           =			None
				__a           =			None
				if self.use_labels:
						__a           =			ids_tensor([self.batch_size]							, self.type_sequence_label_size      )
						__a           =			ids_tensor([self.batch_size, self.seq_length]							, self.num_labels      )
						__a           =			ids_tensor([self.batch_size]							, self.num_choices      )

				__a           =			self.get_config()

				__a           =			ids_tensor([self.num_hidden_layers, self.num_attention_heads]							, 2      )

				return (
				    config,
				    input_ids,
				    input_mask,
				    head_mask,
				    token_type_ids,
				    mc_token_ids,
				    sequence_labels,
				    token_labels,
				    choice_labels,
				)

		def 			__UpperCAmelCase       (  self      ):
				return CTRLConfig(
				    vocab_size=self.vocab_size							, n_embd=self.hidden_size							, n_layer=self.num_hidden_layers							, n_head=self.num_attention_heads							, n_positions=self.max_position_embeddings							, pad_token_id=self.pad_token_id							, )

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, _a							, *_a      ):
				__a           =			CTRLModel(config=_a      )
				model.to(_a      )
				model.eval()

				model(_a							, token_type_ids=_a							, head_mask=_a      )
				model(_a							, token_type_ids=_a      )
				__a           =			model(_a      )
				self.parent.assertEqual(result.last_hidden_state.shape							, (self.batch_size, self.seq_length, self.hidden_size)      )
				self.parent.assertEqual(len(result.past_key_values      )							, config.n_layer      )

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, _a							, *_a      ):
				__a           =			CTRLLMHeadModel(_a      )
				model.to(_a      )
				model.eval()

				__a           =			model(_a							, token_type_ids=_a							, labels=_a      )
				self.parent.assertEqual(result.loss.shape							, ()      )
				self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.seq_length, self.vocab_size)      )

		def 			__UpperCAmelCase       (  self      ):
				__a           =			self.prepare_config_and_inputs()

				(
				    (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     (
				    __a
				)      ,     
				)           =			config_and_inputs

				__a           =			{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

				return config, inputs_dict





		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, *_a      ):
				__a           =			self.num_labels
				__a           =			CTRLForSequenceClassification(_a      )
				model.to(_a      )
				model.eval()
				__a           =			ids_tensor([self.batch_size]							, self.type_sequence_label_size      )
				__a           =			model(_a							, token_type_ids=_a							, labels=_a      )
				self.parent.assertEqual(result.logits.shape							, (self.batch_size, self.num_labels)      )







@require_torch
class 					__lowerCAmelCase					(   __SCREAMING_SNAKE_CASE     ,			__SCREAMING_SNAKE_CASE     ,			__SCREAMING_SNAKE_CASE     ,			unittest.TestCase       ):


		'''simple docstring'''



		__UpperCAmelCase		:			str										=				(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
		__UpperCAmelCase		:			Union[str, Any]										=				(CTRLLMHeadModel,) if is_torch_available() else ()
		__UpperCAmelCase		:			Union[str, Any]										=				(
		    {
		        'feature-extraction': CTRLModel,
		        'text-classification': CTRLForSequenceClassification,
		        'text-generation': CTRLLMHeadModel,
		        'zero-shot': CTRLForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		__UpperCAmelCase		:			Optional[Any]										=				True
		__UpperCAmelCase		:			List[Any]										=				False
		__UpperCAmelCase		:			str										=				False

		def 			__UpperCAmelCase       (  self							, _a							, _a							, _a							, _a							, _a      ):
				if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
						# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
						# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
						# config could not be created.
						return True

				return False

		def 			__UpperCAmelCase       (  self      ):
				__a           =			CTRLModelTester(self      )
				__a           =			ConfigTester(self							, config_class=_a							, n_embd=37      )

		def 			__UpperCAmelCase       (  self      ):
				super().tearDown()
				# clean-up as much as possible GPU memory occupied by PyTorch
				gc.collect()
				torch.cuda.empty_cache()

		def 			__UpperCAmelCase       (  self      ):
				self.config_tester.run_common_tests()

		def 			__UpperCAmelCase       (  self      ):
				__a           =			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_ctrl_model(*_a      )

		def 			__UpperCAmelCase       (  self      ):
				__a           =			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_lm_head_model(*_a      )

		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
		def 			__UpperCAmelCase       (  self      ):
				pass

		@slow
		def 			__UpperCAmelCase       (  self      ):
				for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						__a           =			CTRLModel.from_pretrained(_a      )
						self.assertIsNotNone(_a      )





		@unittest.skip('''The model doesn\'t support left padding'''      )  # and it's not used enough to be worth fixing :)
		def 			__UpperCAmelCase       (  self      ):
				pass







@require_torch
class 					__lowerCAmelCase					(   unittest.TestCase       ):


		'''simple docstring'''



		def 			__UpperCAmelCase       (  self      ):
				super().tearDown()
				# clean-up as much as possible GPU memory occupied by PyTorch
				gc.collect()
				torch.cuda.empty_cache()





		@slow
		def 			__UpperCAmelCase       (  self      ):
				__a           =			CTRLLMHeadModel.from_pretrained('''ctrl'''      )
				model.to(_a      )
				__a           =			torch.tensor(
				    [[11_859, 0, 1_611, 8]]							, dtype=torch.long							, device=_a      )  # Legal the president is
				__a           =			[
				    11_859,
				    0,
				    1_611,
				    8,
				    5,
				    150,
				    26_449,
				    2,
				    19,
				    348,
				    469,
				    3,
				    2_595,
				    48,
				    20_740,
				    246_533,
				    246_533,
				    19,
				    30,
				    5,
				]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

				__a           =			model.generate(_a							, do_sample=_a      )
				self.assertListEqual(output_ids[0].tolist()							, _a      )






