



import itertools
from dataclasses import dataclass
from io import StringIO
from typing import Optional

import pyarrow as pa

import datasets
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


A_		:  Tuple										=  datasets.utils.logging.get_logger(__name__)



@dataclass
class 		_lowercase		(							datasets.BuilderConfig						):
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      "utf-8"
   _UpperCAmelCase  						=      None
   _UpperCAmelCase  						=      10 << 20  # 10MB
   _UpperCAmelCase  						=      False
   _UpperCAmelCase  						=      "line"



class 		_lowercase		(							datasets.ArrowBasedBuilder						):
   _UpperCAmelCase  						=      TextConfig

   def 		A				(   self      :							List[Any]				)							->					Union[str, Any]:


    """simple docstring"""






    return datasets.DatasetInfo(features=self.config.features				)

   def 		A				(   self      :							str				, __lowerCAmelCase      :							int				)							->					Union[str, Any]:


    """simple docstring"""






    if not self.config.data_files:
     raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}"""				)
    a							=		dl_manager.download_and_extract(self.config.data_files				)
    if isinstance(__lowerCAmelCase				, (str, list, tuple)				):
     a							=		data_files
     if isinstance(__lowerCAmelCase				, __lowerCAmelCase				):
      a							=		[files]
     a							=		[dl_manager.iter_files(__lowerCAmelCase				) for file in files]
     return [datasets.SplitGenerator(name=datasets.Split.TRAIN				, gen_kwargs={"files": files}				)]
    a							=		[]
    for split_name, files in data_files.items():
     if isinstance(__lowerCAmelCase				, __lowerCAmelCase				):
      a							=		[files]
     a							=		[dl_manager.iter_files(__lowerCAmelCase				) for file in files]
     splits.append(datasets.SplitGenerator(name=__lowerCAmelCase				, gen_kwargs={"files": files}				)				)
    return splits

   def 		A				(   self      :							Optional[int]				, __lowerCAmelCase      :							pa.Table				)							->					pa.Table:


    """simple docstring"""






    if self.config.features is not None:
     a							=		self.config.features.arrow_schema
     if all(not require_storage_cast(__lowerCAmelCase				) for feature in self.config.features.values()				):
      # cheaper cast
      a							=		pa_table.cast(__lowerCAmelCase				)
     else:
      # more expensive cast; allows str <-> int/float or str to Audio for example
      a							=		table_cast(__lowerCAmelCase				, __lowerCAmelCase				)
     return pa_table
    else:
     return pa_table.cast(pa.schema({"text": pa.string()}				)				)




   def 		A				(   self      :							int				, __lowerCAmelCase      :							str				)							->					List[Any]:


    """simple docstring"""






    a							=		list(self.config.features				) if self.config.features is not None else ["text"]
    for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCAmelCase				)				):
     # open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n"
     with open(__lowerCAmelCase				, encoding=self.config.encoding				, errors=self.config.errors				) as f:
      if self.config.sample_by == "line":
       a							=		0
       while True:
        a							=		f.read(self.config.chunksize				)
        if not batch:
         break
        batch += f.readline()  # finish current line
        # StringIO.readlines, by default splits only on "\n" (and keeps line breaks)
        a							=		StringIO(__lowerCAmelCase				).readlines()
        if not self.config.keep_linebreaks:
         a							=		[line.rstrip("\n"				) for line in batch]
        a							=		pa.Table.from_arrays([pa.array(__lowerCAmelCase				)]				, names=__lowerCAmelCase				)
        # Uncomment for debugging (will print the Arrow table size and elements)
        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
        yield (file_idx, batch_idx), self._cast_table(__lowerCAmelCase				)
        batch_idx += 1
      elif self.config.sample_by == "paragraph":
       a							=		0
       a							=		""
       while True:
        a							=		f.read(self.config.chunksize				)
        if not new_batch:
         break
        batch += new_batch
        batch += f.readline()  # finish current line
        a							=		batch.split("\n\n"				)
        a							=		pa.Table.from_arrays(
            [pa.array([example for example in batch[:-1] if example]				)]				, names=__lowerCAmelCase				)
        # Uncomment for debugging (will print the Arrow table size and elements)
        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
        yield (file_idx, batch_idx), self._cast_table(__lowerCAmelCase				)
        batch_idx += 1
        a							=		batch[-1]
       if batch:
        a							=		pa.Table.from_arrays([pa.array([batch]				)]				, names=__lowerCAmelCase				)
        yield (file_idx, batch_idx), self._cast_table(__lowerCAmelCase				)
      elif self.config.sample_by == "document":
       a							=		f.read()
       a							=		pa.Table.from_arrays([pa.array([text]				)]				, names=__lowerCAmelCase				)
       yield file_idx, self._cast_table(__lowerCAmelCase				)


'''simple docstring'''


import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


snake_case__	:     int      =    '''\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
'''

snake_case__	:     List[str]      =    '''
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
'''

snake_case__	:     int      =    '''
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer \'id\' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - \'id\': id of the question-answer pair (see above),
            - \'answers\': a list of Dict {\'text\': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    \'exact\': Exact match (the normalized answer exactly match the gold answer)
    \'f1\': The F-score of predicted tokens versus the gold answer
    \'total\': Number of score considered
    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer
    \'HasAns_total\': Number of score considered
    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)
    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer
    \'NoAns_total\': Number of score considered
    \'best_exact\': Best exact match (with varying threshold)
    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match
    \'best_f1\': Best F1 (with varying threshold)
    \'best_f1_thresh\': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]
    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]
    >>> squad_v2_metric = datasets.load_metric("squad_v2")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'exact\': 100.0, \'f1\': 100.0, \'total\': 1, \'HasAns_exact\': 100.0, \'HasAns_f1\': 100.0, \'HasAns_total\': 1, \'best_exact\': 100.0, \'best_exact_thresh\': 0.0, \'best_f1\': 100.0, \'best_f1_thresh\': 0.0}
'''






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







  '''simple docstring'''






  def _UpperCamelCase	(					self		):




       '''simple docstring'''

       return datasets.MetricInfo(
           description=_DESCRIPTION ,						citation=_CITATION ,						inputs_description=_KWARGS_DESCRIPTION ,						features=datasets.Features(
               {
                   'predictions': {
                       'id': datasets.Value('string'		),
                       'prediction_text': datasets.Value('string'		),
                       'no_answer_probability': datasets.Value('float32'		),
                   },
                   'references': {
                       'id': datasets.Value('string'		),
                       'answers': datasets.features.Sequence(
                           {'text': datasets.Value('string'		), 'answer_start': datasets.Value('int32'		)}		),
                   },
               }		) ,						codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/'] ,						reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/'] ,						)






  def _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_ ,						snake_case_=1.0		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[int]  = {p['id']: p['no_answer_probability'] for p in predictions}
       UpperCAmelCase_				:  Dict  = [{'paragraphs': [{'qas': references}]}]
       UpperCAmelCase_				:  Optional[int]  = {p['id']: p['prediction_text'] for p in predictions}

       UpperCAmelCase_				:  Optional[int]  = make_qid_to_has_ans(snake_case_		)  # maps qid to True/False
       UpperCAmelCase_				:  List[Any]  = [k for k, v in qid_to_has_ans.items() if v]
       UpperCAmelCase_				:  Union[str, Any]  = [k for k, v in qid_to_has_ans.items() if not v]

       UpperCAmelCase_  ,     UpperCAmelCase_				:  Optional[int]  = get_raw_scores(snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  Tuple  = apply_no_ans_threshold(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  Dict  = apply_no_ans_threshold(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       UpperCAmelCase_				:  str  = make_eval_dict(snake_case_ ,						snake_case_		)

       if has_ans_qids:
            UpperCAmelCase_				:  Dict  = make_eval_dict(snake_case_ ,						snake_case_ ,						qid_list=snake_case_		)
            merge_eval(snake_case_ ,						snake_case_ ,						'HasAns'		)
       if no_ans_qids:
            UpperCAmelCase_				:  List[str]  = make_eval_dict(snake_case_ ,						snake_case_ ,						qid_list=snake_case_		)
            merge_eval(snake_case_ ,						snake_case_ ,						'NoAns'		)
       find_all_best_thresh(snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_ ,						snake_case_		)
       return dict(snake_case_		)






