


'''simple docstring'''

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

import numpy as np


a_						:       Optional[Any]      			=				re.compile(R"""\b(a|an|the)\b""", re.UNICODE)

a_						:       Optional[int]      			=				None





def __snake_case      (   ):
 lowerCamelCase_  				=						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=UpperCAmelCase_      ,       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=UpperCAmelCase_      ,       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 __snake_case      (   UpperCAmelCase_		:		Tuple	):
 lowerCamelCase_  				=						{}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    lowerCamelCase_  				=						bool(qa["answers"]["text"]	)
 return qid_to_has_ans





def __snake_case      (   UpperCAmelCase_		:		Union[str, Any]	):

 def remove_articles(UpperCAmelCase_		:		Any	):
  return ARTICLES_REGEX.sub(" "      ,       UpperCAmelCase_	)

 def white_space_fix(UpperCAmelCase_		:		Union[str, Any]	):
  return " ".join(text.split()	)

 def remove_punc(UpperCAmelCase_		:		List[str]	):
  lowerCamelCase_  				=						set(string.punctuation	)
  return "".join(ch for ch in text if ch not in exclude	)

 def lower(UpperCAmelCase_		:		Tuple	):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase_	)	)	)	)





def __snake_case      (   UpperCAmelCase_		:		Any	):
 if not s:
  return []
 return normalize_answer(UpperCAmelCase_	).split()





def __snake_case      (   UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		int	):
 return int(normalize_answer(UpperCAmelCase_	) == normalize_answer(UpperCAmelCase_	)	)





def __snake_case      (   UpperCAmelCase_		:		List[str]      ,       UpperCAmelCase_		:		int	):
 lowerCamelCase_  				=						get_tokens(UpperCAmelCase_	)
 lowerCamelCase_  				=						get_tokens(UpperCAmelCase_	)
 lowerCamelCase_  				=						collections.Counter(UpperCAmelCase_	) & collections.Counter(UpperCAmelCase_	)
 lowerCamelCase_  				=						sum(common.values()	)
 if len(UpperCAmelCase_	) == 0 or len(UpperCAmelCase_	) == 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
 lowerCamelCase_  				=						1.0 * num_same / len(UpperCAmelCase_	)
 lowerCamelCase_  				=						1.0 * num_same / len(UpperCAmelCase_	)
 lowerCamelCase_  				=						(2 * precision * recall) / (precision + recall)
 return fa





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





def __snake_case      (   UpperCAmelCase_		:		int      ,       UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Optional[int]	):
 lowerCamelCase_  				=						{}
 for qid, s in scores.items():
  lowerCamelCase_  				=						na_probs[qid] > na_prob_thresh
  if pred_na:
   lowerCamelCase_  				=						float(not qid_to_has_ans[qid]	)
  else:
   lowerCamelCase_  				=						s
 return new_scores





def __snake_case      (   UpperCAmelCase_		:		Optional[int]      ,       UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Union[str, Any]=None	):
 if not qid_list:
  lowerCamelCase_  				=						len(UpperCAmelCase_	)
  return collections.OrderedDict(
      [
          ("exact", 100.0 * sum(exact_scores.values()	) / total),
          ("f1", 100.0 * sum(fa_scores.values()	) / total),
          ("total", total),
      ]	)
 else:
  lowerCamelCase_  				=						len(UpperCAmelCase_	)
  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 __snake_case      (   UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Union[str, Any]	):
 for k in new_eval:
  lowerCamelCase_  				=						new_eval[k]





