



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

import datasets


_snake_case		=  "\\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"

_snake_case		=  "\\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"

_snake_case		=  "\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   UpperCAmelCase_    (       datasets.Metric):







							def    snake_case__      (   self):

														'''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    snake_case__      (   self,			__a,			__a,			__a = CHRF.CHAR_ORDER,			__a = CHRF.WORD_ORDER,			__a = CHRF.BETA,			__a = False,			__a = False,			__a = False,			):

														'''simple docstring'''

														_lowerCAmelCase     :							str    =    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")
														_lowerCAmelCase     :							str    =    [[refs[i] for refs in references] for i in range(__UpperCAmelCase)]

														_lowerCAmelCase     :							str    =    CHRF(__UpperCAmelCase,			__UpperCAmelCase,			__UpperCAmelCase,			__UpperCAmelCase,			__UpperCAmelCase,			__UpperCAmelCase)
														_lowerCAmelCase     :							Optional[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 os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


__lowerCamelCase							 =     logging.get_logger(__name__)

__lowerCamelCase							 =     list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
__lowerCamelCase							 =     tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class 			UpperCamelCase__:
						lowerCAmelCase__     :  str  							=						field(
						    default=__A						,  metadata={'help': 'Model type selected in the list: ' + ', '.join(__A       )}       )
						lowerCAmelCase__     :  str  							=						field(
						    default=__A						,  metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}       )
						lowerCAmelCase__     :  int  							=						field(
						    default=128						,  metadata={
						        'help': (
						            'The maximum total input sequence length after tokenization. Sequences longer '
						            'than this will be truncated, sequences shorter will be padded.'
						        )
						    }						,  )
						lowerCAmelCase__     :  int  							=						field(
						    default=128						,  metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}						,  )
						lowerCAmelCase__     :  int  							=						field(
						    default=64						,  metadata={
						        'help': (
						            'The maximum number of tokens for the question. Questions longer than this will '
						            'be truncated to this length.'
						        )
						    }						,  )
						lowerCAmelCase__     :  int  							=						field(
						    default=30						,  metadata={
						        'help': (
						            'The maximum length of an answer that can be generated. This is needed because the start '
						            'and end predictions are not conditioned on one another.'
						        )
						    }						,  )
						lowerCAmelCase__     :  bool  							=						field(
						    default=__A						,  metadata={'help': 'Overwrite the cached training and evaluation sets'}       )
						lowerCAmelCase__     :  bool  							=						field(
						    default=__A						,  metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'}       )
						lowerCAmelCase__     :  float  							=						field(
						    default=0.0						,  metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}       )
						lowerCAmelCase__     :  int  							=						field(
						    default=20						,  metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'}       )
						lowerCAmelCase__     :  int  							=						field(
						    default=0						,  metadata={
						        'help': (
						            'language id of input for language-specific xlm models (see'
						            ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
						        )
						    }						,  )
						lowerCAmelCase__     :  int  							=						field(default=1						,  metadata={'help': 'multiple threads for converting example to features'}       )






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Dict  							=						'train'
						lowerCAmelCase__     :  int  							=						'dev'






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  SquadDataTrainingArguments
						lowerCAmelCase__     :  List[SquadFeatures]
						lowerCAmelCase__     :  Split
						lowerCAmelCase__     :  bool





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = None						,__UpperCAmelCase = Split.train						,__UpperCAmelCase = False						,__UpperCAmelCase = None						,__UpperCAmelCase = "pt"						,)    -> Optional[Any]:
													A__		   =							args
													A__		   =							is_language_sensitive
													A__		   =							SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
													if isinstance(__UpperCAmelCase						,__UpperCAmelCase   ):
																				try:
																											A__		   =							Split[mode]
																				except KeyError:
																											raise KeyError('mode is not a valid split name'   )
													A__		   =							mode
													# Load data features from cache or dataset file
													A__		   =							'v2' if args.version_2_with_negative else 'v1'
													A__		   =							os.path.join(
													    cache_dir if cache_dir is not None else args.data_dir						,f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''						,)

													# Make sure only the first process in distributed training processes the dataset,
													# and the others will use the cache.
													A__		   =							cached_features_file + '.lock'
													with FileLock(__UpperCAmelCase   ):
																				if os.path.exists(__UpperCAmelCase   ) and not args.overwrite_cache:
																											A__		   =							time.time()
																											A__		   =							torch.load(__UpperCAmelCase   )

																											# Legacy cache files have only features, while new cache files
																											# will have dataset and examples also.
																											A__		   =							self.old_features['features']
																											A__		   =							self.old_features.get('dataset'						,__UpperCAmelCase   )
																											A__		   =							self.old_features.get('examples'						,__UpperCAmelCase   )
																											logger.info(
																											    f'''Loading features from cached file {cached_features_file} [took %.3f s]'''						,time.time() - start   )

																											if self.dataset is None or self.examples is None:
																																		logger.warning(
																																		    f'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
																																		    ' future run'   )
																				else:
																											if mode == Split.dev:
																																		A__		   =							self.processor.get_dev_examples(args.data_dir   )
																											else:
																																		A__		   =							self.processor.get_train_examples(args.data_dir   )

																											A__   ,     A__		   =							squad_convert_examples_to_features(
																											    examples=self.examples						,tokenizer=__UpperCAmelCase						,max_seq_length=args.max_seq_length						,doc_stride=args.doc_stride						,max_query_length=args.max_query_length						,is_training=mode == Split.train						,threads=args.threads						,return_dataset=__UpperCAmelCase						,)

																											A__		   =							time.time()
																											torch.save(
																											    {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}						,__UpperCAmelCase						,)
																											# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																											logger.info(
																											    f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''   )





						def __len__(				self   )    -> Union[str, Any]:
													return len(self.features   )





						def __getitem__(				self						,__UpperCAmelCase   )    -> Dict[str, torch.Tensor]:
													# Convert to Tensors and build dataset
													A__		   =							self.features[i]

													A__		   =							torch.tensor(feature.input_ids						,dtype=torch.long   )
													A__		   =							torch.tensor(feature.attention_mask						,dtype=torch.long   )
													A__		   =							torch.tensor(feature.token_type_ids						,dtype=torch.long   )
													A__		   =							torch.tensor(feature.cls_index						,dtype=torch.long   )
													A__		   =							torch.tensor(feature.p_mask						,dtype=torch.float   )
													A__		   =							torch.tensor(feature.is_impossible						,dtype=torch.float   )

													A__		   =							{
													    'input_ids': input_ids,
													    'attention_mask': attention_mask,
													    'token_type_ids': token_type_ids,
													}

													if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
																				del inputs["token_type_ids"]

													if self.args.model_type in ["xlnet", "xlm"]:
																				inputs.update({'cls_index': cls_index, 'p_mask': p_mask}   )
																				if self.args.version_2_with_negative:
																											inputs.update({'is_impossible': is_impossible}   )
																				if self.is_language_sensitive:
																											inputs.update({'langs': (torch.ones(input_ids.shape						,dtype=torch.intaa   ) * self.args.lang_id)}   )

													if self.mode == Split.train:
																				A__		   =							torch.tensor(feature.start_position						,dtype=torch.long   )
																				A__		   =							torch.tensor(feature.end_position						,dtype=torch.long   )
																				inputs.update({'start_positions': start_positions, 'end_positions': end_positions}   )

													return inputs





