

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

from ...utils import logging


__UpperCAmelCase    				=     logging.get_logger(__name__)







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      Optional[int]:

     """simple docstring"""







     _lowerCAmelCase   :					List[Any]        =    nn.functional.normalize(__lowerCAmelCase				)
     _lowerCAmelCase   :					List[str]        =    nn.functional.normalize(__lowerCAmelCase				)
     return torch.mm(__lowerCAmelCase		,							normalized_text_embeds.t()				)





class UpperCAmelCase_    ( UpperCAmelCase__ ):



 """simple docstring"""







 _lowercase     :					Optional[Any]      =						CLIPConfig

 _lowercase     :					Dict      =						["CLIPEncoderLayer"]

 def __init__(		self :	str     ,						A_ :	CLIPConfig       ):






      '''simple docstring'''




      super().__init__(lowerCamelCase__       )

      _lowerCAmelCase   :					Optional[Any]        =    CLIPVisionModel(config.vision_config       )
      _lowerCAmelCase   :					List[str]        =    nn.Linear(config.vision_config.hidden_size     ,						config.projection_dim     ,						bias=lowerCamelCase__       )

      _lowerCAmelCase   :					Any        =    nn.Parameter(torch.ones(1_7     ,						config.projection_dim       )     ,						requires_grad=lowerCamelCase__       )
      _lowerCAmelCase   :					Dict        =    nn.Parameter(torch.ones(3     ,						config.projection_dim       )     ,						requires_grad=lowerCamelCase__       )

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

 @torch.no_grad()
 def    __magic_name__       (		self :	Union[str, Any]     ,						A_ :	List[str]     ,						A_ :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Union[str, Any]        =    self.vision_model(lowerCamelCase__       )[1]  # pooled_output
      _lowerCAmelCase   :					Union[str, Any]        =    self.visual_projection(lowerCamelCase__       )

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

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

           for concept_idx in range(len(special_cos_dist[0]       )       ):
                _lowerCAmelCase   :					Dict        =    special_cos_dist[i][concept_idx]
                _lowerCAmelCase   :					str        =    self.special_care_embeds_weights[concept_idx].item()
                _lowerCAmelCase   :					List[str]        =    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   :					Tuple        =    0.01

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

           result.append(lowerCamelCase__       )

      _lowerCAmelCase   :					Union[str, Any]        =    [len(res["bad_concepts"]       ) > 0 for res in result]

      return images, has_nsfw_concepts


 @torch.no_grad()
 def    __magic_name__       (		self :	Optional[int]     ,						A_ :	torch.FloatTensor     ,						A_ :	torch.FloatTensor       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    self.vision_model(lowerCamelCase__       )[1]  # pooled_output
      _lowerCAmelCase   :					Optional[Any]        =    self.visual_projection(lowerCamelCase__       )

      _lowerCAmelCase   :					Any        =    cosine_distance(lowerCamelCase__     ,						self.special_care_embeds       )
      _lowerCAmelCase   :					Optional[int]        =    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
      _lowerCAmelCase   :					Union[str, Any]        =    0.0

      _lowerCAmelCase   :					List[str]        =    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   :					Dict        =    special_care * 0.01
      _lowerCAmelCase   :					Union[str, Any]        =    special_adjustment.unsqueeze(1       ).expand(-1     ,						cos_dist.shape[1]       )

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

      return images, has_nsfw_concepts









def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      "list[int]":

     """simple docstring"""







     if upper_limit < 0:
          raise ValueError("Limit for the Catalan sequence must be ≥ 0"				)

     _lowerCAmelCase   :					Optional[Any]        =    [0] * (upper_limit + 1)

     # Base case: C(0) = C(1) = 1
     _lowerCAmelCase   :					Optional[int]        =    1
     if upper_limit > 0:
          _lowerCAmelCase   :					Any        =    1

     # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
     for i in range(2		,							upper_limit + 1				):
          for j in range(SCREAMING_SNAKE_CASE				):
               catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]

     return catalan_list


if __name__ == "__main__":
  print('\n********* Catalan Numbers Using Dynamic Programming ************\n')
  print('\n*** Enter -1 at any time to quit ***')
  print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='')
  try:
    while True:
      __UpperCAmelCase    				=     int(input().strip())
      if N < 0:
        print('\n********* Goodbye!! ************')
        break
      else:
        print(f'''The Catalan numbers from 0 through {N} are:''')
        print(catalan_numbers(N))
        print('Try another upper limit for the sequence: ', end='')
  except (NameError, ValueError):
    print('\n********* Invalid input, goodbye! ************\n')

  import doctest

  doctest.testmod()






