





'''simple docstring'''






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

import numpy as np


A             =			re.compile(r'\b(a|an|the)\b', re.UNICODE)

A             =			None





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





def       lowercase_      (		lowercase__						)   ->Any:

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

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

						def remove_punc(lowercase__						):
												_snake_case:   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(lowercase__						)						)						)						)





def       lowercase_      (		lowercase__						)   ->List[str]:
						if not s:
												return []
						return normalize_answer(lowercase__						).split()





def       lowercase_      (		lowercase__				,  lowercase__						)   ->Union[str, Any]:
						return int(normalize_answer(lowercase__						) == normalize_answer(lowercase__						)						)





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





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





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





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__=None						)   ->Optional[Any]:
						if not qid_list:
												_snake_case:   Dict  					=		len(lowercase__						)
												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:
												_snake_case:   Dict  					=		len(lowercase__						)
												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       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__						)   ->Any:
						for k in new_eval:
												_snake_case:   Tuple  					=		new_eval[k]





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->List[Any]:
						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.0_5]						)
						plt.ylim([0.0, 1.0_5]						)
						plt.title(lowercase__						)
						plt.savefig(lowercase__						)
						plt.clf()





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





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->List[Any]:
						if out_image_dir and not os.path.exists(lowercase__						):
												os.makedirs(lowercase__						)
						_snake_case:   Dict  					=		sum(1 for v in qid_to_has_ans.values() if v						)
						if num_true_pos == 0:
												return
						_snake_case:   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'				,  )
						_snake_case:   Dict  					=		make_precision_recall_eval(
						    lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  out_image=os.path.join(lowercase__				,  'pr_f1.png'						)				,  title='Precision-Recall curve for F1 score'				,  )
						_snake_case:   Any  					=		{k: float(lowercase__						) for k, v in qid_to_has_ans.items()}
						_snake_case:   str  					=		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       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->int:
						if not qid_list:
												return
						_snake_case:   Union[str, Any]  					=		[na_probs[k] for k in qid_list]
						_snake_case:   Any  					=		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       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->Tuple:
						_snake_case:   int  					=		sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]						)
						_snake_case:   str  					=		num_no_ans
						_snake_case:   Dict  					=		cur_score
						_snake_case:   Optional[Any]  					=		0.0
						_snake_case:   Dict  					=		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]:
																		_snake_case:   Dict  					=		scores[qid]
												else:
																		if preds[qid]:
																								_snake_case:   Union[str, Any]  					=		-1
																		else:
																								_snake_case:   Tuple  					=		0
												cur_score += diff
												if cur_score > best_score:
																		_snake_case:   int  					=		cur_score
																		_snake_case:   int  					=		na_probs[qid]
						return 1_0_0.0 * best_score / len(lowercase__						), best_thresh





def       lowercase_      (		lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)   ->Dict:
						_snake_case:   List[str]  					=		find_best_thresh(lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)
						_snake_case:   List[str]  					=		find_best_thresh(lowercase__				,  lowercase__				,  lowercase__				,  lowercase__						)
						_snake_case:   int  					=		best_exact
						_snake_case:   Any  					=		exact_thresh
						_snake_case:   str  					=		best_fa
						_snake_case:   Any  					=		fa_thresh





def       lowercase_      (		)   ->int:
						with open(OPTS.data_file						) as f:
												_snake_case:   Any  					=		json.load(lowercase__						)
												_snake_case:   Optional[Any]  					=		dataset_json["""data"""]
						with open(OPTS.pred_file						) as f:
												_snake_case:   List[Any]  					=		json.load(lowercase__						)
						if OPTS.na_prob_file:
												with open(OPTS.na_prob_file						) as f:
																		_snake_case:   Union[str, Any]  					=		json.load(lowercase__						)
						else:
												_snake_case:   int  					=		{k: 0.0 for k in preds}
						_snake_case:   List[str]  					=		make_qid_to_has_ans(lowercase__						)  # maps qid to True/False
						_snake_case:   str  					=		[k for k, v in qid_to_has_ans.items() if v]
						_snake_case:   Optional[Any]  					=		[k for k, v in qid_to_has_ans.items() if not v]
						_snake_case:   Union[str, Any]  					=		get_raw_scores(lowercase__				,  lowercase__						)
						_snake_case:   Any  					=		apply_no_ans_threshold(lowercase__				,  lowercase__				,  lowercase__				,  OPTS.na_prob_thresh						)
						_snake_case:   Optional[int]  					=		apply_no_ans_threshold(lowercase__				,  lowercase__				,  lowercase__				,  OPTS.na_prob_thresh						)
						_snake_case:   Optional[Any]  					=		make_eval_dict(lowercase__				,  lowercase__						)
						if has_ans_qids:
												_snake_case:   int  					=		make_eval_dict(lowercase__				,  lowercase__				,  qid_list=lowercase__						)
												merge_eval(lowercase__				,  lowercase__				,  'HasAns'						)
						if no_ans_qids:
												_snake_case:   Union[str, 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__":
		A             =			parse_args()
		if OPTS.out_image_dir:
				import matplotlib

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












'''simple docstring'''






from __future__ import annotations

A   : Union[str, Any]             =			[-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]
A   : Optional[int]             =			[-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]





def       lowercase_      (		lowercase__						)   ->list[float]:
						_snake_case:   Tuple  					=		[]
						_snake_case:   List[Any]  					=		len(lowercase__						)

						for i in range(lowercase__						):
												_snake_case:   float  					=		-1
												for j in range(i + 1				,  lowercase__						):
																		if arr[i] < arr[j]:
																								_snake_case:   List[str]  					=		arr[j]
																								break
												result.append(lowercase__						)
						return result





def       lowercase_      (		lowercase__						)   ->list[float]:
						_snake_case:   Tuple  					=		[]
						for i, outer in enumerate(lowercase__						):
												_snake_case:   float  					=		-1
												for inner in arr[i + 1 :]:
																		if outer < inner:
																								_snake_case:   List[Any]  					=		inner
																								break
												result.append(lowercase__						)
						return result





def       lowercase_      (		lowercase__						)   ->list[float]:
						_snake_case:   int  					=		len(lowercase__						)
						_snake_case:   list[float]  					=		[]
						_snake_case:   list[float]  					=		[-1] * arr_size

						for index in reversed(range(lowercase__						)						):
												if stack:
																		while stack[-1] <= arr[index]:
																								stack.pop()
																								if not stack:
																														break
												if stack:
																		_snake_case:   Dict  					=		stack[-1]
												stack.append(arr[index]						)
						return result


if __name__ == "__main__":
		from doctest import testmod
		from timeit import timeit

		testmod()
		print(next_greatest_element_slow(arr))
		print(next_greatest_element_fast(arr))
		print(next_greatest_element(arr))

		A   : Union[str, Any]             =			(
		    'from __main__ import arr, next_greatest_element_slow, '
		    'next_greatest_element_fast, next_greatest_element'
		)
		print(
		    'next_greatest_element_slow():',
		    timeit('next_greatest_element_slow(arr)', setup=setup),
		)
		print(
		    'next_greatest_element_fast():',
		    timeit('next_greatest_element_fast(arr)', setup=setup),
		)
		print(
		    '     next_greatest_element():',
		    timeit('next_greatest_element(arr)', setup=setup),
		)





