'''simple docstring'''

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

from ...utils import logging


_A      :				str 				=    logging.get_logger(__name__)







def 					UpperCamelCase_						( snake_case_	:	Union[str, Any]						,		snake_case_	:	Optional[Any]				) ->					Dict:






 '''simple docstring'''

 __lowerCAmelCase    							=						nn.functional.normalize(snake_case_				)
 __lowerCAmelCase    							=						nn.functional.normalize(snake_case_				)
 return torch.mm(snake_case_						,		normalized_text_embeds.t()				)







class     _lowercase					(    UpperCAmelCase__      ):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE					:	Optional[Any]				     = CLIPConfig

 _SCREAMING_SNAKE_CASE					:	List[Any]				     = ["""CLIPEncoderLayer"""]
 def __init__(				self       :     Any				,	SCREAMING_SNAKE_CASE__       :     CLIPConfig							)  ->   List[Any]:
  super().__init__(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						CLIPVisionModel(config.vision_config							)
  __lowerCAmelCase    							=						nn.Linear(config.vision_config.hidden_size				,	config.projection_dim				,	bias=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						nn.Parameter(torch.ones(17				,	config.projection_dim							)				,	requires_grad=SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						nn.Parameter(torch.ones(3				,	config.projection_dim							)				,	requires_grad=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						nn.Parameter(torch.ones(17							)				,	requires_grad=SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						nn.Parameter(torch.ones(3							)				,	requires_grad=SCREAMING_SNAKE_CASE__							)
 @torch.no_grad()
 def a (				self       :     int				,	SCREAMING_SNAKE_CASE__       :     Tuple				,	SCREAMING_SNAKE_CASE__       :     Any							)  ->   Union[str, Any]:
  __lowerCAmelCase    							=						self.vision_model(SCREAMING_SNAKE_CASE__							)[1]  # pooled_output
  __lowerCAmelCase    							=						self.visual_projection(SCREAMING_SNAKE_CASE__							)

  # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
  __lowerCAmelCase    							=						cosine_distance(SCREAMING_SNAKE_CASE__				,	self.special_care_embeds							).cpu().float().numpy()
  __lowerCAmelCase    							=						cosine_distance(SCREAMING_SNAKE_CASE__				,	self.concept_embeds							).cpu().float().numpy()

  __lowerCAmelCase    							=						[]
  __lowerCAmelCase    							=						image_embeds.shape[0]
  for i in range(SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase    							=						{"""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
   __lowerCAmelCase    							=						0.0

   for concept_idx in range(len(special_cos_dist[0]							)							):
    __lowerCAmelCase    							=						special_cos_dist[i][concept_idx]
    __lowerCAmelCase    							=						self.special_care_embeds_weights[concept_idx].item()
    __lowerCAmelCase    							=						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]}							)
     __lowerCAmelCase    							=						0.0_1

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

   result.append(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						[len(res["""bad_concepts"""]							) > 0 for res in result]

  for idx, has_nsfw_concept in enumerate(SCREAMING_SNAKE_CASE__							):
   if has_nsfw_concept:
    if torch.is_tensor(SCREAMING_SNAKE_CASE__							) or torch.is_tensor(images[0]							):
     __lowerCAmelCase    							=						torch.zeros_like(images[idx]							)  # black image
    else:
     __lowerCAmelCase    							=						np.zeros(images[idx].shape							)  # black image

  if any(SCREAMING_SNAKE_CASE__							):
   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       :     Dict				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor							)  ->   Tuple:
  __lowerCAmelCase    							=						self.vision_model(SCREAMING_SNAKE_CASE__							)[1]  # pooled_output
  __lowerCAmelCase    							=						self.visual_projection(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						cosine_distance(SCREAMING_SNAKE_CASE__				,	self.special_care_embeds							)
  __lowerCAmelCase    							=						cosine_distance(SCREAMING_SNAKE_CASE__				,	self.concept_embeds							)

  # increase this value to create a stronger `nsfw` filter
  # at the cost of increasing the possibility of filtering benign images
  __lowerCAmelCase    							=						0.0

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

  __lowerCAmelCase    							=						(cos_dist - self.concept_embeds_weights) + special_adjustment
  # concept_scores = concept_scores.round(decimals=3)
  __lowerCAmelCase    							=						torch.any(concept_scores > 0				,	dim=1							)

  __lowerCAmelCase    							=						0.0  # black image

  return images, has_nsfw_concepts







'''simple docstring'''

def 					UpperCamelCase_						( snake_case_	:	int				) ->					int:






 '''simple docstring'''

 if number != int(snake_case_				):
  raise ValueError("""factorial() only accepts integral values"""				)
 if number < 0:
  raise ValueError("""factorial() not defined for negative values"""				)
 __lowerCAmelCase    							=						1
 for i in range(1						,		number + 1				):
  value *= i
 return value







def 					UpperCamelCase_						( snake_case_	:	int				) ->					int:






 '''simple docstring'''

 if not isinstance(snake_case_						,		snake_case_				):
  raise ValueError("""factorial() only accepts integral values"""				)
 if n < 0:
  raise ValueError("""factorial() not defined for negative values"""				)
 return 1 if n == 0 or n == 1 else n * factorial(n - 1				)


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 _A      :				List[Any] 				=    int(input('''Enter a positive integer: ''').strip() or 0)
 print(f'factorial{n} is {factorial(n)}')






