


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


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

A   :					Union[str, Any]	=      list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A   :					Optional[Any]	=      tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







@dataclass
class     _lowercase				:


       """simple docstring"""




       A__      		=    field(
           default=lowercase__							,						metadata={"help": "Model type selected in the list: " + ", ".join(lowercase__)})
       A__      		=    field(
           default=lowercase__							,						metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."})
       A__      		=    field(
           default=1_28							,						metadata={
               "help": (
                   "The maximum total input sequence length after tokenization. Sequences longer "
                   "than this will be truncated, sequences shorter will be padded."
               )
           }							,						)
       A__      		=    field(
           default=1_28							,						metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}							,						)
       A__      		=    field(
           default=64							,						metadata={
               "help": (
                   "The maximum number of tokens for the question. Questions longer than this will "
                   "be truncated to this length."
               )
           }							,						)
       A__      		=    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."
               )
           }							,						)
       A__      		=    field(
           default=lowercase__							,						metadata={"help": "Overwrite the cached training and evaluation sets"})
       A__      		=    field(
           default=lowercase__							,						metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."})
       A__      		=    field(
           default=0.0							,						metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
       A__      		=    field(
           default=20							,						metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."})
       A__      		=    field(
           default=0							,						metadata={
               "help": (
                   "language id of input for language-specific xlm models (see"
                   " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
               )
           }							,						)
       A__      		=    field(default=1							,						metadata={"help": "multiple threads for converting example to features"})







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    "train"
       A__      		=    "dev"







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    42
       A__      		=    42
       A__      		=    42
       A__      		=    42





       def __init__(     self							:    Optional[int]      ,   __lowerCamelCase							:    SquadDataTrainingArguments      ,   __lowerCamelCase							:    PreTrainedTokenizer      ,   __lowerCamelCase							:    Optional[int] = None      ,   __lowerCamelCase							:    Union[str, Split] = Split.train      ,   __lowerCamelCase							:    Optional[bool] = False      ,   __lowerCamelCase							:    Optional[str] = None      ,   __lowerCamelCase							:    Optional[str] = "pt"      ,   ):


             '''simple docstring'''



             lowerCamelCase__	:       List[str]					=						args
             lowerCamelCase__	:       Tuple					=						is_language_sensitive
             lowerCamelCase__	:       int					=						SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
             if isinstance(__lowerCamelCase      ,   __lowerCamelCase ):
                   try:
                         lowerCamelCase__	:       List[str]					=						Split[mode]
                   except KeyError:
                         raise KeyError("mode is not a valid split name" )
             lowerCamelCase__	:       str					=						mode
             # Load data features from cache or dataset file
             lowerCamelCase__	:       Any					=						"v2" if args.version_2_with_negative else "v1"
             lowerCamelCase__	:       List[str]					=						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.
             lowerCamelCase__	:       List[str]					=						cached_features_file + ".lock"
             with FileLock(__lowerCamelCase ):
                   if os.path.exists(__lowerCamelCase ) and not args.overwrite_cache:
                         lowerCamelCase__	:       str					=						time.time()
                         lowerCamelCase__	:       Tuple					=						torch.load(__lowerCamelCase )

                         # Legacy cache files have only features, while new cache files
                         # will have dataset and examples also.
                         lowerCamelCase__	:       Optional[Any]					=						self.old_features["features"]
                         lowerCamelCase__	:       Optional[int]					=						self.old_features.get("dataset"      ,   __lowerCamelCase )
                         lowerCamelCase__	:       Optional[Any]					=						self.old_features.get("examples"      ,   __lowerCamelCase )
                         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:
                               lowerCamelCase__	:       List[Any]					=						self.processor.get_dev_examples(args.data_dir )
                         else:
                               lowerCamelCase__	:       str					=						self.processor.get_train_examples(args.data_dir )

                         lowerCamelCase__					,     lowerCamelCase__	:       Tuple					=						squad_convert_examples_to_features(
                             examples=self.examples      ,   tokenizer=__lowerCamelCase      ,   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=__lowerCamelCase      ,   )

                         lowerCamelCase__	:       int					=						time.time()
                         torch.save(
                             {"features": self.features, "dataset": self.dataset, "examples": self.examples}      ,   __lowerCamelCase      ,   )
                         # ^ 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							:    List[Any] ):


             '''simple docstring'''



             return len(self.features )





       def __getitem__(     self							:    List[str]      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						self.features[i]

             lowerCamelCase__	:       Tuple					=						torch.tensor(feature.input_ids      ,   dtype=torch.long )
             lowerCamelCase__	:       List[Any]					=						torch.tensor(feature.attention_mask      ,   dtype=torch.long )
             lowerCamelCase__	:       Tuple					=						torch.tensor(feature.token_type_ids      ,   dtype=torch.long )
             lowerCamelCase__	:       Any					=						torch.tensor(feature.cls_index      ,   dtype=torch.long )
             lowerCamelCase__	:       Any					=						torch.tensor(feature.p_mask      ,   dtype=torch.float )
             lowerCamelCase__	:       Union[str, Any]					=						torch.tensor(feature.is_impossible      ,   dtype=torch.float )

             lowerCamelCase__	:       List[str]					=						{
                 "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:
                   lowerCamelCase__	:       List[Any]					=						torch.tensor(feature.start_position      ,   dtype=torch.long )
                   lowerCamelCase__	:       List[Any]					=						torch.tensor(feature.end_position      ,   dtype=torch.long )
                   inputs.update({"start_positions": start_positions, "end_positions": end_positions} )

             return inputs






import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


A   :					Tuple	=      "\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

A   :					Optional[int]	=      "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

A   :					str	=      "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"







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


       """simple docstring"""




       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             return datasets.MetricInfo(
                 description=_DESCRIPTION      ,   citation=_CITATION      ,   inputs_description=_KWARGS_DESCRIPTION      ,   features=datasets.Features(
                     {
                         "predictions": datasets.Sequence(datasets.Value("string"      ,   id="token" )      ,   id="sequence" ),
                         "references": datasets.Sequence(
                             datasets.Sequence(datasets.Value("string"      ,   id="token" )      ,   id="sequence" )      ,   id="references" ),
                     } )      ,   codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"]      ,   reference_urls=[
                     "https://en.wikipedia.org/wiki/BLEU",
                     "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
                 ]      ,   )





       def 		lowerCAmelCase  (     self							:    Optional[Any]      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    Optional[Any]=4      ,   __lowerCamelCase							:    Dict=False ):


             '''simple docstring'''



             lowerCamelCase__	:       str					=						compute_bleu(
                 reference_corpus=__lowerCamelCase      ,   translation_corpus=__lowerCamelCase      ,   max_order=__lowerCamelCase      ,   smooth=__lowerCamelCase )
             ((lowerCamelCase__)					,     (lowerCamelCase__)					,     (lowerCamelCase__)					,     (lowerCamelCase__)					,     (lowerCamelCase__)					,     (lowerCamelCase__))	:       List[str]					=						score
             return {
                 "bleu": bleu,
                 "precisions": precisions,
                 "brevity_penalty": bp,
                 "length_ratio": ratio,
                 "translation_length": translation_length,
                 "reference_length": reference_length,
             }


