




"""simple docstring"""


import argparse
import math
import os

import torch
from neural_compressor.utils.pytorch import load
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel



def lowercase_				(			)						->    List[Any]:
      lowerCAmelCase__      :			int   =	argparse.ArgumentParser()
      parser.add_argument(
          """-m"""    ,		"""--pretrained_model_name_or_path"""    ,		type=lowercase_    ,		default=lowercase_    ,		required=lowercase_    ,		help="""Path to pretrained model or model identifier from huggingface.co/models."""    ,		)
      parser.add_argument(
          """-c"""    ,		"""--caption"""    ,		type=lowercase_    ,		default="""robotic cat with wings"""    ,		help="""Text used to generate images."""    ,		)
      parser.add_argument(
          """-n"""    ,		"""--images_num"""    ,		type=lowercase_    ,		default=4    ,		help="""How much images to generate."""    ,		)
      parser.add_argument(
          """-s"""    ,		"""--seed"""    ,		type=lowercase_    ,		default=42    ,		help="""Seed for random process."""    ,		)
      parser.add_argument(
          """-ci"""    ,		"""--cuda_id"""    ,		type=lowercase_    ,		default=0    ,		help="""cuda_id."""    ,		)
      lowerCAmelCase__      :			Tuple   =	parser.parse_args()
      return args



def lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase    ,		__UpperCAmelCase				)						->    str:
      if not len(lowercase_				) == rows * cols:
            raise ValueError("""The specified number of rows and columns are not correct."""				)

      lowerCAmelCase__ ,   lowerCAmelCase__      :			Any   =	imgs[0].size
      lowerCAmelCase__      :			str   =	Image.new("""RGB"""    ,		size=(cols * w, rows * h)				)
      lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	grid.size

      for i, img in enumerate(lowercase_				):
            grid.paste(lowercase_    ,		box=(i % cols * w, i // cols * h)				)
      return grid



def lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase="robotic cat with wings"    ,		__UpperCAmelCase=7.5    ,		__UpperCAmelCase=50    ,		__UpperCAmelCase=1    ,		__UpperCAmelCase=42    ,		)						->    Tuple:
      lowerCAmelCase__      :			Union[str, Any]   =	torch.Generator(pipeline.device				).manual_seed(lowercase_				)
      lowerCAmelCase__      :			int   =	pipeline(
          lowercase_    ,		guidance_scale=lowercase_    ,		num_inference_steps=lowercase_    ,		generator=lowercase_    ,		num_images_per_prompt=lowercase_    ,		).images
      lowerCAmelCase__      :			List[str]   =	int(math.sqrt(lowercase_				)				)
      lowerCAmelCase__      :			str   =	image_grid(lowercase_    ,		rows=_rows    ,		cols=num_images_per_prompt // _rows				)
      return grid, images


_A													=      parse_args()
# Load models and create wrapper for stable diffusion
_A													=      CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="""tokenizer""")
_A													=      CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""text_encoder""")
_A													=      AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="""vae""")
_A													=      UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""unet""")

_A													=      StableDiffusionPipeline.from_pretrained(
    args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
_A													=      lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, """best_model.pt""")):
  _A													=      load(args.pretrained_model_name_or_path, model=unet)
  unet.eval()
  setattr(pipeline, """unet""", unet)
else:
  _A													=      unet.to(torch.device("""cuda""", args.cuda_id))
_A													=      pipeline.to(unet.device)
_A													=      generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
grid.save(os.path.join(args.pretrained_model_name_or_path, """{}.png""".format("""_""".join(args.caption.split()))))
_A													=      os.path.join(args.pretrained_model_name_or_path, """_""".join(args.caption.split()))
os.makedirs(dirname, exist_ok=True)
for idx, image in enumerate(images):
  image.save(os.path.join(dirname, """{}.png""".format(idx + 1)))











"""simple docstring"""


from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule



def 	lowercase_				(			__UpperCAmelCase    ,		__UpperCAmelCase    ,		__UpperCAmelCase=1E-12				)						->    Dict:
      lowerCAmelCase__      :			Optional[int]   =	jnp.divide(emb_a.T    ,		jnp.clip(jnp.linalg.norm(__UpperCAmelCase    ,		axis=1				)    ,		a_min=__UpperCAmelCase				)				).T
      lowerCAmelCase__      :			Any   =	jnp.divide(emb_a.T    ,		jnp.clip(jnp.linalg.norm(__UpperCAmelCase    ,		axis=1				)    ,		a_min=__UpperCAmelCase				)				).T
      return jnp.matmul(__UpperCAmelCase    ,		norm_emb_a.T				)


