




"""simple docstring"""

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

from ...utils import logging


UpperCamelCase__			:     str			       =				logging.get_logger(__name__)




def    snake_case__						(							lowerCAmelCase :		str					,       lowerCAmelCase :		Union[str, Any]		):
					__snake_case        =						nn.functional.normalize(lowerCAmelCase		)
					__snake_case        =						nn.functional.normalize(lowerCAmelCase		)
					return torch.mm(lowerCAmelCase					,       normalized_text_embeds.t()		)

class      A__   (   lowercase_  ):
	A_				:					List[Any]      =   CLIPConfig

	A_				:					List[Any]      =   ["""CLIPEncoderLayer"""]




	def __init__( self	:						Union[str, Any]   ,     lowercase	:						CLIPConfig						)       ->			Any:
						super().__init__(lowercase						)

						__snake_case        =						CLIPVisionModel(config.vision_config						)
						__snake_case        =						nn.Linear(config.vision_config.hidden_size   ,     config.projection_dim   ,     bias=lowercase						)

						__snake_case        =						nn.Parameter(torch.ones(17   ,     config.projection_dim						)   ,     requires_grad=lowercase						)
						__snake_case        =						nn.Parameter(torch.ones(3   ,     config.projection_dim						)   ,     requires_grad=lowercase						)

						__snake_case        =						nn.Parameter(torch.ones(17						)   ,     requires_grad=lowercase						)
						__snake_case        =						nn.Parameter(torch.ones(3						)   ,     requires_grad=lowercase						)




	@torch.no_grad()
	def 				a_		( self	:						Union[str, Any]   ,     lowercase	:						Dict   ,     lowercase	:						Dict						)       ->			Union[str, Any]:
						__snake_case        =						self.vision_model(lowercase						)[1]  # pooled_output
						__snake_case        =						self.visual_projection(lowercase						)

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

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

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

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

											result.append(lowercase						)

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

						for idx, has_nsfw_concept in enumerate(lowercase						):
											if has_nsfw_concept:
																if torch.is_tensor(lowercase						) or torch.is_tensor(images[0]						):
																					__snake_case        =						torch.zeros_like(images[idx]						)  # black image
																else:
																					__snake_case        =						np.zeros(images[idx].shape						)  # black image

						if any(lowercase						):
											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 				a_		( self	:						Optional[int]   ,     lowercase	:						torch.FloatTensor   ,     lowercase	:						torch.FloatTensor						)       ->			Any:
						__snake_case        =						self.vision_model(lowercase						)[1]  # pooled_output
						__snake_case        =						self.visual_projection(lowercase						)

						__snake_case        =						cosine_distance(lowercase   ,     self.special_care_embeds						)
						__snake_case        =						cosine_distance(lowercase   ,     self.concept_embeds						)

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

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

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

						__snake_case        =						0.0  # black image

						return images, has_nsfw_concepts








"""simple docstring"""

from .chunk_utils import chunk_layer
from .data_transforms import make_atomaa_masks
from .feats import atomaa_to_atomaa, frames_and_literature_positions_to_atomaa_pos, torsion_angles_to_frames
from .loss import compute_predicted_aligned_error, compute_tm
from .protein import Protein as OFProtein
from .protein import to_pdb
from .rigid_utils import Rigid, Rotation
from .tensor_utils import dict_multimap, flatten_final_dims, permute_final_dims


