
import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


lowerCamelCase__     :		Any        = re.compile(R"""\b(a|an|the)\b""", re.UNICODE)

lowerCamelCase__     :		Optional[int]        = None

def 		UpperCamelCase						(   )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: Union[str, Any]     		=   argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0.""" )
  parser.add_argument("""data_file"""			,			metavar="""data.json"""			,			help="""Input data JSON file.""" )
  parser.add_argument("""pred_file"""			,			metavar="""pred.json"""			,			help="""Model predictions.""" )
  parser.add_argument(
      """--out-file"""			,			"""-o"""			,			metavar="""eval.json"""			,			help="""Write accuracy metrics to file (default is stdout).""" )
  parser.add_argument(
      """--na-prob-file"""			,			"""-n"""			,			metavar="""na_prob.json"""			,			help="""Model estimates of probability of no answer.""" )
  parser.add_argument(
      """--na-prob-thresh"""			,			"""-t"""			,			type=lowercase_			,			default=1.0			,			help="""Predict \"\" if no-answer probability exceeds this (default = 1.0)."""			,			)
  parser.add_argument(
      """--out-image-dir"""			,			"""-p"""			,			metavar="""out_images"""			,			default=lowercase_			,			help="""Save precision-recall curves to directory.""" )
  parser.add_argument("""--verbose"""			,			"""-v"""			,			action="""store_true""" )
  if len(sys.argv ) == 1:
    parser.print_help()
    sys.exit(1 )
  return parser.parse_args()

def 		UpperCamelCase						(   lowercase_ )		->						Any:


  '''simple docstring'''






  lowercase__	: Optional[int]     		=   {}
  for article in dataset:
    for p in article["paragraphs"]:
      for qa in p["qas"]:
        lowercase__	: Optional[Any]     		=   bool(qa["""answers"""]["""text"""] )
  return qid_to_has_ans

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  def remove_articles(lowercase_ ):
    return ARTICLES_REGEX.sub(""" """			,			lowercase_ )

  def white_space_fix(lowercase_ ):
    return " ".join(text.split() )

  def remove_punc(lowercase_ ):
    lowercase__	: Union[str, Any]     		=   set(string.punctuation )
    return "".join(ch for ch in text if ch not in exclude )

  def lower(lowercase_ ):
    return text.lower()

  return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) )

