


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

from ...utils import logging


snake_case__		:     List[Any]    				=				logging.get_logger(__name__)


def      _snake_case						(						_snake_case				:			int ,   _snake_case				:			Union[str, Any]			):
      lowerCAmelCase					:	Dict       =   nn.functional.normalize(__SCREAMING_SNAKE_CASE			)
      lowerCAmelCase					:	Optional[int]       =   nn.functional.normalize(__SCREAMING_SNAKE_CASE			)
      return torch.mm(__SCREAMING_SNAKE_CASE ,   normalized_text_embeds.t()			)






class 		snake_case_(       lowercase__			):
     __UpperCamelCase  =					CLIPConfig

     __UpperCamelCase  =					['CLIPEncoderLayer']






     def __init__(	self  :					int					,				UpperCamelCase_  :					Optional[int]				):
           super().__init__(UpperCamelCase_				)

           lowerCAmelCase					:	Tuple       =   CLIPVisionModel(config.vision_config				)
           lowerCAmelCase					:	Optional[int]       =   nn.Linear(config.vision_config.hidden_size					,				config.projection_dim					,				bias=UpperCamelCase_				)

           lowerCAmelCase					:	List[Any]       =   nn.Parameter(torch.ones(1_7					,				config.projection_dim				)					,				requires_grad=UpperCamelCase_				)
           lowerCAmelCase					:	Tuple       =   nn.Parameter(torch.ones(3					,				config.projection_dim				)					,				requires_grad=UpperCamelCase_				)

           lowerCAmelCase					:	str       =   nn.Parameter(torch.ones(1_7				)					,				requires_grad=UpperCamelCase_				)
           lowerCAmelCase					:	List[Any]       =   nn.Parameter(torch.ones(3				)					,				requires_grad=UpperCamelCase_				)






     @torch.no_grad()
     def      lowerCamelCase__     (	self  :					List[str]					,				UpperCamelCase_  :					Union[str, Any]					,				UpperCamelCase_  :					Dict				):
           lowerCAmelCase					:	List[Any]       =   self.vision_model(UpperCamelCase_				)[1]  # pooled_output
           lowerCAmelCase					:	Optional[Any]       =   self.visual_projection(UpperCamelCase_				)

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

           lowerCAmelCase					:	Tuple       =   []
           lowerCAmelCase					:	Union[str, Any]       =   image_embeds.shape[0]
           for i in range(UpperCamelCase_				):
                 lowerCAmelCase					:	Tuple       =   {'''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					:	Optional[int]       =   0.0

                 for concept_idx in range(len(special_cos_dist[0]				)				):
                       lowerCAmelCase					:	str       =   special_cos_dist[i][concept_idx]
                       lowerCAmelCase					:	Union[str, Any]       =   self.special_care_embeds_weights[concept_idx].item()
                       lowerCAmelCase					:	Optional[int]       =   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					:	List[str]       =   0.01

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

                 result.append(UpperCamelCase_				)

           lowerCAmelCase					:	Optional[Any]       =   [len(res['''bad_concepts''']				) > 0 for res in result]

           return images, has_nsfw_concepts






     @torch.no_grad()
     def      lowerCamelCase__     (	self  :					int					,				UpperCamelCase_  :					List[str]					,				UpperCamelCase_  :					Union[str, Any]				):
           lowerCAmelCase					:	Optional[int]       =   self.vision_model(UpperCamelCase_				)[1]  # pooled_output
           lowerCAmelCase					:	Dict       =   self.visual_projection(UpperCamelCase_				)

           lowerCAmelCase					:	Dict       =   cosine_distance(UpperCamelCase_					,				self.special_care_embeds				)
           lowerCAmelCase					:	int       =   cosine_distance(UpperCamelCase_					,				self.concept_embeds				)

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

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

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

           return images, has_nsfw_concepts






"""simple docstring"""





from __future__ import annotations



class 		snake_case_:






     def __init__(	self  :					int					,				UpperCamelCase_  :					str					,				UpperCamelCase_  :					str				):
           lowerCAmelCase,      lowerCAmelCase					:	List[str]       =   text, pattern
           lowerCAmelCase,      lowerCAmelCase					:	Union[str, Any]       =   len(UpperCamelCase_				), len(UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					List[Any]					,				UpperCamelCase_  :					str				):

           for i in range(self.patLen - 1					,				-1					,				-1				):
                 if char == self.pattern[i]:
                       return i
           return -1






     def      lowerCamelCase__     (	self  :					Optional[Any]					,				UpperCamelCase_  :					int				):

           for i in range(self.patLen - 1					,				-1					,				-1				):
                 if self.pattern[i] != self.text[current_pos + i]:
                       return current_pos + i
           return -1






     def      lowerCamelCase__     (	self  :					Dict				):
           # searches pattern in text and returns index positions
           lowerCAmelCase					:	Union[str, Any]       =   []
           for i in range(self.textLen - self.patLen + 1				):
                 lowerCAmelCase					:	str       =   self.mismatch_in_text(UpperCamelCase_				)
                 if mismatch_index == -1:
                       positions.append(UpperCamelCase_				)
                 else:
                       lowerCAmelCase					:	Optional[Any]       =   self.match_in_pattern(self.text[mismatch_index]				)
                       lowerCAmelCase					:	int       =   (
                           mismatch_index - match_index
                       )  # shifting index lgtm [py/multiple-definition]
           return positions



snake_case__		:     str    				=				'''ABAABA'''
snake_case__		:     List[str]    				=				'''AB'''
snake_case__		:     Union[str, Any]    				=				BoyerMooreSearch(text, pattern)
snake_case__		:     Optional[Any]    				=				bms.bad_character_heuristic()

if len(positions) == 0:
 print('''No match found''')
else:
 print('''Pattern found in following positions: ''')
 print(positions)


