




import numpy as np
from PIL import Image




def 		a_( lowerCamelCase      )				->np.array:






       '''simple docstring'''




       lowercase  :		Union[str, Any]						=      rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
       return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b




def 		a_( lowerCamelCase      )				->np.array:






       '''simple docstring'''




       return (gray > 127) & (gray <= 255)




def 		a_( lowerCamelCase   ,				lowerCamelCase      )				->np.array:






       '''simple docstring'''




       lowercase  :		Optional[Any]						=      np.zeros_like(lowerCamelCase      )
       lowercase  :		Any						=      np.zeros(
           (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1)      )

       # Copy image to padded image
       lowercase  :		List[str]						=      image

       # Iterate over image & apply kernel
       for x in range(image.shape[1]      ):
              for y in range(image.shape[0]      ):
                     lowercase  :		Union[str, Any]						=      (
                         kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]]
                     ).sum()
                     lowercase  :		Any						=      int(summation == 5      )
       return output


# kernel to be applied
lowercase	:      List[Any]				=       np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])

if __name__ == "__main__":
      # read original image
      lowercase	:      Dict				=       np.array(Image.open(r'''..\image_data\lena.jpg'''))
      # Apply erosion operation to a binary image
      lowercase	:      List[str]				=       erosion(grayabinary(rgbagray(image)), structuring_element)
      # Save the output image
      lowercase	:      Optional[Any]				=       Image.fromarray(output).convert('''RGB''')
      pil_img.save('''result_erosion.png''')










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




