"""simple docstring"""






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

from ...utils import logging


UpperCamelCase     					=     logging.get_logger(__name__)

def  lowerCAmelCase_      (_SCREAMING_SNAKE_CASE	:Any		,			_SCREAMING_SNAKE_CASE	:List[str]  )				-> Optional[int]:
						a_							:			Optional[Any]     		=					nn.functional.normalize(_SCREAMING_SNAKE_CASE  )
						a_							:			Optional[Any]     		=					nn.functional.normalize(_SCREAMING_SNAKE_CASE  )
						return torch.mm(_SCREAMING_SNAKE_CASE		,			normalized_text_embeds.t()  )



class   UpperCAmelCase__				(    A__			):


	"""simple docstring"""
	lowerCAmelCase__    :					Dict						      =							CLIPConfig

	lowerCAmelCase__    :					List[Any]						      =							["""CLIPEncoderLayer"""]







	def __init__(			self       ,     _SCREAMING_SNAKE_CASE )    ->	str:
							super().__init__(_lowerCAmelCase )

							a_							:			str     		=					CLIPVisionModel(config.vision_config )
							a_							:			Optional[Any]     		=					nn.Linear(config.vision_config.hidden_size       ,     config.projection_dim       ,     bias=_lowerCAmelCase )

							a_							:			str     		=					nn.Parameter(torch.ones(1_7       ,     config.projection_dim )       ,     requires_grad=_lowerCAmelCase )
							a_							:			List[str]     		=					nn.Parameter(torch.ones(3       ,     config.projection_dim )       ,     requires_grad=_lowerCAmelCase )

							a_							:			Tuple     		=					nn.Parameter(torch.ones(1_7 )       ,     requires_grad=_lowerCAmelCase )
							a_							:			Tuple     		=					nn.Parameter(torch.ones(3 )       ,     requires_grad=_lowerCAmelCase )







	@torch.no_grad()
	def       A    (			self       ,     _SCREAMING_SNAKE_CASE       ,     _SCREAMING_SNAKE_CASE )    ->	Optional[int]:
							a_							:			Dict     		=					self.vision_model(_lowerCAmelCase )[1]  # pooled_output
							a_							:			Any     		=					self.visual_projection(_lowerCAmelCase )

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							a_							:			int     		=					cosine_distance(_lowerCAmelCase       ,     self.special_care_embeds ).cpu().float().numpy()
							a_							:			Optional[int]     		=					cosine_distance(_lowerCAmelCase       ,     self.concept_embeds ).cpu().float().numpy()

							a_							:			int     		=					[]
							a_							:			Dict     		=					image_embeds.shape[0]
							for i in range(_lowerCAmelCase ):
													a_							:			Union[str, Any]     		=					{"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}

													# increase this value to create a stronger `nfsw` filter
													# at the cost of increasing the possibility of filtering benign images
													a_							:			List[Any]     		=					0.0

													for concept_idx in range(len(special_cos_dist[0] ) ):
																			a_							:			Union[str, Any]     		=					special_cos_dist[i][concept_idx]
																			a_							:			Tuple     		=					self.special_care_embeds_weights[concept_idx].item()
																			a_							:			Optional[Any]     		=					round(concept_cos - concept_threshold + adjustment       ,     3 )
																			if result_img["special_scores"][concept_idx] > 0:
																									result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} )
																									a_							:			List[Any]     		=					0.0_1

													for concept_idx in range(len(cos_dist[0] ) ):
																			a_							:			str     		=					cos_dist[i][concept_idx]
																			a_							:			List[str]     		=					self.concept_embeds_weights[concept_idx].item()
																			a_							:			Optional[int]     		=					round(concept_cos - concept_threshold + adjustment       ,     3 )
																			if result_img["concept_scores"][concept_idx] > 0:
																									result_img["bad_concepts"].append(_lowerCAmelCase )

													result.append(_lowerCAmelCase )

							a_							:			Any     		=					[len(res["bad_concepts"] ) > 0 for res in result]

							for idx, has_nsfw_concept in enumerate(_lowerCAmelCase ):
													if has_nsfw_concept:
																			if torch.is_tensor(_lowerCAmelCase ) or torch.is_tensor(images[0] ):
																									a_							:			List[str]     		=					torch.zeros_like(images[idx] )  # black image
																			else:
																									a_							:			int     		=					np.zeros(images[idx].shape )  # black image

							if any(_lowerCAmelCase ):
													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." )

							return images, has_nsfw_concepts







	@torch.no_grad()
	def       A    (			self       ,     _SCREAMING_SNAKE_CASE       ,     _SCREAMING_SNAKE_CASE )    ->	Optional[int]:
							a_							:			List[str]     		=					self.vision_model(_lowerCAmelCase )[1]  # pooled_output
							a_							:			int     		=					self.visual_projection(_lowerCAmelCase )

							a_							:			str     		=					cosine_distance(_lowerCAmelCase       ,     self.special_care_embeds )
							a_							:			int     		=					cosine_distance(_lowerCAmelCase       ,     self.concept_embeds )

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							a_							:			List[str]     		=					0.0

							a_							:			Dict     		=					special_cos_dist - self.special_care_embeds_weights + adjustment
							# special_scores = special_scores.round(decimals=3)
							a_							:			str     		=					torch.any(special_scores > 0       ,     dim=1 )
							a_							:			Union[str, Any]     		=					special_care * 0.0_1
							a_							:			Tuple     		=					special_adjustment.unsqueeze(1 ).expand(-1       ,     cos_dist.shape[1] )

							a_							:			List[Any]     		=					(cos_dist - self.concept_embeds_weights) + special_adjustment
							# concept_scores = concept_scores.round(decimals=3)
							a_							:			List[Any]     		=					torch.any(concept_scores > 0       ,     dim=1 )

							a_							:			Optional[Any]     		=					0.0  # black image

							return images, has_nsfw_concepts





"""simple docstring"""






import unittest

import torch

from diffusers import DDIMScheduler, TextToVideoZeroPipeline
from diffusers.utils import load_pt, require_torch_gpu, slow

from ..test_pipelines_common import assert_mean_pixel_difference
@slow
@require_torch_gpu
class   UpperCAmelCase__				(    unittest.TestCase			):


	"""simple docstring"""







	def       A    (			self )    ->	List[str]:
							a_							:			List[str]     		=					"runwayml/stable-diffusion-v1-5"
							a_							:			Optional[int]     		=					TextToVideoZeroPipeline.from_pretrained(_SCREAMING_SNAKE_CASE       ,     torch_dtype=torch.floataa ).to("cuda" )
							a_							:			Dict     		=					DDIMScheduler.from_config(pipe.scheduler.config )
							a_							:			Optional[Any]     		=					torch.Generator(device="cuda" ).manual_seed(0 )

							a_							:			List[Any]     		=					"A bear is playing a guitar on Times Square"
							a_							:			List[Any]     		=					pipe(prompt=_SCREAMING_SNAKE_CASE       ,     generator=_SCREAMING_SNAKE_CASE ).images

							a_							:			Optional[int]     		=					load_pt(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text-to-video/A bear is playing a guitar on Times Square.pt" )

							assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE       ,     _SCREAMING_SNAKE_CASE )




