
import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


UpperCamelCase_						:     List[str]	       =							"""\
@inproceedings{popovic-2015-chrf,
    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
    month = sep,
    year = \"2015\",
    address = \"Lisbon, Portugal\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W15-3049\",
    doi = \"10.18653/v1/W15-3049\",
    pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
    title = \"chr{F}++: words helping character n-grams\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Second Conference on Machine Translation\",
    month = sep,
    year = \"2017\",
    address = \"Copenhagen, Denmark\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W17-4770\",
    doi = \"10.18653/v1/W17-4770\",
    pages = \"612--618\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

UpperCamelCase_						:     List[str]	       =							"""\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""

UpperCamelCase_						:     Dict	       =							"""
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    'score' (float): The chrF (chrF++) score,
    'char_order' (int): The character n-gram order,
    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    'beta' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""




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






	def       _a(self				: Union[str, Any]    ) ->			str:
							if version.parse(scb.__version__    ) < version.parse("1.4.12"    ):
													raise ImportWarning(
													    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
													    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."    )
							return datasets.MetricInfo(
							    description=_DESCRIPTION      ,	citation=_CITATION      ,	homepage="https://github.com/mjpost/sacreBLEU#chrf--chrf"      ,	inputs_description=_KWARGS_DESCRIPTION      ,	features=datasets.Features(
							        {
							            "predictions": datasets.Value("string"      ,	id="sequence"    ),
							            "references": datasets.Sequence(datasets.Value("string"      ,	id="sequence"    )      ,	id="references"    ),
							        }    )      ,	codebase_urls=["https://github.com/mjpost/sacreBLEU#chrf--chrf"]      ,	reference_urls=[
							        "https://github.com/m-popovic/chrF",
							    ]      ,	)






	def       _a(self				: List[Any]      ,	snake_case				: List[Any]      ,	snake_case				: Tuple      ,	snake_case				: int = CHRF.CHAR_ORDER      ,	snake_case				: int = CHRF.WORD_ORDER      ,	snake_case				: int = CHRF.BETA      ,	snake_case				: bool = False      ,	snake_case				: bool = False      ,	snake_case				: bool = False      ,	) ->			int:
							_lowercase       :	Optional[Any]           =   len(references[0]    )
							if any(len(snake_case    ) != references_per_prediction for refs in references    ):
													raise ValueError("Sacrebleu requires the same number of references for each prediction"    )
							_lowercase       :	List[str]           =   [[refs[i] for refs in references] for i in range(snake_case    )]

							_lowercase       :	Any           =   CHRF(snake_case      ,	snake_case      ,	snake_case      ,	snake_case      ,	snake_case      ,	snake_case    )
							_lowercase       :	int           =   sb_chrf.corpus_score(snake_case      ,	snake_case    )

							return {
							    "score": output.score,
							    "char_order": output.char_order,
							    "word_order": output.word_order,
							    "beta": output.beta,
							}






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

from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Dict  )   ->			Any:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   nn.functional.normalize(_UpperCAmelCase  )
						_lowercase       :	List[str]           =   nn.functional.normalize(_UpperCAmelCase  )
						return torch.mm(_UpperCAmelCase ,			normalized_text_embeds.t()  )




class   __lowercase						(						__snake_case       ):
	_A       =   CLIPConfig

	_A       =   ["CLIPEncoderLayer"]






	def __init__(self				: List[str]      ,	snake_case				: CLIPConfig    ) ->			Optional[int]:
							super().__init__(snake_case    )

							_lowercase       :	Tuple           =   CLIPVisionModel(config.vision_config    )
							_lowercase       :	Any           =   nn.Linear(config.vision_config.hidden_size      ,	config.projection_dim      ,	bias=snake_case    )

							_lowercase       :	int           =   nn.Parameter(torch.ones(17      ,	config.projection_dim    )      ,	requires_grad=snake_case    )
							_lowercase       :	str           =   nn.Parameter(torch.ones(3      ,	config.projection_dim    )      ,	requires_grad=snake_case    )

							_lowercase       :	Any           =   nn.Parameter(torch.ones(17    )      ,	requires_grad=snake_case    )
							_lowercase       :	Dict           =   nn.Parameter(torch.ones(3    )      ,	requires_grad=snake_case    )






	@torch.no_grad()
	def       _a(self				: int      ,	snake_case				: Tuple      ,	snake_case				: Optional[Any]    ) ->			Union[str, Any]:
							_lowercase       :	str           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	List[Any]           =   self.visual_projection(snake_case    )

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							_lowercase       :	str           =   cosine_distance(snake_case      ,	self.special_care_embeds    ).cpu().float().numpy()
							_lowercase       :	Optional[int]           =   cosine_distance(snake_case      ,	self.concept_embeds    ).cpu().float().numpy()

							_lowercase       :	List[str]           =   []
							_lowercase       :	int           =   image_embeds.shape[0]
							for i in range(snake_case    ):
													_lowercase       :	int           =   {"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
													_lowercase       :	Optional[int]           =   0.0

													for concept_idx in range(len(special_cos_dist[0]    )    ):
																			_lowercase       :	Union[str, Any]           =   special_cos_dist[i][concept_idx]
																			_lowercase       :	Optional[int]           =   self.special_care_embeds_weights[concept_idx].item()
																			_lowercase       :	Optional[int]           =   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]}    )
																									_lowercase       :	Union[str, Any]           =   0.01

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

													result.append(snake_case    )

							_lowercase       :	Dict           =   [len(res["bad_concepts"]    ) > 0 for res in result]

							return images, has_nsfw_concepts






	@torch.no_grad()
	def       _a(self				: str      ,	snake_case				: torch.FloatTensor      ,	snake_case				: torch.FloatTensor    ) ->			List[str]:
							_lowercase       :	Dict           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	Any           =   self.visual_projection(snake_case    )

							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.special_care_embeds    )
							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.concept_embeds    )

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							_lowercase       :	Optional[int]           =   0.0

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

							_lowercase       :	Any           =   (cos_dist - self.concept_embeds_weights) + special_adjustment
							# concept_scores = concept_scores.round(decimals=3)
							_lowercase       :	List[Any]           =   torch.any(concept_scores > 0      ,	dim=1    )

							return images, has_nsfw_concepts




