





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

from ...utils import logging


A_    :					Optional[Any]             =logging.get_logger(__name__)




def   lowerCamelCase_       (					UpperCAmelCase__       ,    UpperCAmelCase__      ):



						"""simple docstring"""




						a_					=		nn.functional.normalize(UpperCAmelCase__      )
						a_					=		nn.functional.normalize(UpperCAmelCase__      )
						return torch.mm(UpperCAmelCase__       ,    normalized_text_embeds.t()      )





class        lowercase_				( UpperCamelCase__):






							"""simple docstring"""







							snake_case_        =		CLIPConfig

							snake_case_        =		['''CLIPEncoderLayer''']


							def __init__(   self			,    _UpperCAmelCase		):







													"""simple docstring"""


													super().__init__(_UpperCAmelCase		)

													a_					=		CLIPVisionModel(config.vision_config		)
													a_					=		nn.Linear(config.vision_config.hidden_size			,    config.projection_dim			,    bias=_UpperCAmelCase		)

													a_					=		nn.Parameter(torch.ones(17			,    config.projection_dim		)			,    requires_grad=_UpperCAmelCase		)
													a_					=		nn.Parameter(torch.ones(3			,    config.projection_dim		)			,    requires_grad=_UpperCAmelCase		)

													a_					=		nn.Parameter(torch.ones(17		)			,    requires_grad=_UpperCAmelCase		)
													a_					=		nn.Parameter(torch.ones(3		)			,    requires_grad=_UpperCAmelCase		)


							@torch.no_grad()
							def 						lowercase__     (   self			,    _UpperCAmelCase			,    _UpperCAmelCase		):







													"""simple docstring"""


													a_					=		self.vision_model(_UpperCAmelCase		)[1]  # pooled_output
													a_					=		self.visual_projection(_UpperCAmelCase		)

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

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

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

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

																			result.append(_UpperCAmelCase		)

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

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

													if any(_UpperCAmelCase		):
																			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			,    _UpperCAmelCase			,    _UpperCAmelCase		):







													"""simple docstring"""


													a_					=		self.vision_model(_UpperCAmelCase		)[1]  # pooled_output
													a_					=		self.visual_projection(_UpperCAmelCase		)

													a_					=		cosine_distance(_UpperCAmelCase			,    self.special_care_embeds		)
													a_					=		cosine_distance(_UpperCAmelCase			,    self.concept_embeds		)

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

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

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

													a_					=		0.0  # black image

													return images, has_nsfw_concepts



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


A_    :					Optional[Any]             ={
    """configuration_wav2vec2_conformer""": [
        """WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """Wav2Vec2ConformerConfig""",
    ],
}


try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	A_    :					Union[str, Any]             =[
	    """WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """Wav2Vec2ConformerForAudioFrameClassification""",
	    """Wav2Vec2ConformerForCTC""",
	    """Wav2Vec2ConformerForPreTraining""",
	    """Wav2Vec2ConformerForSequenceClassification""",
	    """Wav2Vec2ConformerForXVector""",
	    """Wav2Vec2ConformerModel""",
	    """Wav2Vec2ConformerPreTrainedModel""",
	]

if TYPE_CHECKING:
	from .configuration_wavaveca_conformer import (
	    WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
	    WavaVecaConformerConfig,
	)

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_wavaveca_conformer import (
		    WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    WavaVecaConformerForAudioFrameClassification,
		    WavaVecaConformerForCTC,
		    WavaVecaConformerForPreTraining,
		    WavaVecaConformerForSequenceClassification,
		    WavaVecaConformerForXVector,
		    WavaVecaConformerModel,
		    WavaVecaConformerPreTrainedModel,
		)

else:
	import sys

	A_    :					Union[str, Any]             =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)