






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

from ...utils import logging


snake_case     					=		logging.get_logger(__name__)


class 			SCREAMING_SNAKE_CASE      (      lowerCAmelCase       ):
     '''simple docstring'''


     UpperCamelCase_				:		Optional[int]								=						CLIPConfig

     UpperCamelCase_				:		str								=						['''CLIPEncoderLayer''']


     def __init__(					self							:						Optional[Any]       ,			UpperCAmelCase_							:						CLIPConfig   ):
       super().__init__(UpperCAmelCase_   )

       SCREAMING_SNAKE_CASE							:   List[str]						    =     CLIPVisionModelWithProjection(config.vision_config   )

       SCREAMING_SNAKE_CASE							:   List[str]						    =     nn.Linear(config.vision_config.projection_dim       ,			1   )
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     nn.Linear(config.vision_config.projection_dim       ,			1   )






     @torch.no_grad()
     def 					_A							(					self							:						List[Any]       ,			UpperCAmelCase_							:						int       ,			UpperCAmelCase_							:						Optional[Any]       ,			UpperCAmelCase_							:						Tuple=0.5       ,			UpperCAmelCase_							:						Optional[Any]=0.5   ):
       SCREAMING_SNAKE_CASE							:   int						    =     self.vision_model(UpperCAmelCase_   )[0]

       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     self.p_head(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Tuple						    =     nsfw_detected.flatten()
       SCREAMING_SNAKE_CASE							:   str						    =     nsfw_detected > p_threshold
       SCREAMING_SNAKE_CASE							:   str						    =     nsfw_detected.tolist()

       if any(UpperCAmelCase_   ):
         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(UpperCAmelCase_   ):
         if nsfw_detected_:
           SCREAMING_SNAKE_CASE							:   Tuple						    =     np.zeros(images[idx].shape   )

       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     self.w_head(UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   Tuple						    =     watermark_detected.flatten()
       SCREAMING_SNAKE_CASE							:   int						    =     watermark_detected > w_threshold
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     watermark_detected.tolist()

       if any(UpperCAmelCase_   ):
         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(UpperCAmelCase_   ):
         if watermark_detected_:
           SCREAMING_SNAKE_CASE							:   List[str]						    =     np.zeros(images[idx].shape   )

       return images, nsfw_detected, watermark_detected










'''simple docstring'''





from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


UpperCAmelCase__  			=				logging.get_logger(__name__)  # pylint: disable=invalid-name
class 						a__					(					a_      ,  a_   ):





			'''simple docstring'''

			@register_to_config
			def __init__(  self							:			Any			,    lowerCAmelCase_							:			bool			,    lowerCAmelCase_							:			Optional[int] = None			,    lowerCAmelCase_							:			Optional[int] = None	)      ->		str:
						super().__init__()

						__A=	learnable

						if self.learnable:
									assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
									assert length is not None, "learnable=True requires `length` to be set"

									__A=	torch.zeros(lowerCAmelCase_			,    lowerCAmelCase_	)
						else:
									__A=	None

						__A=	torch.nn.Parameter(lowerCAmelCase_	)


class 						a__					(					a_   ):





			'''simple docstring'''

			A						:				VQModel
			A						:				CLIPTextModel
			A						:				CLIPTokenizer
			A						:				TransformeraDModel
			A						:				LearnedClassifierFreeSamplingEmbeddings
			A						:				VQDiffusionScheduler
			def __init__(  self							:			Optional[int]			,    lowerCAmelCase_							:			VQModel			,    lowerCAmelCase_							:			CLIPTextModel			,    lowerCAmelCase_							:			CLIPTokenizer			,    lowerCAmelCase_							:			TransformeraDModel			,    lowerCAmelCase_							:			VQDiffusionScheduler			,    lowerCAmelCase_							:			LearnedClassifierFreeSamplingEmbeddings			,    )      ->		Tuple:
						super().__init__()

						self.register_modules(
						    vqvae=lowerCAmelCase_			,    transformer=lowerCAmelCase_			,    text_encoder=lowerCAmelCase_			,    tokenizer=lowerCAmelCase_			,    scheduler=lowerCAmelCase_			,    learned_classifier_free_sampling_embeddings=lowerCAmelCase_			,    )
			def 					lowerCAmelCase     (  self							:			int			,    lowerCAmelCase_							:			List[str]			,    lowerCAmelCase_							:			Optional[Any]			,    lowerCAmelCase_							:			List[str]	)      ->		Union[str, Any]:
						__A=	len(lowerCAmelCase_	) if isinstance(lowerCAmelCase_			,    lowerCAmelCase_	) else 1

						# get prompt text embeddings
						__A=	self.tokenizer(
						    lowerCAmelCase_			,    padding='max_length'			,    max_length=self.tokenizer.model_max_length			,    return_tensors='pt'			,    )
						__A=	text_inputs.input_ids

						if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
									__A=	self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]	)
									logger.warning(
									    'The following part of your input was truncated because CLIP can only handle sequences up to'
									    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""	)
									__A=	text_input_ids[:, : self.tokenizer.model_max_length]
						__A=	self.text_encoder(text_input_ids.to(self.device	)	)[0]

						# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
						# While CLIP does normalize the pooled output of the text transformer when combining
						# the image and text embeddings, CLIP does not directly normalize the last hidden state.
						#
						# CLIP normalizing the pooled output.
						# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
						__A=	prompt_embeds / prompt_embeds.norm(dim=-1			,    keepdim=lowerCAmelCase_	)

						# duplicate text embeddings for each generation per prompt
						__A=	prompt_embeds.repeat_interleave(lowerCAmelCase_			,    dim=0	)

						if do_classifier_free_guidance:
									if self.learned_classifier_free_sampling_embeddings.learnable:
												__A=	self.learned_classifier_free_sampling_embeddings.embeddings
												__A=	negative_prompt_embeds.unsqueeze(0	).repeat(lowerCAmelCase_			,    1			,    1	)
									else:
												__A=	[''] * batch_size

												__A=	text_input_ids.shape[-1]
												__A=	self.tokenizer(
												    lowerCAmelCase_			,    padding='max_length'			,    max_length=lowerCAmelCase_			,    truncation=lowerCAmelCase_			,    return_tensors='pt'			,    )
												__A=	self.text_encoder(uncond_input.input_ids.to(self.device	)	)[0]
												# See comment for normalizing text embeddings
												__A=	negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1			,    keepdim=lowerCAmelCase_	)

									# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
									__A=	negative_prompt_embeds.shape[1]
									__A=	negative_prompt_embeds.repeat(1			,    lowerCAmelCase_			,    1	)
									__A=	negative_prompt_embeds.view(batch_size * num_images_per_prompt			,    lowerCAmelCase_			,    -1	)

									# For classifier free guidance, we need to do two forward passes.
									# Here we concatenate the unconditional and text embeddings into a single batch
									# to avoid doing two forward passes
									__A=	torch.cat([negative_prompt_embeds, prompt_embeds]	)

						return prompt_embeds
			@torch.no_grad()
			def __call__(  self							:			int			,    lowerCAmelCase_							:			Union[str, List[str]]			,    lowerCAmelCase_							:			int = 100			,    lowerCAmelCase_							:			float = 5.0			,    lowerCAmelCase_							:			float = 1.0			,    lowerCAmelCase_							:			int = 1			,    lowerCAmelCase_							:			Optional[Union[torch.Generator, List[torch.Generator]]] = None			,    lowerCAmelCase_							:			Optional[torch.FloatTensor] = None			,    lowerCAmelCase_							:			Optional[str] = "pil"			,    lowerCAmelCase_							:			bool = True			,    lowerCAmelCase_							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,    lowerCAmelCase_							:			int = 1			,    )      ->		Union[ImagePipelineOutput, Tuple]:
						if isinstance(lowerCAmelCase_			,    lowerCAmelCase_	):
									__A=	1
						elif isinstance(lowerCAmelCase_			,    lowerCAmelCase_	):
									__A=	len(lowerCAmelCase_	)
						else:
									raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_	)}"""	)

						__A=	batch_size * num_images_per_prompt

						__A=	guidance_scale > 1.0

						__A=	self._encode_prompt(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)

						if (callback_steps is None) or (
						    callback_steps is not None and (not isinstance(lowerCAmelCase_			,    lowerCAmelCase_	) or callback_steps <= 0)
						):
									raise ValueError(
									    F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
									    F""" {type(lowerCAmelCase_	)}."""	)

						# get the initial completely masked latents unless the user supplied it

						__A=	(batch_size, self.transformer.num_latent_pixels)
						if latents is None:
									__A=	self.transformer.num_vector_embeds - 1
									__A=	torch.full(lowerCAmelCase_			,    lowerCAmelCase_	).to(self.device	)
						else:
									if latents.shape != latents_shape:
												raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""	)
									if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
												raise ValueError(
												    'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'
												    F""" {self.transformer.num_vector_embeds - 1} (inclusive)."""	)
									__A=	latents.to(self.device	)

						# set timesteps
						self.scheduler.set_timesteps(lowerCAmelCase_			,    device=self.device	)

						__A=	self.scheduler.timesteps.to(self.device	)

						__A=	latents

						for i, t in enumerate(self.progress_bar(lowerCAmelCase_	)	):
									# expand the sample if we are doing classifier free guidance
									__A=	torch.cat([sample] * 2	) if do_classifier_free_guidance else sample

									# predict the un-noised image
									# model_output == `log_p_x_0`
									__A=	self.transformer(lowerCAmelCase_			,    encoder_hidden_states=lowerCAmelCase_			,    timestep=lowerCAmelCase_	).sample

									if do_classifier_free_guidance:
												__A,	__A=	model_output.chunk(2	)
												__A=	model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
												model_output -= torch.logsumexp(lowerCAmelCase_			,    dim=1			,    keepdim=lowerCAmelCase_	)

									__A=	self.truncate(lowerCAmelCase_			,    lowerCAmelCase_	)

									# remove `log(0)`'s (`-inf`s)
									__A=	model_output.clamp(-70	)

									# compute the previous noisy sample x_t -> x_t-1
									__A=	self.scheduler.step(lowerCAmelCase_			,    timestep=lowerCAmelCase_			,    sample=lowerCAmelCase_			,    generator=lowerCAmelCase_	).prev_sample

									# call the callback, if provided
									if callback is not None and i % callback_steps == 0:
												callback(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)

						__A=	self.vqvae.config.vq_embed_dim
						__A=	(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
						__A=	self.vqvae.quantize.get_codebook_entry(lowerCAmelCase_			,    shape=lowerCAmelCase_	)
						__A=	self.vqvae.decode(lowerCAmelCase_			,    force_not_quantize=lowerCAmelCase_	).sample

						__A=	(image / 2 + 0.5).clamp(0			,    1	)
						__A=	image.cpu().permute(0			,    2			,    3			,    1	).numpy()

						if output_type == "pil":
									__A=	self.numpy_to_pil(lowerCAmelCase_	)

						if not return_dict:
									return (image,)

						return ImagePipelineOutput(images=lowerCAmelCase_	)

			def 					lowerCAmelCase     (  self							:			Any			,    lowerCAmelCase_							:			torch.FloatTensor			,    lowerCAmelCase_							:			float	)      ->		torch.FloatTensor:
						__A,	__A=	torch.sort(lowerCAmelCase_			,    1			,    descending=lowerCAmelCase_	)
						__A=	torch.exp(lowerCAmelCase_	)
						__A=	sorted_p_x_0.cumsum(dim=1	) < truncation_rate

						# Ensure that at least the largest probability is not zeroed out
						__A=	torch.full_like(keep_mask[:, 0:1, :]			,    lowerCAmelCase_	)
						__A=	torch.cat((all_true, keep_mask)			,    dim=1	)
						__A=	keep_mask[:, :-1, :]

						__A=	keep_mask.gather(1			,    indices.argsort(1	)	)

						__A=	log_p_x_0.clone()

						__A=	-torch.inf  # -inf = log(0)

						return rv



