


'''simple docstring'''



from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
						import timm


if is_torch_available():
						from torch import Tensor



class 			a       (	_a			,						_a ):


					"""simple docstring"""






					SCREAMING_SNAKE_CASE :				List[str]							     =     "pixel_values"
					SCREAMING_SNAKE_CASE :				Union[str, Any]							     =     False
					SCREAMING_SNAKE_CASE :				Optional[Any]							     =     TimmBackboneConfig

					def __init__(       self  :	Optional[Any]							,				snake_case  :	Dict							,				**snake_case  :	Any    )		->							List[Any]:
										requires_backends(self							,				'''timm'''    )
										super().__init__(UpperCAmelCase__    )
										__UpperCAmelCase			:				Dict													=    config

										if config.backbone is None:
															raise ValueError('''backbone is not set in the config. Please set it to a timm model name.'''    )

										if config.backbone not in timm.list_models():
															raise ValueError(f'backbone {config.backbone} is not supported by timm.'    )

										if hasattr(UpperCAmelCase__							,				'''out_features'''    ) and config.out_features is not None:
															raise ValueError('''out_features is not supported by TimmBackbone. Please use out_indices instead.'''    )

										__UpperCAmelCase			:				Any													=    getattr(UpperCAmelCase__							,				'''use_pretrained_backbone'''							,				UpperCAmelCase__    )
										if pretrained is None:
															raise ValueError('''use_pretrained_backbone is not set in the config. Please set it to True or False.'''    )

										# We just take the final layer by default. This matches the default for the transformers models.
										__UpperCAmelCase			:				int													=    config.out_indices if getattr(UpperCAmelCase__							,				'''out_indices'''							,				UpperCAmelCase__    ) is not None else (-1,)

										__UpperCAmelCase			:				Tuple													=    timm.create_model(
										    config.backbone							,				pretrained=UpperCAmelCase__							,				features_only=config.features_only							,				in_chans=config.num_channels							,				out_indices=UpperCAmelCase__							,				**UpperCAmelCase__							,				)
										# These are used to control the output of the model when called. If output_hidden_states is True, then
										# return_layers is modified to include all layers.
										__UpperCAmelCase			:				Any													=    self._backbone.return_layers
										__UpperCAmelCase			:				Any													=    {layer['''module''']: str(UpperCAmelCase__    ) for i, layer in enumerate(self._backbone.feature_info.info    )}
										super()._init_backbone(UpperCAmelCase__    )

					@classmethod
					def 				lowerCamelCase__				(       cls  :	List[str]							,				snake_case  :	Optional[int]							,				*snake_case  :	Union[str, Any]							,				**snake_case  :	List[Any]    )		->							Union[str, Any]:
										requires_backends(cls							,				['''vision''', '''timm''']    )
										from ...models.timm_backbone import TimmBackboneConfig

										__UpperCAmelCase			:				Any													=    kwargs.pop('''config'''							,				TimmBackboneConfig()    )

										__UpperCAmelCase			:				Optional[int]													=    kwargs.pop('''use_timm_backbone'''							,				UpperCAmelCase__    )
										if not use_timm:
															raise ValueError('''use_timm_backbone must be True for timm backbones'''    )

										__UpperCAmelCase			:				Any													=    kwargs.pop('''num_channels'''							,				config.num_channels    )
										__UpperCAmelCase			:				Any													=    kwargs.pop('''features_only'''							,				config.features_only    )
										__UpperCAmelCase			:				Dict													=    kwargs.pop('''use_pretrained_backbone'''							,				config.use_pretrained_backbone    )
										__UpperCAmelCase			:				Dict													=    kwargs.pop('''out_indices'''							,				config.out_indices    )
										__UpperCAmelCase			:				List[Any]													=    TimmBackboneConfig(
										    backbone=UpperCAmelCase__							,				num_channels=UpperCAmelCase__							,				features_only=UpperCAmelCase__							,				use_pretrained_backbone=UpperCAmelCase__							,				out_indices=UpperCAmelCase__							,				)
										return super()._from_config(UpperCAmelCase__							,				**UpperCAmelCase__    )

					def 				lowerCamelCase__				(       self  :	str							,				snake_case  :	int    )		->							List[str]:
										pass






					def 				lowerCamelCase__				(       self  :	List[Any]							,				snake_case  :	str							,				snake_case  :	int=None							,				snake_case  :	Union[str, Any]=None							,				snake_case  :	Any=None							,				**snake_case  :	List[str]    )		->							Union[BackboneOutput, Tuple[Tensor, ...]]:
										__UpperCAmelCase			:				Any													=    return_dict if return_dict is not None else self.config.use_return_dict
										__UpperCAmelCase			:				Dict													=    (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										__UpperCAmelCase			:				Dict													=    output_attentions if output_attentions is not None else self.config.output_attentions

										if output_attentions:
															raise ValueError('''Cannot output attentions for timm backbones at the moment'''    )

										if output_hidden_states:
															# We modify the return layers to include all the stages of the backbone
															__UpperCAmelCase			:				Tuple													=    self._all_layers
															__UpperCAmelCase			:				Dict													=    self._backbone(UpperCAmelCase__							,				**UpperCAmelCase__    )
															__UpperCAmelCase			:				Optional[Any]													=    self._return_layers
															__UpperCAmelCase			:				List[str]													=    tuple(hidden_states[i] for i in self.out_indices    )
										else:
															__UpperCAmelCase			:				Union[str, Any]													=    self._backbone(UpperCAmelCase__							,				**UpperCAmelCase__    )
															__UpperCAmelCase			:				Optional[int]													=    None

										__UpperCAmelCase			:				Tuple													=    tuple(UpperCAmelCase__    )
										__UpperCAmelCase			:				List[Any]													=    tuple(UpperCAmelCase__    ) if hidden_states is not None else None

										if not return_dict:
															__UpperCAmelCase			:				List[str]													=    (feature_maps,)
															if output_hidden_states:
																				__UpperCAmelCase			:				str													=    output + (hidden_states,)
															return output

										return BackboneOutput(feature_maps=UpperCAmelCase__							,				hidden_states=UpperCAmelCase__							,				attentions=UpperCAmelCase__    )



'''simple docstring'''



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

import datasets


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

__UpperCAmelCase    :Tuple				       =     "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

__UpperCAmelCase    :List[Any]				       =     "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> 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.\"]\n        >>> 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.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"



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


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	Dict    )		->							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 				lowerCamelCase__				(       self  :	Any							,				snake_case  :	str							,				snake_case  :	int							,				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							,				)		->							Optional[int]:
          __UpperCAmelCase			:				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'''    )
          __UpperCAmelCase			:				int													=    [[refs[i] for refs in references] for i in range(snake_case    )]

          __UpperCAmelCase			:				int													=    CHRF(snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case							,				snake_case    )
          __UpperCAmelCase			:				Dict													=    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,
          }