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

from ...utils import logging


_lowerCamelCase    :      Union[str, Any]	 =						logging.get_logger(__name__)





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[str]					,       UpperCAmelCase__   :							List[Any]     ):
					SCREAMING_SNAKE_CASE				=				nn.functional.normalize(UpperCAmelCase__     )
					SCREAMING_SNAKE_CASE				=				nn.functional.normalize(UpperCAmelCase__     )
					return torch.mm(UpperCAmelCase__					,       normalized_text_embeds.t()     )


class   lowercase			(   a   ):
							lowercase__  :				Union[str, Any]									=							CLIPConfig

							lowercase__  :				List[str]									=							["""CLIPEncoderLayer"""]




							def __init__(  self      :    Union[str, Any]		,							_UpperCamelCase      :    CLIPConfig					)    -> List[Any]:



												'''simple docstring'''

												super().__init__(_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				CLIPVisionModel(config.vision_config					)
												SCREAMING_SNAKE_CASE				=				nn.Linear(config.vision_config.hidden_size		,							config.projection_dim		,							bias=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				nn.Parameter(torch.ones(17		,							config.projection_dim					)		,							requires_grad=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				nn.Parameter(torch.ones(3		,							config.projection_dim					)		,							requires_grad=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				nn.Parameter(torch.ones(17					)		,							requires_grad=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				nn.Parameter(torch.ones(3					)		,							requires_grad=_UpperCamelCase					)




							@torch.no_grad()
							def 		__snake_case(  self      :    Optional[int]		,							_UpperCamelCase      :    List[Any]		,							_UpperCamelCase      :    Optional[Any]					)    -> Dict:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				self.vision_model(_UpperCamelCase					)[1]  # pooled_output
												SCREAMING_SNAKE_CASE				=				self.visual_projection(_UpperCamelCase					)

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

												SCREAMING_SNAKE_CASE				=				[]
												SCREAMING_SNAKE_CASE				=				image_embeds.shape[0]
												for i in range(_UpperCamelCase					):
																	SCREAMING_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
																	SCREAMING_SNAKE_CASE				=				0.0

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

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

																	result.append(_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				[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]					):
																											SCREAMING_SNAKE_CASE				=				torch.zeros_like(images[idx]					)  # black image
																						else:
																											SCREAMING_SNAKE_CASE				=				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 		__snake_case(  self      :    List[Any]		,							_UpperCamelCase      :    torch.FloatTensor		,							_UpperCamelCase      :    torch.FloatTensor					)    -> int:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				self.vision_model(_UpperCamelCase					)[1]  # pooled_output
												SCREAMING_SNAKE_CASE				=				self.visual_projection(_UpperCamelCase					)

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

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

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

												SCREAMING_SNAKE_CASE				=				0.0  # black image

												return images, has_nsfw_concepts





from sklearn.metrics import mean_absolute_error

import datasets


_lowerCamelCase    :      Any	 =						'''\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
'''

_lowerCamelCase    :      str	 =						'''\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
'''


_lowerCamelCase    :      List[str]	 =						'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 "raw_values" : Returns a full set of errors in case of multioutput input.

                 "uniform_average" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is "raw_values", then mean absolute error is returned for each output separately. If multioutput is "uniform_average" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric("mae")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.5}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric("mae", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results)
    {\'mae\': array([0.5, 1. ])}
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,				_KWARGS_DESCRIPTION   )
class   lowercase			(   datasets.Metric   ):




							def 		__snake_case(  self      :    int					)    -> str:



												'''simple docstring'''

												return datasets.MetricInfo(
												    description=_DESCRIPTION		,							citation=_CITATION		,							inputs_description=_KWARGS_DESCRIPTION		,							features=datasets.Features(self._get_feature_types()					)		,							reference_urls=[
												        "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"
												    ]		,							)




							def 		__snake_case(  self      :    int					)    -> Tuple:



												'''simple docstring'''

												if self.config_name == "multilist":
																	return {
																	    "predictions": datasets.Sequence(datasets.Value("float"					)					),
																	    "references": datasets.Sequence(datasets.Value("float"					)					),
																	}
												else:
																	return {
																	    "predictions": datasets.Value("float"					),
																	    "references": datasets.Value("float"					),
																	}





							def 		__snake_case(  self      :    Tuple		,							_UpperCamelCase      :    List[str]		,							_UpperCamelCase      :    List[Any]		,							_UpperCamelCase      :    str=None		,							_UpperCamelCase      :    Any="uniform_average"					)    -> int:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				mean_absolute_error(_UpperCamelCase		,							_UpperCamelCase		,							sample_weight=_UpperCamelCase		,							multioutput=_UpperCamelCase					)

												return {"mae": mae_score}




