


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__						: Optional[Any]						,						A__						: List[Any]						,						A__						: Any=[]					)     ->    List[Any]:
   lowerCamelCase_						:   Optional[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_						:   int		= np.ones((size_y, size_x)						,						dtype=np.uinta					) * 255
   lowerCamelCase_						:   Any		= np.pad(A__						,						mode="""linear_ramp"""						,						pad_width=A__						,						end_values=0					)

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


def    __lowerCamelCase   (      A__						: Dict						,						A__						: List[Any]						,						A__						: List[Any]					)     ->    List[Any]:
   return max(A__						,						min(A__						,						A__					)					)


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


def    __lowerCamelCase   (      A__						: List[Any]						,						A__						: Tuple						,						A__						: List[str]						,						A__						: Any					)     ->    int:
   lowerCamelCase_						:   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(A__						,						(original_slice, 0)					)
   return result


def    __lowerCamelCase   (      A__						: Optional[Any]						,						A__						: int					)     ->    Optional[int]:
   lowerCamelCase_						:   Tuple		= (original_image_slice * 4, 0, tile.size[0], tile.size[1])
   lowerCamelCase_						:   Optional[Any]		= tile.crop(A__					)
   return tile


def    __lowerCamelCase   (      A__						: List[Any]						,						A__						: int					)     ->    Dict:
   lowerCamelCase_						:   Dict		= n % d
   return n - divisor





class   SCREAMING_SNAKE_CASE_			(a__						):




       '''simple docstring'''



       def __init__(						self				:				int		,				__a				:				AutoencoderKL		,				__a				:				CLIPTextModel		,				__a				:				CLIPTokenizer		,				__a				:				UNetaDConditionModel		,				__a				:				DDPMScheduler		,				__a				:				Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]		,				__a				:				int = 350		,				)					->Dict:
          super().__init__(
              vae=__a		,				text_encoder=__a		,				tokenizer=__a		,				unet=__a		,				low_res_scheduler=__a		,				scheduler=__a		,				max_noise_level=__a		,				)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Optional[int]		,				__a				:				Optional[Any]		,				__a				:				Any		,				__a				:				Optional[int]		,				__a				:				str		,				__a				:				str		,				__a				:				List[str]		,				**__a				:				int							)					->List[str]:
          torch.manual_seed(0							)
          lowerCamelCase_						:   Optional[int]		= (
              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_						:   Optional[Any]		= add_overlap_rect(__a		,				__a		,				image.size							)
          lowerCamelCase_						:   Tuple		= image.crop(__a							)
          lowerCamelCase_						:   Optional[int]		= ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
          lowerCamelCase_						:   Optional[Any]		= translated_slice_x - (original_image_slice / 2)
          lowerCamelCase_						:   int		= max(0		,				__a							)
          lowerCamelCase_						:   int		= squeeze_tile(__a		,				__a		,				__a		,				__a							)
          lowerCamelCase_						:   Optional[int]		= to_input.size
          lowerCamelCase_						:   Union[str, Any]		= to_input.resize((tile_size, tile_size)		,				Image.BICUBIC							)
          lowerCamelCase_						:   List[str]		= super(__a		,				self							).__call__(image=__a		,				**__a							).images[0]
          lowerCamelCase_						:   str		= upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)		,				Image.BICUBIC							)
          lowerCamelCase_						:   List[Any]		= unsqueeze_tile(__a		,				__a							)
          lowerCamelCase_						:   int		= upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)		,				Image.BICUBIC							)
          lowerCamelCase_						:   List[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"""							)
          lowerCamelCase_						:   Optional[Any]		= 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				:				Optional[int]		,				__a				:				Union[str, List[str]]		,				__a				:				Union[PIL.Image.Image, List[PIL.Image.Image]]		,				__a				:				int = 75		,				__a				:				float = 9.0		,				__a				:				int = 50		,				__a				:				Optional[Union[str, List[str]]] = None		,				__a				:				Optional[int] = 1		,				__a				:				float = 0.0		,				__a				:				Optional[torch.Generator] = None		,				__a				:				Optional[torch.FloatTensor] = None		,				__a				:				Optional[Callable[[int, int, torch.FloatTensor], None]] = None		,				__a				:				int = 1		,				__a				:				int = 128		,				__a				:				int = 32		,				__a				:				int = 32		,				)					->Optional[Any]:
          lowerCamelCase_						:   Optional[Any]		= Image.new("""RGB"""		,				(image.size[0] * 4, image.size[1] * 4)							)
          lowerCamelCase_						:   List[Any]		= math.ceil(image.size[0] / tile_size							)
          lowerCamelCase_						:   Optional[Any]		= math.ceil(image.size[1] / tile_size							)
          lowerCamelCase_						:   Any		= tcx * tcy
          lowerCamelCase_						:   Dict		= 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    __lowerCamelCase   (      )     ->    int:
   # Run a demo
   lowerCamelCase_						:   Tuple		= """stabilityai/stable-diffusion-x4-upscaler"""
   lowerCamelCase_						:   str		= StableDiffusionTiledUpscalePipeline.from_pretrained(A__						,						revision="""fp16"""						,						torch_dtype=torch.floataa					)
   lowerCamelCase_						:   int		= pipe.to("""cuda"""					)
   lowerCamelCase_						:   Tuple		= Image.open("""../../docs/source/imgs/diffusers_library.jpg"""					)

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

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


if __name__ == "__main__":
      main()









import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel

from ...utils import logging


snake_case__				:	int					       =					logging.get_logger(__name__)





class   SCREAMING_SNAKE_CASE_			(a__						):




       '''simple docstring'''



       _a   							=							CLIPConfig

       _a   							=							["CLIPEncoderLayer"]



       def __init__(						self				:				Tuple		,				__a				:				CLIPConfig							)					->Union[str, Any]:
          super().__init__(__a							)

          lowerCamelCase_						:   List[Any]		= CLIPVisionModelWithProjection(config.vision_config							)

          lowerCamelCase_						:   int		= nn.Linear(config.vision_config.projection_dim		,				1							)
          lowerCamelCase_						:   int		= nn.Linear(config.vision_config.projection_dim		,				1							)




       @torch.no_grad()
       def 				_lowerCAmelCase							(						self				:				Dict		,				__a				:				List[Any]		,				__a				:				Tuple		,				__a				:				int=0.5		,				__a				:				Optional[Any]=0.5							)					->Union[str, Any]:
          lowerCamelCase_						:   Dict		= self.vision_model(__a							)[0]

          lowerCamelCase_						:   str		= self.p_head(__a							)
          lowerCamelCase_						:   Union[str, Any]		= nsfw_detected.flatten()
          lowerCamelCase_						:   Tuple		= nsfw_detected > p_threshold
          lowerCamelCase_						:   Dict		= nsfw_detected.tolist()

          if any(__a							):
             logger.warning(
                 """Potential NSFW content was detected in one or more images. A black image will be returned instead."""
                 """ Try again with a different prompt and/or seed."""							)

          for idx, nsfw_detected_ in enumerate(__a							):
             if nsfw_detected_:
                lowerCamelCase_						:   int		= np.zeros(images[idx].shape							)

          lowerCamelCase_						:   Union[str, Any]		= self.w_head(__a							)
          lowerCamelCase_						:   List[str]		= watermark_detected.flatten()
          lowerCamelCase_						:   Dict		= watermark_detected > w_threshold
          lowerCamelCase_						:   Optional[int]		= watermark_detected.tolist()

          if any(__a							):
             logger.warning(
                 """Potential watermarked content was detected in one or more images. A black image will be returned instead."""
                 """ Try again with a different prompt and/or seed."""							)

          for idx, watermark_detected_ in enumerate(__a							):
             if watermark_detected_:
                lowerCamelCase_						:   Tuple		= np.zeros(images[idx].shape							)

          return images, nsfw_detected, watermark_detected





