


"""simple docstring"""



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

import datasets


__snake_case             =   """\
@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\",
}
"""

__snake_case             =   """\
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.
"""

__snake_case             =   """
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 _lowerCAmelCase    (				datasets.Metric     ):







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       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 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__ = CHRF.CHAR_ORDER						,     UpperCamelCase__ = CHRF.WORD_ORDER						,     UpperCamelCase__ = CHRF.BETA						,     UpperCamelCase__ = False						,     UpperCamelCase__ = False						,     UpperCamelCase__ = False						,     )     ->		Any:

       '''simple docstring'''




       snake_case   :				List[Any]				 =   len(references[0]						)
       if any(len(UpperCamelCase__						) != references_per_prediction for refs in references						):
           raise ValueError("Sacrebleu requires the same number of references for each prediction"						)
       snake_case   :				str				 =   [[refs[i] for refs in references] for i in range(UpperCamelCase__						)]

       snake_case   :				Any				 =   CHRF(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)
       snake_case   :				Union[str, Any]				 =   sb_chrf.corpus_score(UpperCamelCase__						,     UpperCamelCase__						)

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









"""simple docstring"""



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__snake_case             =   logging.get_logger(__name__)

__snake_case             =   {
    """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}







class _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	Tuple							  =  '''altclip_text_model'''







   def __init__(     self						,     UpperCamelCase__=25_0002						,     UpperCamelCase__=1024						,     UpperCamelCase__=24						,     UpperCamelCase__=16						,     UpperCamelCase__=4096						,     UpperCamelCase__="gelu"						,     UpperCamelCase__=0.1						,     UpperCamelCase__=0.1						,     UpperCamelCase__=514						,     UpperCamelCase__=1						,     UpperCamelCase__=0.02						,     UpperCamelCase__=0.02						,     UpperCamelCase__=1e-05						,     UpperCamelCase__=1						,     UpperCamelCase__=0						,     UpperCamelCase__=2						,     UpperCamelCase__="absolute"						,     UpperCamelCase__=True						,     UpperCamelCase__=768						,     **UpperCamelCase__						,     )     ->		Optional[int]:

       '''simple docstring'''




       super().__init__(pad_token_id=UpperCamelCase__						,     bos_token_id=UpperCamelCase__						,     eos_token_id=UpperCamelCase__						,     **UpperCamelCase__						)

       snake_case   :				Any				 =   vocab_size
       snake_case   :				List[Any]				 =   hidden_size
       snake_case   :				Optional[int]				 =   num_hidden_layers
       snake_case   :				Optional[Any]				 =   num_attention_heads
       snake_case   :				Dict				 =   hidden_act
       snake_case   :				Dict				 =   intermediate_size
       snake_case   :				int				 =   hidden_dropout_prob
       snake_case   :				Optional[int]				 =   attention_probs_dropout_prob
       snake_case   :				Union[str, Any]				 =   max_position_embeddings
       snake_case   :				Optional[int]				 =   type_vocab_size
       snake_case   :				Dict				 =   initializer_range
       snake_case   :				int				 =   initializer_factor
       snake_case   :				Union[str, Any]				 =   layer_norm_eps
       snake_case   :				List[Any]				 =   position_embedding_type
       snake_case   :				Any				 =   use_cache
       snake_case   :				str				 =   project_dim







