






"""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,
)


_UpperCamelCase		:  Union[str, Any]						=		'\\n@inproceedings{Rajpurkar2016SQuAD10,\n  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n  booktitle={EMNLP},\n  year={2016}\n}\n'

_UpperCamelCase		:  Union[str, Any]						=		'\nThis metric wrap the official scoring script for version 2 of the Stanford Question\nAnswering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n\nSQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions\nwritten adversarially by crowdworkers to look similar to answerable ones.\nTo do well on SQuAD2.0, systems must not only answer questions when possible, but also\ndetermine when no answer is supported by the paragraph and abstain from answering.\n'

_UpperCamelCase		:  Optional[int]						=		'\nComputes SQuAD v2 scores (F1 and EM).\nArgs:\n    predictions: List of triple for question-answers to score with the following elements:\n        - the question-answer \'id\' field as given in the references (see below)\n        - the text of the answer\n        - the probability that the question has no answer\n    references: List of question-answers dictionaries with the following key-values:\n            - \'id\': id of the question-answer pair (see above),\n            - \'answers\': a list of Dict {\'text\': text of the answer as a string}\n    no_answer_threshold: float\n        Probability threshold to decide that a question has no answer.\nReturns:\n    \'exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'f1\': The F-score of predicted tokens versus the gold answer\n    \'total\': Number of score considered\n    \'HasAns_exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'HasAns_f1\': The F-score of predicted tokens versus the gold answer\n    \'HasAns_total\': Number of score considered\n    \'NoAns_exact\': Exact match (the normalized answer exactly match the gold answer)\n    \'NoAns_f1\': The F-score of predicted tokens versus the gold answer\n    \'NoAns_total\': Number of score considered\n    \'best_exact\': Best exact match (with varying threshold)\n    \'best_exact_thresh\': No-answer probability threshold associated to the best exact match\n    \'best_f1\': Best F1 (with varying threshold)\n    \'best_f1_thresh\': No-answer probability threshold associated to the best F1\nExamples:\n\n    >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\', \'no_answer_probability\': 0.}]\n    >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n    >>> squad_v2_metric = datasets.load_metric("squad_v2")\n    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'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}\n'

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







    def       UpperCamelCase_				(      self	):
      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							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase=1.0	):
      lowercase							   =	{p['id']: p['no_answer_probability'] for p in predictions}
      lowercase							   =	[{'paragraphs': [{'qas': references}]}]
      lowercase							   =	{p['id']: p['prediction_text'] for p in predictions}

      lowercase							   =	make_qid_to_has_ans(_lowerCamelCase	)  # maps qid to True/False
      lowercase							   =	[k for k, v in qid_to_has_ans.items() if v]
      lowercase							   =	[k for k, v in qid_to_has_ans.items() if not v]

      lowercase   ,					lowercase							   =	get_raw_scores(_lowerCamelCase							,		_lowerCamelCase	)
      lowercase							   =	apply_no_ans_threshold(_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase	)
      lowercase							   =	apply_no_ans_threshold(_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase	)
      lowercase							   =	make_eval_dict(_lowerCamelCase							,		_lowerCamelCase	)

      if has_ans_qids:
        lowercase							   =	make_eval_dict(_lowerCamelCase							,		_lowerCamelCase							,		qid_list=_lowerCamelCase	)
        merge_eval(_lowerCamelCase							,		_lowerCamelCase							,		'HasAns'	)
      if no_ans_qids:
        lowercase							   =	make_eval_dict(_lowerCamelCase							,		_lowerCamelCase							,		qid_list=_lowerCamelCase	)
        merge_eval(_lowerCamelCase							,		_lowerCamelCase							,		'NoAns'	)
      find_all_best_thresh(_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase	)
      return dict(_lowerCamelCase	)









"""simple docstring"""



import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_UpperCamelCase		:  Optional[Any]						=		logging.get_logger(__name__)


_UpperCamelCase		:  Any						=		{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all MVP models at https://huggingface.co/models?filter=mvp
_UpperCamelCase		:  Optional[int]						=		{
    'vocab_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json',
    },
    'added_tokens.json': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json',
    },
    'merges_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt',
    },
}

_UpperCamelCase		:  Union[str, Any]						=		{
    'RUCAIBox/mvp': 1_0_2_4,
}
@lru_cache()
def 						_SCREAMING_SNAKE_CASE			(   ):





  '''simple docstring'''





  lowercase							   =	(
      list(range(ord('!'   )		, ord('~'   ) + 1   )   ) + list(range(ord('¡'   )		, ord('¬'   ) + 1   )   ) + list(range(ord('®'   )		, ord('ÿ'   ) + 1   )   )
  )
  lowercase							   =	bs[:]
  lowercase							   =	0
  for b in range(2**8   ):
    if b not in bs:
      bs.append(__snake_case   )
      cs.append(2**8 + n   )
      n += 1
  lowercase							   =	[chr(__snake_case   ) for n in cs]
  return dict(zip(__snake_case		, __snake_case   )   )
def 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  int   ):





  '''simple docstring'''





  lowercase							   =	set()
  lowercase							   =	word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)   )
    lowercase							   =	char
  return pairs



class 	a					(       a_     ):
    UpperCAmelCase_			:					Tuple     					=VOCAB_FILES_NAMES
    UpperCAmelCase_			:					int     					=PRETRAINED_VOCAB_FILES_MAP
    UpperCAmelCase_			:					Optional[int]     					=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    UpperCAmelCase_			:					Any     					=["input_ids", "attention_mask"]







    def __init__(      self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase="replace"							,		_lowerCamelCase="<s>"							,		_lowerCamelCase="</s>"							,		_lowerCamelCase="</s>"							,		_lowerCamelCase="<s>"							,		_lowerCamelCase="<unk>"							,		_lowerCamelCase="<pad>"							,		_lowerCamelCase="<mask>"							,		_lowerCamelCase=False							,		**_lowerCamelCase							,		):
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else bos_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else eos_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else sep_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else cls_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else unk_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else mask_token

      super().__init__(
          errors=_lowerCamelCase							,		bos_token=_lowerCamelCase							,		eos_token=_lowerCamelCase							,		unk_token=_lowerCamelCase							,		sep_token=_lowerCamelCase							,		cls_token=_lowerCamelCase							,		pad_token=_lowerCamelCase							,		mask_token=_lowerCamelCase							,		add_prefix_space=_lowerCamelCase							,		**_lowerCamelCase							,		)
      with open(_lowerCamelCase							,		encoding='utf-8'	) as vocab_handle:
        lowercase							   =	json.load(_lowerCamelCase	)
      lowercase							   =	{v: k for k, v in self.encoder.items()}
      lowercase							   =	errors  # how to handle errors in decoding
      lowercase							   =	bytes_to_unicode()
      lowercase							   =	{v: k for k, v in self.byte_encoder.items()}
      with open(_lowerCamelCase							,		encoding='utf-8'	) as merges_handle:
        lowercase							   =	merges_handle.read().split('\n'	)[1:-1]
      lowercase							   =	[tuple(merge.split()	) for merge in bpe_merges]
      lowercase							   =	dict(zip(_lowerCamelCase							,		range(len(_lowerCamelCase	)	)	)	)
      lowercase							   =	{}
      lowercase							   =	add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      lowercase							   =	re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'	)







    @property
    def       UpperCamelCase_				(      self	):
      return len(self.encoder	)







    def       UpperCamelCase_				(      self	):
      return dict(self.encoder							,		**self.added_tokens_encoder	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      if token in self.cache:
        return self.cache[token]
      lowercase							   =	tuple(_lowerCamelCase	)
      lowercase							   =	get_pairs(_lowerCamelCase	)

      if not pairs:
        return token

      while True:
        lowercase							   =	min(_lowerCamelCase							,		key=lambda _lowerCamelCase	: self.bpe_ranks.get(_lowerCamelCase							,		float('inf'	)	)	)
        if bigram not in self.bpe_ranks:
          break
        lowercase   ,					lowercase							   =	bigram
        lowercase							   =	[]
        lowercase							   =	0
        while i < len(_lowerCamelCase	):
          try:
            lowercase							   =	word.index(_lowerCamelCase							,		_lowerCamelCase	)
          except ValueError:
            new_word.extend(word[i:]	)
            break
          else:
            new_word.extend(word[i:j]	)
            lowercase							   =	j

          if word[i] == first and i < len(_lowerCamelCase	) - 1 and word[i + 1] == second:
            new_word.append(first + second	)
            i += 2
          else:
            new_word.append(word[i]	)
            i += 1
        lowercase							   =	tuple(_lowerCamelCase	)
        lowercase							   =	new_word
        if len(_lowerCamelCase	) == 1:
          break
        else:
          lowercase							   =	get_pairs(_lowerCamelCase	)
      lowercase							   =	' '.join(_lowerCamelCase	)
      lowercase							   =	word
      return word







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      lowercase							   =	[]
      for token in re.findall(self.pat							,		_lowerCamelCase	):
        lowercase							   =	''.join(
            self.byte_encoder[b] for b in token.encode('utf-8'	)	)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
        bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase	).split(' '	)	)
      return bpe_tokens







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      return self.encoder.get(_lowerCamelCase							,		self.encoder.get(self.unk_token	)	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      return self.decoder.get(_lowerCamelCase	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      lowercase							   =	''.join(_lowerCamelCase	)
      lowercase							   =	bytearray([self.byte_decoder[c] for c in text]	).decode('utf-8'							,		errors=self.errors	)
      return text







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None	):
      if not os.path.isdir(_lowerCamelCase	):
        logger.error(F'Vocabulary path ({save_directory}) should be a directory'	)
        return
      lowercase							   =	os.path.join(
          _lowerCamelCase							,		(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']	)
      lowercase							   =	os.path.join(
          _lowerCamelCase							,		(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']	)

      with open(_lowerCamelCase							,		'w'							,		encoding='utf-8'	) as f:
        f.write(json.dumps(self.encoder							,		indent=2							,		sort_keys=_lowerCamelCase							,		ensure_ascii=_lowerCamelCase	) + '\n'	)

      lowercase							   =	0
      with open(_lowerCamelCase							,		'w'							,		encoding='utf-8'	) as writer:
        writer.write('#version: 0.2\n'	)
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items()							,		key=lambda _lowerCamelCase	: kv[1]	):
          if index != token_index:
            logger.warning(
                F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
                ' Please check that the tokenizer is not corrupted!'	)
            lowercase							   =	token_index
          writer.write(' '.join(_lowerCamelCase	) + '\n'	)
          index += 1

      return vocab_file, merge_file







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None	):
      if token_ids_a is None:
        return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      lowercase							   =	[self.cls_token_id]
      lowercase							   =	[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None							,		_lowerCamelCase = False	):
      if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=_lowerCamelCase							,		token_ids_a=_lowerCamelCase							,		already_has_special_tokens=_lowerCamelCase	)

      if token_ids_a is None:
        return [1] + ([0] * len(_lowerCamelCase	)) + [1]
      return [1] + ([0] * len(_lowerCamelCase	)) + [1, 1] + ([0] * len(_lowerCamelCase	)) + [1]







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None	):
      lowercase							   =	[self.sep_token_id]
      lowercase							   =	[self.cls_token_id]

      if token_ids_a is None:
        return len(cls + token_ids_a + sep	) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep	) * [0]







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase=False							,		**_lowerCamelCase	):
      lowercase							   =	kwargs.pop('add_prefix_space'							,		self.add_prefix_space	)
      if (is_split_into_words or add_prefix_space) and (len(_lowerCamelCase	) > 0 and not text[0].isspace()):
        lowercase							   =	' ' + text
      return (text, kwargs)


