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

import numpy as np


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

SCREAMING_SNAKE_CASE							:List[str]							 =				None


def 						UpperCAmelCase			(	)		->	Any:







				"""simple docstring"""



				__A   			= 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 						UpperCAmelCase			(	a_						)		->	Optional[int]:







				"""simple docstring"""



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


def 						UpperCAmelCase			(	a_						)		->	str:







				"""simple docstring"""



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

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

				def remove_punc(a_						):
								__A   			= set(string.punctuation						)
								return "".join(ch for ch in text if ch not in exclude						)

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

				return white_space_fix(remove_articles(remove_punc(lower(a_						)						)						)						)


def 						UpperCAmelCase			(	a_						)		->	Dict:







				"""simple docstring"""



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


def 						UpperCAmelCase			(	a_		,   a_						)		->	Tuple:







				"""simple docstring"""



				return int(normalize_answer(a_						) == normalize_answer(a_						)						)


def 						UpperCAmelCase			(	a_		,   a_						)		->	List[str]:







				"""simple docstring"""



				__A   			= get_tokens(a_						)
				__A   			= get_tokens(a_						)
				__A   			= collections.Counter(a_						) & collections.Counter(a_						)
				__A   			= 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
				__A   			= 1.0 * num_same / len(a_						)
				__A   			= 1.0 * num_same / len(a_						)
				__A   			= (2 * precision * recall) / (precision + recall)
				return fa


def 						UpperCAmelCase			(	a_		,   a_						)		->	Optional[Any]:







				"""simple docstring"""



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


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_						)		->	Dict:







				"""simple docstring"""



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


def 						UpperCAmelCase			(	a_		,   a_		,   a_=None						)		->	int:







				"""simple docstring"""



				if not qid_list:
								__A   			= len(a_						)
								return collections.OrderedDict(
								    [
								        ("exact", 100.0 * sum(exact_scores.values()						) / total),
								        ("f1", 100.0 * sum(fa_scores.values()						) / total),
								        ("total", total),
								    ]						)
				else:
								__A   			= len(a_						)
								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			(	a_		,   a_		,   a_						)		->	str:







				"""simple docstring"""



				for k in new_eval:
								__A   			= new_eval[k]


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_						)		->	Union[str, Any]:







				"""simple docstring"""



				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.05]						)
				plt.ylim([0.0, 1.05]						)
				plt.title(a_						)
				plt.savefig(a_						)
				plt.clf()


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_		,   a_=None		,   a_=None						)		->	int:







				"""simple docstring"""



				__A   			= sorted(a_		,   key=lambda a_						: na_probs[k]						)
				__A   			= 0.0
				__A   			= 1.0
				__A   			= 0.0
				__A   			= [1.0]
				__A   			= [0.0]
				__A   			= 0.0
				for i, qid in enumerate(a_						):
								if qid_to_has_ans[qid]:
												true_pos += scores[qid]
								__A   			= true_pos / float(i + 1						)
								__A   			= 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": 100.0 * avg_prec}


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_		,   a_		,   a_						)		->	List[str]:







				"""simple docstring"""



				if out_image_dir and not os.path.exists(a_						):
								os.makedirs(a_						)
				__A   			= sum(1 for v in qid_to_has_ans.values() if v						)
				if num_true_pos == 0:
								return
				__A   			= 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"		,   )
				__A   			= make_precision_recall_eval(
				    a_		,   a_		,   a_		,   a_		,   out_image=os.path.join(a_		,   "pr_f1.png"						)		,   title="Precision-Recall curve for F1 score"		,   )
				__A   			= {k: float(a_						) for k, v in qid_to_has_ans.items()}
				__A   			= 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 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_						)		->	List[str]:







				"""simple docstring"""



				if not qid_list:
								return
				__A   			= [na_probs[k] for k in qid_list]
				__A   			= np.ones_like(a_						) / float(len(a_						)						)
				plt.hist(a_		,   weights=a_		,   bins=2_0		,   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 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_						)		->	Any:







				"""simple docstring"""



				__A   			= sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]						)
				__A   			= num_no_ans
				__A   			= cur_score
				__A   			= 0.0
				__A   			= sorted(a_		,   key=lambda a_						: na_probs[k]						)
				for i, qid in enumerate(a_						):
								if qid not in scores:
												continue
								if qid_to_has_ans[qid]:
												__A   			= scores[qid]
								else:
												if preds[qid]:
																__A   			= -1
												else:
																__A   			= 0
								cur_score += diff
								if cur_score > best_score:
												__A   			= cur_score
												__A   			= na_probs[qid]
				return 100.0 * best_score / len(a_						), best_thresh


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_		,   a_		,   a_						)		->	Tuple:







				"""simple docstring"""



				__A			,							__A   			= find_best_thresh(a_		,   a_		,   a_		,   a_						)
				__A			,							__A   			= find_best_thresh(a_		,   a_		,   a_		,   a_						)
				__A   			= best_exact
				__A   			= exact_thresh
				__A   			= best_fa
				__A   			= fa_thresh


def 						UpperCAmelCase			(	)		->	int:







				"""simple docstring"""



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

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


def 						UpperCAmelCase			(	a_						)		->	list:







				"""simple docstring"""



				if len(a_						) <= 1:
								return lst

				__A   			= 1

				while i < len(a_						):
								if lst[i - 1] <= lst[i]:
												i += 1
								else:
												__A			,							__A   			= lst[i], lst[i - 1]
												i -= 1
												if i == 0:
																__A   			= 1

				return lst


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE							:List[Any]							 =				input('Enter numbers separated by a comma:\n').strip()
					SCREAMING_SNAKE_CASE							:List[Any]							 =				[int(item) for item in user_input.split(',')]
					print(gnome_sort(unsorted))
