



'''simple docstring'''







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(      UpperCAmelCase_      :	List[Any]					, UpperCAmelCase_      :	Tuple						) ->							List[Any]:
							lowerCAmelCase__  =   nn.functional.normalize(UpperCAmelCase_						)
							lowerCAmelCase__  =   nn.functional.normalize(UpperCAmelCase_						)
							return torch.mm(UpperCAmelCase_					, normalized_text_embeds.t()						)






class      lowerCamelCase__     (     _A				):






	'''simple docstring'''

	A__		=	CLIPConfig

	A__		=	['''CLIPEncoderLayer''']




	def __init__(  self		:  str   ,		__A		:  CLIPConfig					)     ->			Optional[Any]:




								'''simple docstring'''





								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      lowercase__							(  self		:  str   ,		__A		:  Any   ,		__A		:  Optional[int]					)     ->			List[Any]:




								'''simple docstring'''





								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.0_1

															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      lowercase__							(  self		:  Dict   ,		__A		:  torch.FloatTensor   ,		__A		:  torch.FloatTensor					)     ->			Tuple:




								'''simple docstring'''





								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.0_1
								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))





