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(	UpperCamelCase_							,					UpperCamelCase_       )		->	Dict:







 '''simple docstring'''
 UpperCamelCase			  =      nn.functional.normalize(UpperCamelCase_       )
 UpperCamelCase			  =      nn.functional.normalize(UpperCamelCase_       )
 return torch.mm(UpperCamelCase_							,					normalized_text_embeds.t()       )


class SCREAMING_SNAKE_CASE_		(      __lowerCAmelCase		):
   __lowerCAmelCase           =				CLIPConfig

   __lowerCAmelCase           =				["""CLIPEncoderLayer"""]







   def __init__(     self						:						Optional[int]   ,   lowerCamelCase_						:						CLIPConfig				):





    """simple docstring"""


    super().__init__(lowerCamelCase_				)

    UpperCamelCase			  =      CLIPVisionModel(config.vision_config				)
    UpperCamelCase			  =      nn.Linear(config.vision_config.hidden_size   ,   config.projection_dim   ,   bias=lowerCamelCase_				)

    UpperCamelCase			  =      nn.Parameter(torch.ones(17   ,   config.projection_dim				)   ,   requires_grad=lowerCamelCase_				)
    UpperCamelCase			  =      nn.Parameter(torch.ones(3   ,   config.projection_dim				)   ,   requires_grad=lowerCamelCase_				)

    UpperCamelCase			  =      nn.Parameter(torch.ones(17				)   ,   requires_grad=lowerCamelCase_				)
    UpperCamelCase			  =      nn.Parameter(torch.ones(3				)   ,   requires_grad=lowerCamelCase_				)







   @torch.no_grad()
   def 						lowerCamelCase_	(     self						:						List[Any]   ,   lowerCamelCase_						:						Optional[Any]   ,   lowerCamelCase_						:						List[Any]				):





    """simple docstring"""


    UpperCamelCase			  =      self.vision_model(lowerCamelCase_				)[1]  # pooled_output
    UpperCamelCase			  =      self.visual_projection(lowerCamelCase_				)

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

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

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

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

     result.append(lowerCamelCase_				)

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

    return images, has_nsfw_concepts







   @torch.no_grad()
   def 						lowerCamelCase_	(     self						:						Any   ,   lowerCamelCase_						:						torch.FloatTensor   ,   lowerCamelCase_						:						torch.FloatTensor				):





    """simple docstring"""


    UpperCamelCase			  =      self.vision_model(lowerCamelCase_				)[1]  # pooled_output
    UpperCamelCase			  =      self.visual_projection(lowerCamelCase_				)

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

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

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

    return images, has_nsfw_concepts

from __future__ import annotations
class SCREAMING_SNAKE_CASE_		:







   def __init__(     self						:						Dict   ,   lowerCamelCase_						:						str   ,   lowerCamelCase_						:						str				):





    """simple docstring"""


    UpperCamelCase  ,     UpperCamelCase			  =      text, pattern
    UpperCamelCase  ,     UpperCamelCase			  =      len(lowerCamelCase_				), len(lowerCamelCase_				)







   def 						lowerCamelCase_	(     self						:						List[Any]   ,   lowerCamelCase_						:						str				):





    """simple docstring"""


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







   def 						lowerCamelCase_	(     self						:						Union[str, Any]   ,   lowerCamelCase_						:						int				):





    """simple docstring"""


    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						:						Union[str, Any]				):





    """simple docstring"""


    UpperCamelCase			  =      []
    for i in range(self.textLen - self.patLen + 1				):
     UpperCamelCase			  =      self.mismatch_in_text(lowerCamelCase_				)
     if mismatch_index == -1:
      positions.append(lowerCamelCase_				)
     else:
      UpperCamelCase			  =      self.match_in_pattern(self.text[mismatch_index]				)
      UpperCamelCase			  =      (
          mismatch_index - match_index
      )  # shifting index lgtm [py/multiple-definition]
    return positions





_SCREAMING_SNAKE_CASE 		=      """ABAABA"""
_SCREAMING_SNAKE_CASE 		=      """AB"""
_SCREAMING_SNAKE_CASE 		=      BoyerMooreSearch(text, pattern)
_SCREAMING_SNAKE_CASE 		=      bms.bad_character_heuristic()

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