





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

from ...utils import logging


SCREAMING_SNAKE_CASE_						       =	logging.get_logger(__name__)



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     )			->       Dict:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						nn.functional.normalize(_SCREAMING_SNAKE_CASE     )
      SCREAMING_SNAKE_CASE		=						nn.functional.normalize(_SCREAMING_SNAKE_CASE     )
      return torch.mm(_SCREAMING_SNAKE_CASE			,						normalized_text_embeds.t()     )



class 		UpperCamelCase__			(				lowerCAmelCase_       ):



     '''simple docstring'''

     __snake_case   :     int		     =      CLIPConfig

     __snake_case   :     Any		     =      ["CLIPEncoderLayer"]






     def __init__(							self						:   Union[str, Any]						,lowerCamelCase__						:   CLIPConfig	)					->		Dict:




           '''simple docstring'''


           super().__init__(lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						CLIPVisionModel(config.vision_config	)
           SCREAMING_SNAKE_CASE		=						nn.Linear(config.vision_config.hidden_size						,config.projection_dim						,bias=lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						nn.Parameter(torch.ones(17						,config.projection_dim	)						,requires_grad=lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						nn.Parameter(torch.ones(3						,config.projection_dim	)						,requires_grad=lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						nn.Parameter(torch.ones(17	)						,requires_grad=lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						nn.Parameter(torch.ones(3	)						,requires_grad=lowerCamelCase__	)






     @torch.no_grad()
     def     SCREAMING_SNAKE_CASE__  (							self						:   Optional[Any]						,lowerCamelCase__						:   Optional[Any]						,lowerCamelCase__						:   List[str]	)					->		Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.vision_model(lowerCamelCase__	)[1]  # pooled_output
           SCREAMING_SNAKE_CASE		=						self.visual_projection(lowerCamelCase__	)

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

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

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

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

                 result.append(lowerCamelCase__	)

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

           return images, has_nsfw_concepts






     @torch.no_grad()
     def     SCREAMING_SNAKE_CASE__  (							self						:   Optional[Any]						,lowerCamelCase__						:   torch.FloatTensor						,lowerCamelCase__						:   torch.FloatTensor	)					->		int:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.vision_model(lowerCamelCase__	)[1]  # pooled_output
           SCREAMING_SNAKE_CASE		=						self.visual_projection(lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						cosine_distance(lowerCamelCase__						,self.special_care_embeds	)
           SCREAMING_SNAKE_CASE		=						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
           SCREAMING_SNAKE_CASE		=						0.0

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

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

           return images, has_nsfw_concepts









from PIL import Image



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     )			->       Image:


      '''simple docstring'''


      def brightness(_SCREAMING_SNAKE_CASE     ) -> float:
            return 1_28 + level + (c - 1_28)

      if not -255.0 <= level <= 255.0:
            raise ValueError("""level must be between -255.0 (black) and 255.0 (white)"""     )
      return img.point(_SCREAMING_SNAKE_CASE     )


if __name__ == "__main__":
      # Load image
      with Image.open("""image_data/lena.jpg""") as img:
            # Change brightness to 100
            SCREAMING_SNAKE_CASE_						       =	change_brightness(img, 1_0_0)
            brigt_img.save("""image_data/lena_brightness.png""", format="""png""")