def __snake_case      (   UpperCAmelCase_		:		Optional[int]      ,       UpperCAmelCase_		:		Optional[int]      ,       UpperCAmelCase_		:		List[str]      ,       UpperCAmelCase_		:		Optional[int]	):
 plt.step(UpperCAmelCase_      ,       UpperCAmelCase_      ,       color="b"      ,       alpha=0.2      ,       where="post"	)
 plt.fill_between(UpperCAmelCase_      ,       UpperCAmelCase_      ,       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(UpperCAmelCase_	)
 plt.savefig(UpperCAmelCase_	)
 plt.clf()





def __snake_case      (   UpperCAmelCase_		:		str      ,       UpperCAmelCase_		:		Optional[Any]      ,       UpperCAmelCase_		:		List[str]      ,       UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		int=None      ,       UpperCAmelCase_		:		str=None	):
 lowerCamelCase_  				=						sorted(UpperCAmelCase_      ,       key=lambda UpperCAmelCase_	: na_probs[k]	)
 lowerCamelCase_  				=						0.0
 lowerCamelCase_  				=						1.0
 lowerCamelCase_  				=						0.0
 lowerCamelCase_  				=						[1.0]
 lowerCamelCase_  				=						[0.0]
 lowerCamelCase_  				=						0.0
 for i, qid in enumerate(UpperCAmelCase_	):
  if qid_to_has_ans[qid]:
   true_pos += scores[qid]
  lowerCamelCase_  				=						true_pos / float(i + 1	)
  lowerCamelCase_  				=						true_pos / float(UpperCAmelCase_	)
  if i == len(UpperCAmelCase_	) - 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(UpperCAmelCase_	)
   recalls.append(UpperCAmelCase_	)
 if out_image:
  plot_pr_curve(UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_	)
 return {"ap": 100.0 * avg_prec}





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





def __snake_case      (   UpperCAmelCase_		:		int      ,       UpperCAmelCase_		:		int      ,       UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Dict	):
 if not qid_list:
  return
 lowerCamelCase_  				=						[na_probs[k] for k in qid_list]
 lowerCamelCase_  				=						np.ones_like(UpperCAmelCase_	) / float(len(UpperCAmelCase_	)	)
 plt.hist(UpperCAmelCase_      ,       weights=UpperCAmelCase_      ,       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(UpperCAmelCase_      ,       F'''na_prob_hist_{name}.png'''	)	)
 plt.clf()





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





def __snake_case      (   UpperCAmelCase_		:		Tuple      ,       UpperCAmelCase_		:		int      ,       UpperCAmelCase_		:		str      ,       UpperCAmelCase_		:		Optional[int]      ,       UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Union[str, Any]	):
 lowerCamelCase_				,lowerCamelCase_  				=						find_best_thresh(UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_	)
 lowerCamelCase_				,lowerCamelCase_  				=						find_best_thresh(UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_      ,       UpperCAmelCase_	)
 lowerCamelCase_  				=						best_exact
 lowerCamelCase_  				=						exact_thresh
 lowerCamelCase_  				=						best_fa
 lowerCamelCase_  				=						fa_thresh





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


if __name__ == "__main__":
     a_						:       Optional[int]      			=				parse_args()
     if OPTS.out_image_dir:
          import matplotlib

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







'''simple docstring'''

import contextlib
import os
import sqlitea

import pytest

from datasets import Dataset, Features, Value
from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy





def __snake_case      (   UpperCAmelCase_		:		Optional[int]      ,       UpperCAmelCase_		:		Dict	):
 assert isinstance(UpperCAmelCase_      ,       UpperCAmelCase_	)
 assert dataset.num_rows == 4
 assert dataset.num_columns == 3
 assert dataset.column_names == ["col_1", "col_2", "col_3"]
 for feature, expected_dtype in expected_features.items():
  assert dataset.features[feature].dtype == expected_dtype





@require_sqlalchemy
@pytest.mark.parametrize("keep_in_memory"      ,       [False, True]	)
def __snake_case      (   UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		List[str]      ,       UpperCAmelCase_		:		Union[str, Any]	):
 lowerCamelCase_  				=						tmp_path / "cache"
 lowerCamelCase_  				=						{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
  lowerCamelCase_  				=						SqlDatasetReader(
      "dataset"      ,       "sqlite:///" + sqlite_path      ,       cache_dir=UpperCAmelCase_      ,       keep_in_memory=UpperCAmelCase_	).read()
 _check_sql_dataset(UpperCAmelCase_      ,       UpperCAmelCase_	)





@require_sqlalchemy
@pytest.mark.parametrize(
    "features"      ,       [
        None,
        {"col_1": "string", "col_2": "int64", "col_3": "float64"},
        {"col_1": "string", "col_2": "string", "col_3": "string"},
        {"col_1": "int32", "col_2": "int32", "col_3": "int32"},
        {"col_1": "float32", "col_2": "float32", "col_3": "float32"},
    ]      ,       )
def __snake_case      (   UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Optional[Any]      ,       UpperCAmelCase_		:		List[str]      ,       UpperCAmelCase_		:		str	):
 lowerCamelCase_  				=						tmp_path / "cache"
 lowerCamelCase_  				=						{"col_1": "string", "col_2": "int64", "col_3": "float64"}
 lowerCamelCase_  				=						features.copy() if features else default_expected_features
 lowerCamelCase_  				=						(
     Features({feature: Value(UpperCAmelCase_	) for feature, dtype in features.items()}	) if features is not None else None
 )
 lowerCamelCase_  				=						SqlDatasetReader("dataset"      ,       "sqlite:///" + sqlite_path      ,       features=UpperCAmelCase_      ,       cache_dir=UpperCAmelCase_	).read()
 _check_sql_dataset(UpperCAmelCase_      ,       UpperCAmelCase_	)





def __snake_case      (   UpperCAmelCase_		:		Union[str, Any]	):
 with contextlib.closing(sqlitea.connect(UpperCAmelCase_	)	) as con:
  lowerCamelCase_  				=						con.cursor()
  cur.execute("SELECT * FROM dataset"	)
  for row in cur:
   yield row





@require_sqlalchemy
def __snake_case      (   UpperCAmelCase_		:		Dict      ,       UpperCAmelCase_		:		Optional[Any]      ,       UpperCAmelCase_		:		List[str]	):
 lowerCamelCase_  				=						tmp_path / "cache"
 lowerCamelCase_  				=						os.path.join(UpperCAmelCase_      ,       "tmp.sql"	)
 lowerCamelCase_  				=						SqlDatasetReader("dataset"      ,       "sqlite:///" + sqlite_path      ,       cache_dir=UpperCAmelCase_	).read()
 SqlDatasetWriter(UpperCAmelCase_      ,       "dataset"      ,       "sqlite:///" + output_sqlite_path      ,       num_proc=1	).write()

 lowerCamelCase_  				=						iter_sql_file(UpperCAmelCase_	)
 lowerCamelCase_  				=						iter_sql_file(UpperCAmelCase_	)

 for rowa, rowa in zip(UpperCAmelCase_      ,       UpperCAmelCase_	):
  assert rowa == rowa





@require_sqlalchemy
def __snake_case      (   UpperCAmelCase_		:		Union[str, Any]      ,       UpperCAmelCase_		:		Union[str, Any]      ,       UpperCAmelCase_		:		Tuple	):
 lowerCamelCase_  				=						tmp_path / "cache"
 lowerCamelCase_  				=						os.path.join(UpperCAmelCase_      ,       "tmp.sql"	)
 lowerCamelCase_  				=						SqlDatasetReader("dataset"      ,       "sqlite:///" + sqlite_path      ,       cache_dir=UpperCAmelCase_	).read()
 SqlDatasetWriter(UpperCAmelCase_      ,       "dataset"      ,       "sqlite:///" + output_sqlite_path      ,       num_proc=2	).write()

 lowerCamelCase_  				=						iter_sql_file(UpperCAmelCase_	)
 lowerCamelCase_  				=						iter_sql_file(UpperCAmelCase_	)

 for rowa, rowa in zip(UpperCAmelCase_      ,       UpperCAmelCase_	):
  assert rowa == rowa







@require_sqlalchemy
def __snake_case      (   UpperCAmelCase_		:		Any      ,       UpperCAmelCase_		:		Tuple      ,       UpperCAmelCase_		:		Tuple	):
 lowerCamelCase_  				=						tmp_path / "cache"
 lowerCamelCase_  				=						os.path.join(UpperCAmelCase_      ,       "tmp.sql"	)
 lowerCamelCase_  				=						SqlDatasetReader("dataset"      ,       "sqlite:///" + sqlite_path      ,       cache_dir=UpperCAmelCase_	).read()
 with pytest.raises(UpperCAmelCase_	):
  SqlDatasetWriter(UpperCAmelCase_      ,       "dataset"      ,       "sqlite:///" + output_sqlite_path      ,       num_proc=0	).write()



