



"""simple docstring"""






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

import numpy as np


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

lowercase__  		=		None







def   _snake_case    (       ):
				_lowerCamelCase  :    Optional[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=a__							,					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=a__							,					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    (       lowercase__	):
				_lowerCamelCase  :    Optional[Any]					=					{}
				for article in dataset:
								for p in article["paragraphs"]:
												for qa in p["qas"]:
																_lowerCamelCase  :    Optional[int]					=					bool(qa['answers']['text']	)
				return qid_to_has_ans







def   _snake_case    (       lowercase__	):

				def remove_articles(lowercase__	):
								return ARTICLES_REGEX.sub(' '							,					a__	)

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

				def remove_punc(lowercase__	):
								_lowerCamelCase  :    Optional[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(a__	)	)	)	)







def   _snake_case    (       lowercase__	):

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







def   _snake_case    (       lowercase__							,					lowercase__	):
				return int(normalize_answer(a__	) == normalize_answer(a__	)	)







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







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







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







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__=None	):

				if not qid_list:
								_lowerCamelCase  :    List[str]					=					len(a__	)
								return collections.OrderedDict(
								    [
								        ('exact', 1_0_0.0 * sum(exact_scores.values()	) / total),
								        ('f1', 1_0_0.0 * sum(fa_scores.values()	) / total),
								        ('total', total),
								    ]	)
				else:
								_lowerCamelCase  :    Union[str, Any]					=					len(a__	)
								return collections.OrderedDict(
								    [
								        ('exact', 1_0_0.0 * sum(exact_scores[k] for k in qid_list	) / total),
								        ('f1', 1_0_0.0 * sum(fa_scores[k] for k in qid_list	) / total),
								        ('total', total),
								    ]	)







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__	):

				for k in new_eval:
								_lowerCamelCase  :    Tuple					=					new_eval[k]







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				plt.step(a__							,					a__							,					color='b'							,					alpha=0.2							,					where='post'	)
				plt.fill_between(a__							,					a__							,					step='post'							,					alpha=0.2							,					color='b'	)
				plt.xlabel('Recall'	)
				plt.ylabel('Precision'	)
				plt.xlim([0.0, 1.0_5]	)
				plt.ylim([0.0, 1.0_5]	)
				plt.title(a__	)
				plt.savefig(a__	)
				plt.clf()







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







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):

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







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):

				if not qid_list:
								return
				_lowerCamelCase  :    str					=					[na_probs[k] for k in qid_list]
				_lowerCamelCase  :    Union[str, Any]					=					np.ones_like(a__	) / float(len(a__	)	)
				plt.hist(a__							,					weights=a__							,					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(a__							,					f'''na_prob_hist_{name}.png'''	)	)
				plt.clf()







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







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				_lowerCamelCase,				_lowerCamelCase  :    int					=					find_best_thresh(a__							,					a__							,					a__							,					a__	)
				_lowerCamelCase,				_lowerCamelCase  :    Tuple					=					find_best_thresh(a__							,					a__							,					a__							,					a__	)
				_lowerCamelCase  :    Tuple					=					best_exact
				_lowerCamelCase  :    Optional[Any]					=					exact_thresh
				_lowerCamelCase  :    Dict					=					best_fa
				_lowerCamelCase  :    List[Any]					=					fa_thresh







def   _snake_case    (       ):

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


if __name__ == "__main__":
			lowercase__  		=		parse_args()
			if OPTS.out_image_dir:
						import matplotlib

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





"""simple docstring"""






lowercase__  		=		[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

lowercase__  		=		[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

lowercase__  		=		[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

lowercase__  		=		[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

lowercase__  		=		[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

lowercase__  		=		[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

lowercase__  		=		[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

lowercase__  		=		[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]