class _lowerCamelCase    (					nn.Module						):
   _lowerCamelCase    :CLIPConfig
   _lowerCamelCase    :jnp.dtype     				=     jnp.floataa






   def 	_lowerCAmelCase   (		self       :		List[str]   )			->						Tuple:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[int]   =	FlaxCLIPVisionModule(self.config.vision_config   )
         lowerCAmelCase__      :			Dict   =	nn.Dense(self.config.projection_dim   ,     use_bias=UpperCamelCase   ,     dtype=self.dtype   )

         lowerCAmelCase__      :			Optional[int]   =	self.param("""concept_embeds"""   ,     jax.nn.initializers.ones   ,     (17, self.config.projection_dim)   )
         lowerCAmelCase__      :			Optional[int]   =	self.param(
             """special_care_embeds"""   ,     jax.nn.initializers.ones   ,     (3, self.config.projection_dim)   )

         lowerCAmelCase__      :			List[Any]   =	self.param("""concept_embeds_weights"""   ,     jax.nn.initializers.ones   ,     (17,)   )
         lowerCAmelCase__      :			List[Any]   =	self.param("""special_care_embeds_weights"""   ,     jax.nn.initializers.ones   ,     (3,)   )






   def __call__(		self       :		str   ,     UpperCamelCase       :		List[Any]   )			->						Union[str, Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Union[str, Any]   =	self.vision_model(UpperCamelCase   )[1]
         lowerCAmelCase__      :			List[Any]   =	self.visual_projection(UpperCamelCase   )

         lowerCAmelCase__      :			str   =	jax_cosine_distance(UpperCamelCase   ,     self.special_care_embeds   )
         lowerCAmelCase__      :			Optional[int]   =	jax_cosine_distance(UpperCamelCase   ,     self.concept_embeds   )

         # increase this value to create a stronger `nfsw` filter
         # at the cost of increasing the possibility of filtering benign image inputs
         lowerCAmelCase__      :			Any   =	0.0

         lowerCAmelCase__      :			List[Any]   =	special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
         lowerCAmelCase__      :			Any   =	jnp.round(UpperCamelCase   ,     3   )
         lowerCAmelCase__      :			List[str]   =	jnp.any(special_scores > 0   ,     axis=1   ,     keepdims=UpperCamelCase   )
         # Use a lower threshold if an image has any special care concept
         lowerCAmelCase__      :			Tuple   =	is_special_care * 0.01

         lowerCAmelCase__      :			List[Any]   =	cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
         lowerCAmelCase__      :			Dict   =	jnp.round(UpperCamelCase   ,     3   )
         lowerCAmelCase__      :			List[str]   =	jnp.any(concept_scores > 0   ,     axis=1   )

         return has_nsfw_concepts






class _lowerCamelCase    (					a_						):
   _lowerCamelCase    :Optional[Any]     				=     CLIPConfig
   _lowerCamelCase    :Dict     				=     "clip_input"
   _lowerCamelCase    :int     				=     FlaxStableDiffusionSafetyCheckerModule






   def __init__(		self       :		int   ,     UpperCamelCase       :		CLIPConfig   ,     UpperCamelCase       :		Optional[Tuple] = None   ,     UpperCamelCase       :		int = 0   ,     UpperCamelCase       :		jnp.dtype = jnp.floataa   ,     UpperCamelCase       :		bool = True   ,     **UpperCamelCase       :		int   ,     )			->						str:

         """simple docstring"""
         if input_shape is None:
               lowerCAmelCase__      :			str   =	(1, 2_24, 2_24, 3)
         lowerCAmelCase__      :			Union[str, Any]   =	self.module_class(config=UpperCamelCase   ,     dtype=UpperCamelCase   ,     **UpperCamelCase   )
         super().__init__(UpperCamelCase   ,     UpperCamelCase   ,     input_shape=UpperCamelCase   ,     seed=UpperCamelCase   ,     dtype=UpperCamelCase   ,     _do_init=_do_init   )






   def 	_lowerCAmelCase   (		self       :		Dict   ,     UpperCamelCase       :		jax.random.KeyArray   ,     UpperCamelCase       :		Tuple   ,     UpperCamelCase       :		FrozenDict = None   )			->						FrozenDict:

         """simple docstring"""
         # init input tensor
         lowerCAmelCase__      :			Union[str, Any]   =	jax.random.normal(UpperCamelCase   ,     UpperCamelCase   )

         lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	jax.random.split(UpperCamelCase   )
         lowerCAmelCase__      :			List[Any]   =	{"""params""": params_rng, """dropout""": dropout_rng}

         lowerCAmelCase__      :			str   =	self.module.init(UpperCamelCase   ,     UpperCamelCase   )["""params"""]

         return random_params






   def __call__(		self       :		Dict   ,     UpperCamelCase       :		Tuple   ,     UpperCamelCase       :		dict = None   ,     )			->						List[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Union[str, Any]   =	jnp.transpose(UpperCamelCase   ,     (0, 2, 3, 1)   )

         return self.module.apply(
             {"""params""": params or self.params}   ,     jnp.array(UpperCamelCase   ,     dtype=jnp.floataa   )   ,     rngs={}   ,     )