class _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	Tuple							  =  '''altclip_vision_model'''







   def __init__(     self						,     UpperCamelCase__=768						,     UpperCamelCase__=3072						,     UpperCamelCase__=512						,     UpperCamelCase__=12						,     UpperCamelCase__=12						,     UpperCamelCase__=3						,     UpperCamelCase__=224						,     UpperCamelCase__=32						,     UpperCamelCase__="quick_gelu"						,     UpperCamelCase__=1e-5						,     UpperCamelCase__=0.0						,     UpperCamelCase__=0.02						,     UpperCamelCase__=1.0						,     **UpperCamelCase__						,     )     ->		str:

       '''simple docstring'''




       super().__init__(**UpperCamelCase__						)

       snake_case   :				Optional[int]				 =   hidden_size
       snake_case   :				str				 =   intermediate_size
       snake_case   :				List[str]				 =   projection_dim
       snake_case   :				Optional[Any]				 =   num_hidden_layers
       snake_case   :				Optional[int]				 =   num_attention_heads
       snake_case   :				str				 =   num_channels
       snake_case   :				List[str]				 =   patch_size
       snake_case   :				List[Any]				 =   image_size
       snake_case   :				Union[str, Any]				 =   initializer_range
       snake_case   :				Optional[Any]				 =   initializer_factor
       snake_case   :				Any				 =   attention_dropout
       snake_case   :				Dict				 =   layer_norm_eps
       snake_case   :				List[str]				 =   hidden_act







   @classmethod
   def 			lowerCamelCase		(     cls						,     UpperCamelCase__						,     **UpperCamelCase__						)     ->		"PretrainedConfig":

       '''simple docstring'''




       cls._set_token_in_kwargs(UpperCamelCase__						)

       snake_case ,snake_case   :				str				 =   cls.get_config_dict(UpperCamelCase__						,     **UpperCamelCase__						)

       # get the vision config dict if we are loading from AltCLIPConfig
       if config_dict.get("model_type"						) == "altclip":
           snake_case   :				Optional[Any]				 =   config_dict["vision_config"]

       if "model_type" in config_dict and hasattr(cls						,     "model_type"						) and config_dict["model_type"] != cls.model_type:
           logger.warning(
               F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
               F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'						)

       return cls.from_dict(UpperCamelCase__						,     **UpperCamelCase__						)







class _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	str							  =  '''altclip'''
   __UpperCAmelCase			:	Optional[Any]							  =  True







   def __init__(     self						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=768						,     UpperCamelCase__=2.6592						,     **UpperCamelCase__						)     ->		Any:

       '''simple docstring'''




       snake_case   :				List[str]				 =   kwargs.pop("text_config_dict"						,     UpperCamelCase__						)
       snake_case   :				Union[str, Any]				 =   kwargs.pop("vision_config_dict"						,     UpperCamelCase__						)

       super().__init__(**UpperCamelCase__						)

       # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
       # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
       # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
       if text_config_dict is not None:
           if text_config is None:
               snake_case   :				List[str]				 =   {}

           # This is the complete result when using `text_config_dict`.
           snake_case   :				Dict				 =   AltCLIPTextConfig(**UpperCamelCase__						).to_dict()

           # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
           for key, value in _text_config_dict.items():
               if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
                   # If specified in `text_config_dict`
                   if key in text_config_dict:
                       snake_case   :				Optional[Any]				 =   (
                           F'`{key}` is found in both `text_config_dict` and `text_config` but with different values. '
                           F'The value `text_config_dict["{key}"]` will be used instead.'
                       )
                   # If inferred from default argument values (just to be super careful)
                   else:
                       snake_case   :				Any				 =   (
                           F'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '
                           F'value `text_config["{key}"]` will be overriden.'
                       )
                   logger.warning(UpperCamelCase__						)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
           text_config.update(_text_config_dict						)

       if vision_config_dict is not None:
           if vision_config is None:
               snake_case   :				Union[str, Any]				 =   {}

           # This is the complete result when using `vision_config_dict`.
           snake_case   :				int				 =   AltCLIPVisionConfig(**UpperCamelCase__						).to_dict()
           # convert keys to string instead of integer
           if "id2label" in _vision_config_dict:
               snake_case   :				Optional[int]				 =   {
                   str(UpperCamelCase__						): value for key, value in _vision_config_dict["id2label"].items()
               }

           # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
           for key, value in _vision_config_dict.items():
               if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
                   # If specified in `vision_config_dict`
                   if key in vision_config_dict:
                       snake_case   :				int				 =   (
                           F'`{key}` is found in both `vision_config_dict` and `vision_config` but with different '
                           F'values. The value `vision_config_dict["{key}"]` will be used instead.'
                       )
                   # If inferred from default argument values (just to be super careful)
                   else:
                       snake_case   :				Optional[Any]				 =   (
                           F'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '
                           F'The value `vision_config["{key}"]` will be overriden.'
                       )
                   logger.warning(UpperCamelCase__						)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
           vision_config.update(_vision_config_dict						)

       if text_config is None:
           snake_case   :				Optional[int]				 =   {}
           logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."						)

       if vision_config is None:
           snake_case   :				Dict				 =   {}
           logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."						)

       snake_case   :				Dict				 =   AltCLIPTextConfig(**UpperCamelCase__						)
       snake_case   :				Tuple				 =   AltCLIPVisionConfig(**UpperCamelCase__						)

       snake_case   :				int				 =   projection_dim
       snake_case   :				List[str]				 =   logit_scale_init_value
       snake_case   :				int				 =   1.0







   @classmethod
   def 			lowerCamelCase		(     cls						,     UpperCamelCase__						,     UpperCamelCase__						,     **UpperCamelCase__						)     ->		Union[str, Any]:

       '''simple docstring'''




       return cls(text_config=text_config.to_dict()						,     vision_config=vision_config.to_dict()						,     **UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Optional[Any]:

       '''simple docstring'''




       snake_case   :				Tuple				 =   copy.deepcopy(self.__dict__						)
       snake_case   :				Optional[int]				 =   self.text_config.to_dict()
       snake_case   :				str				 =   self.vision_config.to_dict()
       snake_case   :				Optional[int]				 =   self.__class__.model_type
       return output