def 		UpperCamelCase						(   lowercase_ )		->						Tuple:


  '''simple docstring'''






  if not s:
    return []
  return normalize_answer(lowercase_ ).split()

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						List[Any]:


  '''simple docstring'''






  return int(normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) )

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						int:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   get_tokens(lowercase_ )
  lowercase__	: Optional[int]     		=   get_tokens(lowercase_ )
  lowercase__	: List[Any]     		=   collections.Counter(lowercase_ ) & collections.Counter(lowercase_ )
  lowercase__	: Any     		=   sum(common.values() )
  if len(lowercase_ ) == 0 or len(lowercase_ ) == 0:
    # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
    return int(gold_toks == pred_toks )
  if num_same == 0:
    return 0
  lowercase__	: List[Any]     		=   1.0 * num_same / len(lowercase_ )
  lowercase__	: Any     		=   1.0 * num_same / len(lowercase_ )
  lowercase__	: List[str]     		=   (2 * precision * recall) / (precision + recall)
  return fa

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						Dict:


  '''simple docstring'''






  lowercase__	: Tuple     		=   {}
  lowercase__	: Optional[Any]     		=   {}
  for article in dataset:
    for p in article["paragraphs"]:
      for qa in p["qas"]:
        lowercase__	: List[Any]     		=   qa["""id"""]
        lowercase__	: Union[str, Any]     		=   [t for t in qa["""answers"""]["""text"""] if normalize_answer(lowercase_ )]
        if not gold_answers:
          # For unanswerable questions, only correct answer is empty string
          lowercase__	: List[str]     		=   [""""""]
        if qid not in preds:
          print(F'Missing prediction for {qid}' )
          continue
        lowercase__	: Union[str, Any]     		=   preds[qid]
        # Take max over all gold answers
        lowercase__	: int     		=   max(compute_exact(lowercase_			,			lowercase_ ) for a in gold_answers )
        lowercase__	: Tuple     		=   max(compute_fa(lowercase_			,			lowercase_ ) for a in gold_answers )
  return exact_scores, fa_scores

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						int:


  '''simple docstring'''






  lowercase__	: Any     		=   {}
  for qid, s in scores.items():
    lowercase__	: Union[str, Any]     		=   na_probs[qid] > na_prob_thresh
    if pred_na:
      lowercase__	: Tuple     		=   float(not qid_to_has_ans[qid] )
    else:
      lowercase__	: Union[str, Any]     		=   s
  return new_scores

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_=None )		->						int:


  '''simple docstring'''






  if not qid_list:
    lowercase__	: Optional[int]     		=   len(lowercase_ )
    return collections.OrderedDict(
        [
            ("""exact""", 100.0 * sum(exact_scores.values() ) / total),
            ("""f1""", 100.0 * sum(fa_scores.values() ) / total),
            ("""total""", total),
        ] )
  else:
    lowercase__	: Optional[int]     		=   len(lowercase_ )
    return collections.OrderedDict(
        [
            ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list ) / total),
            ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list ) / total),
            ("""total""", total),
        ] )

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  for k in new_eval:
    lowercase__	: int     		=   new_eval[k]

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						Any:


  '''simple docstring'''






  plt.step(lowercase_			,			lowercase_			,			color="""b"""			,			alpha=0.2			,			where="""post""" )
  plt.fill_between(lowercase_			,			lowercase_			,			step="""post"""			,			alpha=0.2			,			color="""b""" )
  plt.xlabel("""Recall""" )
  plt.ylabel("""Precision""" )
  plt.xlim([0.0, 1.05] )
  plt.ylim([0.0, 1.05] )
  plt.title(lowercase_ )
  plt.savefig(lowercase_ )
  plt.clf()

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_=None			,			lowercase_=None )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   sorted(lowercase_			,			key=lambda lowercase_ : na_probs[k] )
  lowercase__	: Any     		=   0.0
  lowercase__	: str     		=   1.0
  lowercase__	: Any     		=   0.0
  lowercase__	: Optional[int]     		=   [1.0]
  lowercase__	: Tuple     		=   [0.0]
  lowercase__	: Dict     		=   0.0
  for i, qid in enumerate(lowercase_ ):
    if qid_to_has_ans[qid]:
      true_pos += scores[qid]
    lowercase__	: List[Any]     		=   true_pos / float(i + 1 )
    lowercase__	: Tuple     		=   true_pos / float(lowercase_ )
    if i == len(lowercase_ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
      # i.e., if we can put a threshold after this point
      avg_prec += cur_p * (cur_r - recalls[-1])
      precisions.append(lowercase_ )
      recalls.append(lowercase_ )
  if out_image:
    plot_pr_curve(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )
  return {"ap": 100.0 * avg_prec}

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						str:


  '''simple docstring'''






  if out_image_dir and not os.path.exists(lowercase_ ):
    os.makedirs(lowercase_ )
  lowercase__	: Dict     		=   sum(1 for v in qid_to_has_ans.values() if v )
  if num_true_pos == 0:
    return
  lowercase__	: Optional[int]     		=   make_precision_recall_eval(
      lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			out_image=os.path.join(lowercase_			,			"""pr_exact.png""" )			,			title="""Precision-Recall curve for Exact Match score"""			,			)
  lowercase__	: Union[str, Any]     		=   make_precision_recall_eval(
      lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			out_image=os.path.join(lowercase_			,			"""pr_f1.png""" )			,			title="""Precision-Recall curve for F1 score"""			,			)
  lowercase__	: Union[str, Any]     		=   {k: float(lowercase_ ) for k, v in qid_to_has_ans.items()}
  lowercase__	: Dict     		=   make_precision_recall_eval(
      lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			out_image=os.path.join(lowercase_			,			"""pr_oracle.png""" )			,			title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"""			,			)
  merge_eval(lowercase_			,			lowercase_			,			"""pr_exact""" )
  merge_eval(lowercase_			,			lowercase_			,			"""pr_f1""" )
  merge_eval(lowercase_			,			lowercase_			,			"""pr_oracle""" )

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						Dict:


  '''simple docstring'''






  if not qid_list:
    return
  lowercase__	: Union[str, Any]     		=   [na_probs[k] for k in qid_list]
  lowercase__	: int     		=   np.ones_like(lowercase_ ) / float(len(lowercase_ ) )
  plt.hist(lowercase_			,			weights=lowercase_			,			bins=20			,			range=(0.0, 1.0) )
  plt.xlabel("""Model probability of no-answer""" )
  plt.ylabel("""Proportion of dataset""" )
  plt.title(F'Histogram of no-answer probability: {name}' )
  plt.savefig(os.path.join(lowercase_			,			F'na_prob_hist_{name}.png' ) )
  plt.clf()

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						Dict:


  '''simple docstring'''






  lowercase__	: Union[str, Any]     		=   sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] )
  lowercase__	: Tuple     		=   num_no_ans
  lowercase__	: Dict     		=   cur_score
  lowercase__	: Tuple     		=   0.0
  lowercase__	: str     		=   sorted(lowercase_			,			key=lambda lowercase_ : na_probs[k] )
  for i, qid in enumerate(lowercase_ ):
    if qid not in scores:
      continue
    if qid_to_has_ans[qid]:
      lowercase__	: List[str]     		=   scores[qid]
    else:
      if preds[qid]:
        lowercase__	: Tuple     		=   -1
      else:
        lowercase__	: Optional[int]     		=   0
    cur_score += diff
    if cur_score > best_score:
      lowercase__	: Tuple     		=   cur_score
      lowercase__	: Optional[Any]     		=   na_probs[qid]
  return 100.0 * best_score / len(lowercase_ ), best_thresh

def 		UpperCamelCase						(   lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__		,     lowercase__	: List[Any]     		=   find_best_thresh(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )
  lowercase__		,     lowercase__	: Optional[Any]     		=   find_best_thresh(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )
  lowercase__	: str     		=   best_exact
  lowercase__	: Tuple     		=   exact_thresh
  lowercase__	: str     		=   best_fa
  lowercase__	: Any     		=   fa_thresh

def 		UpperCamelCase						(   )		->						List[Any]:


  '''simple docstring'''






  with open(OPTS.data_file ) as f:
    lowercase__	: str     		=   json.load(lowercase_ )
    lowercase__	: int     		=   dataset_json["""data"""]
  with open(OPTS.pred_file ) as f:
    lowercase__	: List[str]     		=   json.load(lowercase_ )
  if OPTS.na_prob_file:
    with open(OPTS.na_prob_file ) as f:
      lowercase__	: int     		=   json.load(lowercase_ )
  else:
    lowercase__	: List[Any]     		=   {k: 0.0 for k in preds}
  lowercase__	: Optional[Any]     		=   make_qid_to_has_ans(lowercase_ )  # maps qid to True/False
  lowercase__	: int     		=   [k for k, v in qid_to_has_ans.items() if v]
  lowercase__	: Union[str, Any]     		=   [k for k, v in qid_to_has_ans.items() if not v]
  lowercase__		,     lowercase__	: List[Any]     		=   get_raw_scores(lowercase_			,			lowercase_ )
  lowercase__	: str     		=   apply_no_ans_threshold(lowercase_			,			lowercase_			,			lowercase_			,			OPTS.na_prob_thresh )
  lowercase__	: Optional[Any]     		=   apply_no_ans_threshold(lowercase_			,			lowercase_			,			lowercase_			,			OPTS.na_prob_thresh )
  lowercase__	: List[str]     		=   make_eval_dict(lowercase_			,			lowercase_ )
  if has_ans_qids:
    lowercase__	: Any     		=   make_eval_dict(lowercase_			,			lowercase_			,			qid_list=lowercase_ )
    merge_eval(lowercase_			,			lowercase_			,			"""HasAns""" )
  if no_ans_qids:
    lowercase__	: Optional[Any]     		=   make_eval_dict(lowercase_			,			lowercase_			,			qid_list=lowercase_ )
    merge_eval(lowercase_			,			lowercase_			,			"""NoAns""" )
  if OPTS.na_prob_file:
    find_all_best_thresh(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_ )
  if OPTS.na_prob_file and OPTS.out_image_dir:
    run_precision_recall_analysis(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			OPTS.out_image_dir )
    histogram_na_prob(lowercase_			,			lowercase_			,			OPTS.out_image_dir			,			"""hasAns""" )
    histogram_na_prob(lowercase_			,			lowercase_			,			OPTS.out_image_dir			,			"""noAns""" )
  if OPTS.out_file:
    with open(OPTS.out_file			,			"""w""" ) as f:
      json.dump(lowercase_			,			lowercase_ )
  else:
    print(json.dumps(lowercase_			,			indent=2 ) )


if __name__ == "__main__":
     lowerCamelCase__     :		List[str]        = parse_args()
     if OPTS.out_image_dir:
          import matplotlib

          matplotlib.use("""Agg""")
          import matplotlib.pyplot as plt
     main()








# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


lowerCamelCase__     :		Optional[int]        = [
    """EAGER""",
    """AOT_EAGER""",
    """INDUCTOR""",
    """NVFUSER""",
    """AOT_NVFUSER""",
    """AOT_CUDAGRAPHS""",
    """OFI""",
    """FX2TRT""",
    """ONNXRT""",
    """IPEX""",
]

def 		UpperCamelCase						(   lowercase_			,			lowercase_=None			,			lowercase_=None			,			lowercase_=None )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   True
  while ask_again:
    lowercase__	: Tuple     		=   input(lowercase_ )
    try:
      if default is not None and len(lowercase_ ) == 0:
        return default
      return convert_value(lowercase_ ) if convert_value is not None else result
    except Exception:
      if error_message is not None:
        print(lowercase_ )

def 		UpperCamelCase						(   lowercase_			,			lowercase_=[]			,			lowercase_=None			,			lowercase_=0 )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   BulletMenu(lowercase_			,			lowercase_ )
  lowercase__	: Any     		=   menu.run(default_choice=lowercase_ )
  return convert_value(lowercase_ ) if convert_value is not None else result

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: Union[str, Any]     		=   int(lowercase_ )
  return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[str]     		=   int(lowercase_ )
  return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  lowercase__	: str     		=   int(lowercase_ )
  return DynamoBackend(DYNAMO_BACKENDS[value] ).value

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   int(lowercase_ )
  return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] )

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  return {"yes": True, "no": False}[value.lower()]



class    _snake_case (						argparse.RawDescriptionHelpFormatter				):


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: int     		=   super()._format_usage(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   usage.replace("""<command> [<args>] """       ,	"""""")
   return usage






