




'''simple docstring'''






from __future__ import annotations

from typing import Generic, TypeVar

lowercase	:      Any				=       TypeVar('''T''')

class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):
 pass






class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):
 pass






class   SCREAMING_SNAKE_CASE_		(       Generic[T]				):



 def __init__(  self   ,		A = 10 ):






        '''simple docstring'''




        lowercase  :		list[T]						=      []
        lowercase  :		Dict						=      limit



 def __bool__(  self ):






        '''simple docstring'''




        return bool(self.stack )



 def __str__(  self ):






        '''simple docstring'''




        return str(self.stack )



 def    SCREAMING_SNAKE_CASE(  self   ,		A ):






        '''simple docstring'''




        if len(self.stack ) >= self.limit:
               raise StackOverflowError
        self.stack.append(A )



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        if not self.stack:
               raise StackUnderflowError
        return self.stack.pop()



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        if not self.stack:
               raise StackUnderflowError
        return self.stack[-1]



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        return not bool(self.stack )



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        return self.size() == self.limit



 def    SCREAMING_SNAKE_CASE(  self ):






        '''simple docstring'''




        return len(self.stack )





 def __contains__(  self   ,		A ):






        '''simple docstring'''




        return item in self.stack






def 		a_( )				->None:






       '''simple docstring'''




       lowercase  :		Stack[int]						=      Stack(10      )
       assert bool(lowerCamelCase      ) is False
       assert stack.is_empty() is True
       assert stack.is_full() is False
       assert str(lowerCamelCase      ) == "[]"

       try:
              lowercase  :		List[Any]						=      stack.pop()
              raise AssertionError  # This should not happen
       except StackUnderflowError:
              assert True  # This should happen

       try:
              lowercase  :		int						=      stack.peek()
              raise AssertionError  # This should not happen
       except StackUnderflowError:
              assert True  # This should happen

       for i in range(10      ):
              assert stack.size() == i
              stack.push(lowerCamelCase      )

       assert bool(lowerCamelCase      )
       assert not stack.is_empty()
       assert stack.is_full()
       assert str(lowerCamelCase      ) == str(list(range(10      )      )      )
       assert stack.pop() == 9
       assert stack.peek() == 8

       stack.push(100      )
       assert str(lowerCamelCase      ) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100]      )

       try:
              stack.push(200      )
              raise AssertionError  # This should not happen
       except StackOverflowError:
              assert True  # This should happen

       assert not stack.is_empty()
       assert stack.size() == 10

       assert 5 in stack
       assert 55 not in stack


if __name__ == "__main__":
      test_stack()










'''simple docstring'''






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

from ...utils import logging


lowercase	:      Optional[Any]				=       logging.get_logger(__name__)




def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->Optional[int]:






       '''simple docstring'''




       lowercase  :		List[str]						=      nn.functional.normalize(lowerCamelCase      )
       lowercase  :		Optional[int]						=      nn.functional.normalize(lowerCamelCase      )
       return torch.mm(lowerCamelCase   ,				normalized_text_embeds.t()      )





class   SCREAMING_SNAKE_CASE_		(       lowerCamelCase_				):
 __snake_case	:     List[str]			   =      CLIPConfig

 __snake_case	:     Optional[int]			   =      ["CLIPEncoderLayer"]



 def __init__(  self   ,		A ):






        '''simple docstring'''




        super().__init__(A )

        lowercase  :		Optional[Any]						=      CLIPVisionModel(config.vision_config )
        lowercase  :		Tuple						=      nn.Linear(config.vision_config.hidden_size   ,		config.projection_dim   ,		bias=A )

        lowercase  :		Any						=      nn.Parameter(torch.ones(17   ,		config.projection_dim )   ,		requires_grad=A )
        lowercase  :		int						=      nn.Parameter(torch.ones(3   ,		config.projection_dim )   ,		requires_grad=A )

        lowercase  :		List[str]						=      nn.Parameter(torch.ones(17 )   ,		requires_grad=A )
        lowercase  :		str						=      nn.Parameter(torch.ones(3 )   ,		requires_grad=A )



 @torch.no_grad()
 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Union[str, Any]						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		List[Any]						=      self.visual_projection(A )

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

        lowercase  :		Dict						=      []
        lowercase  :		str						=      image_embeds.shape[0]
        for i in range(A ):
               lowercase  :		List[str]						=      {'''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
               lowercase  :		str						=      0.0

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

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

               result.append(A )

        lowercase  :		Dict						=      [len(res['''bad_concepts'''] ) > 0 for res in result]

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

        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.''' )

        return images, has_nsfw_concepts





 @torch.no_grad()
 def    SCREAMING_SNAKE_CASE(  self   ,		A   ,		A ):






        '''simple docstring'''




        lowercase  :		Dict						=      self.vision_model(A )[1]  # pooled_output
        lowercase  :		Optional[int]						=      self.visual_projection(A )

        lowercase  :		Tuple						=      cosine_distance(A   ,		self.special_care_embeds )
        lowercase  :		List[str]						=      cosine_distance(A   ,		self.concept_embeds )

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

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

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

        lowercase  :		Dict						=      0.0  # black image

        return images, has_nsfw_concepts




