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

from ...utils import logging


_lowerCamelCase					   =logging.get_logger(__name__)





def     _a					(						lowerCamelCase,	lowerCamelCase							):
 lowerCamelCase		:	Optional[Any]							=      nn.functional.normalize(lowerCamelCase							)
 lowerCamelCase		:	List[Any]							=      nn.functional.normalize(lowerCamelCase							)
 return torch.mm(lowerCamelCase,	normalized_text_embeds.t()							)





class 							A__		(	__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase				:    Union[str, Any]           =			CLIPConfig

      _UpperCAmelCase				:    Any           =			["""CLIPEncoderLayer"""]
      def __init__(      self    ,  __magic_name__      ):
       super().__init__(__magic_name__      )

       lowerCamelCase		:	Dict							=      CLIPVisionModel(config.vision_config      )
       lowerCamelCase		:	int							=      nn.Linear(config.vision_config.hidden_size    ,  config.projection_dim    ,  bias=__magic_name__      )

       lowerCamelCase		:	Optional[int]							=      nn.Parameter(torch.ones(1_7    ,  config.projection_dim      )    ,  requires_grad=__magic_name__      )
       lowerCamelCase		:	str							=      nn.Parameter(torch.ones(3    ,  config.projection_dim      )    ,  requires_grad=__magic_name__      )

       lowerCamelCase		:	Tuple							=      nn.Parameter(torch.ones(1_7      )    ,  requires_grad=__magic_name__      )
       lowerCamelCase		:	Optional[int]							=      nn.Parameter(torch.ones(3      )    ,  requires_grad=__magic_name__      )
      @torch.no_grad()
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__      ):
       lowerCamelCase		:	List[str]							=      self.vision_model(__magic_name__      )[1]  # pooled_output
       lowerCamelCase		:	List[str]							=      self.visual_projection(__magic_name__      )

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

       lowerCamelCase		:	List[str]							=      []
       lowerCamelCase		:	Any							=      image_embeds.shape[0]
       for i in range(__magic_name__      ):
        lowerCamelCase		:	Optional[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		:	Tuple							=      0.0

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

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

        result.append(__magic_name__      )

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

       return images, has_nsfw_concepts






      @torch.no_grad()
      def 						UpperCamelCase__							(      self    ,  __magic_name__    ,  __magic_name__      ):
       lowerCamelCase		:	List[str]							=      self.vision_model(__magic_name__      )[1]  # pooled_output
       lowerCamelCase		:	str							=      self.visual_projection(__magic_name__      )

       lowerCamelCase		:	str							=      cosine_distance(__magic_name__    ,  self.special_care_embeds      )
       lowerCamelCase		:	Optional[int]							=      cosine_distance(__magic_name__    ,  self.concept_embeds      )

       # increase this value to create a stronger `nsfw` filter
       # at the cost of increasing the possibility of filtering benign images
       lowerCamelCase		:	Any							=      0.0

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

       lowerCamelCase		:	int							=      (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






import json
import sys





def     _a					(						lowerCamelCase,	lowerCamelCase							):
 with open(lowerCamelCase,	encoding="""utf-8"""							) as f:
  lowerCamelCase		:	List[Any]							=      json.load(lowerCamelCase							)

 lowerCamelCase		:	Optional[Any]							=      ["""<details>""", """<summary>Show updated benchmarks!</summary>""", """ """]

 for benchmark_name in sorted(lowerCamelCase							):
  lowerCamelCase		:	List[Any]							=      results[benchmark_name]

  lowerCamelCase		:	Union[str, Any]							=      benchmark_name.split("""/"""							)[-1]
  output_md.append(F'''### Benchmark: {benchmark_file_name}'''							)

  lowerCamelCase		:	Any							=      """| metric |"""
  lowerCamelCase		:	str							=      """|--------|"""
  lowerCamelCase		:	List[Any]							=      """| new / old (diff) |"""
  for metric_name in sorted(lowerCamelCase							):
   lowerCamelCase		:	List[Any]							=      benchmark_res[metric_name]
   lowerCamelCase		:	Tuple							=      metric_vals["""new"""]
   lowerCamelCase		:	int							=      metric_vals.get("""old""",	lowerCamelCase							)
   lowerCamelCase		:	Dict							=      metric_vals.get("""diff""",	lowerCamelCase							)

   lowerCamelCase		:	Dict							=      F''' {new_val:f}''' if isinstance(lowerCamelCase,	(int, float)							) else """None"""

   if old_val is not None:
    val_str += F''' / {old_val:f}''' if isinstance(lowerCamelCase,	(int, float)							) else "None"
   if dif_val is not None:
    val_str += F''' ({dif_val:f})''' if isinstance(lowerCamelCase,	(int, float)							) else "None"

   title += " " + metric_name + " |"
   lines += "---|"
   value += val_str + " |"

  output_md += [title, lines, value, " "]

 output_md.append("""</details>"""							)

 with open(lowerCamelCase,	"""w""",	encoding="""utf-8"""							) as f:
  f.writelines("""\n""".join(lowerCamelCase							)							)


if __name__ == "__main__":
      _lowerCamelCase					   =sys.argv[1]
      _lowerCamelCase					   =sys.argv[2]

      format_json_to_md(input_json_file, output_md_file)




