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

from ...utils import logging


_UpperCAmelCase    			=					logging.get_logger(__name__)


def 		_lowerCamelCase       (   _a			,   _a  ):
  """simple docstring"""




  _lowerCamelCase      =						nn.functional.normalize(UpperCAmelCase_  )
  _lowerCamelCase      =						nn.functional.normalize(UpperCAmelCase_  )
  return torch.mm(UpperCAmelCase_			,   normalized_text_embeds.t()  )






class 		__magic_name__				( _A					):


  """simple docstring"""





  _UpperCamelCase						 = CLIPConfig

  _UpperCamelCase						 = ["CLIPEncoderLayer"]


  def __init__(					self	,		a__		):
    super().__init__(__A		)

    _lowerCamelCase      =						CLIPVisionModel(config.vision_config		)
    _lowerCamelCase      =						nn.Linear(config.vision_config.hidden_size	,		config.projection_dim	,		bias=__A		)

    _lowerCamelCase      =						nn.Parameter(torch.ones(17	,		config.projection_dim		)	,		requires_grad=__A		)
    _lowerCamelCase      =						nn.Parameter(torch.ones(3	,		config.projection_dim		)	,		requires_grad=__A		)

    _lowerCamelCase      =						nn.Parameter(torch.ones(17		)	,		requires_grad=__A		)
    _lowerCamelCase      =						nn.Parameter(torch.ones(3		)	,		requires_grad=__A		)


  @torch.no_grad()
  def     _UpperCAmelCase  (					self	,		a__	,		a__		):
    _lowerCamelCase      =						self.vision_model(__A		)[1]  # pooled_output
    _lowerCamelCase      =						self.visual_projection(__A		)

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

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

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

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

      result.append(__A		)

    _lowerCamelCase      =						[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]		):
          _lowerCamelCase      =						torch.zeros_like(images[idx]		)  # black image
        else:
          _lowerCamelCase      =						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     _UpperCAmelCase  (					self	,		a__	,		a__		):
    _lowerCamelCase      =						self.vision_model(__A		)[1]  # pooled_output
    _lowerCamelCase      =						self.visual_projection(__A		)

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

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

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

    _lowerCamelCase      =						0.0  # black image

    return images, has_nsfw_concepts









'''simple docstring'''







def 			_lowerCAmelCase(      UpperCAmelCase_      :	str					, UpperCAmelCase_      :	str					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int					, ) ->							tuple[list[list[int]], list[list[str]]]:
							lowerCAmelCase__  =   list(UpperCAmelCase_						)
							lowerCAmelCase__  =   list(UpperCAmelCase_						)
							lowerCAmelCase__  =   len(UpperCAmelCase_						)
							lowerCAmelCase__  =   len(UpperCAmelCase_						)

							lowerCAmelCase__  =   [
							    [0 for _ in range(len_destination_seq + 1						)] for _ in range(len_source_seq + 1						)
							]
							lowerCAmelCase__  =   [
							    ["""0""" for _ in range(len_destination_seq + 1						)] for _ in range(len_source_seq + 1						)
							]

							for i in range(1					, len_source_seq + 1						):
														lowerCAmelCase__  =   i * delete_cost
														lowerCAmelCase__  =   F'''D{source_seq[i - 1]:c}'''

							for i in range(1					, len_destination_seq + 1						):
														lowerCAmelCase__  =   i * insert_cost
														lowerCAmelCase__  =   F'''I{destination_seq[i - 1]:c}'''

							for i in range(1					, len_source_seq + 1						):
														for j in range(1					, len_destination_seq + 1						):
																					if source_seq[i - 1] == destination_seq[j - 1]:
																												lowerCAmelCase__  =   costs[i - 1][j - 1] + copy_cost
																												lowerCAmelCase__  =   F'''C{source_seq[i - 1]:c}'''
																					else:
																												lowerCAmelCase__  =   costs[i - 1][j - 1] + replace_cost
																												lowerCAmelCase__  =   F'''R{source_seq[i - 1]:c}''' + str(destination_seq[j - 1]						)

																					if costs[i - 1][j] + delete_cost < costs[i][j]:
																												lowerCAmelCase__  =   costs[i - 1][j] + delete_cost
																												lowerCAmelCase__  =   F'''D{source_seq[i - 1]:c}'''

																					if costs[i][j - 1] + insert_cost < costs[i][j]:
																												lowerCAmelCase__  =   costs[i][j - 1] + insert_cost
																												lowerCAmelCase__  =   F'''I{destination_seq[j - 1]:c}'''

							return costs, ops
def 			_lowerCAmelCase(      UpperCAmelCase_      :	list[list[str]]					, UpperCAmelCase_      :	int					, UpperCAmelCase_      :	int						) ->							list[str]:
							if i == 0 and j == 0:
														return []
							else:
														if ops[i][j][0] == "C" or ops[i][j][0] == "R":
																					lowerCAmelCase__  =   assemble_transformation(UpperCAmelCase_					, i - 1					, j - 1						)
																					seq.append(ops[i][j]						)
																					return seq
														elif ops[i][j][0] == "D":
																					lowerCAmelCase__  =   assemble_transformation(UpperCAmelCase_					, i - 1					, UpperCAmelCase_						)
																					seq.append(ops[i][j]						)
																					return seq
														else:
																					lowerCAmelCase__  =   assemble_transformation(UpperCAmelCase_					, UpperCAmelCase_					, j - 1						)
																					seq.append(ops[i][j]						)
																					return seq


if __name__ == "__main__":
		_UpperCamelCase						, _UpperCamelCase  						=			compute_transform_tables("""Python""", """Algorithms""", -1, 1, 2, 2)

		_UpperCamelCase  						=			len(operations)
		_UpperCamelCase  						=			len(operations[0])
		_UpperCamelCase  						=			assemble_transformation(operations, m - 1, n - 1)

		_UpperCamelCase  						=			list("""Python""")
		_UpperCamelCase  						=			0
		_UpperCamelCase  						=			0

		with open("""min_cost.txt""", """w""") as file:
				for op in sequence:
						print("""""".join(string))

						if op[0] == "C":
								file.write("""%-16s""" % """Copy %c""" % op[1])
								file.write("""\t\t\t""" + """""".join(string))
								file.write("""\r\n""")

								cost -= 1
						elif op[0] == "R":
								_UpperCamelCase  						=			op[2]

								file.write("""%-16s""" % ("""Replace %c""" % op[1] + """ with """ + str(op[2])))
								file.write("""\t\t""" + """""".join(string))
								file.write("""\r\n""")

								cost += 1
						elif op[0] == "D":
								string.pop(i)

								file.write("""%-16s""" % """Delete %c""" % op[1])
								file.write("""\t\t\t""" + """""".join(string))
								file.write("""\r\n""")

								cost += 2
						else:
								string.insert(i, op[1])

								file.write("""%-16s""" % """Insert %c""" % op[1])
								file.write("""\t\t\t""" + """""".join(string))
								file.write("""\r\n""")

								cost += 2

						i += 1

				print("""""".join(string))
				print("""Cost: """, cost)

				file.write("""\r\nMinimum cost: """ + str(cost))





