




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







def   _snake_case    (       lowercase__	):

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

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

				def remove_punc(lowercase__	):
								_lowerCamelCase  :    Tuple					=					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   _snake_case    (       lowercase__	):
				if not s:
								return []
				return normalize_answer(lowercase__	).split()







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







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







def   _snake_case    (       lowercase__							,					lowercase__	):
				_lowerCamelCase  :    Optional[int]					=					{}
				_lowerCamelCase  :    str					=					{}
				for article in dataset:
								for p in article["paragraphs"]:
												for qa in p["qas"]:
																_lowerCamelCase  :    Dict					=					qa['id']
																_lowerCamelCase  :    Optional[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
																				_lowerCamelCase  :    Optional[Any]					=					['']
																if qid not in preds:
																				print(f'''Missing prediction for {qid}'''	)
																				continue
																_lowerCamelCase  :    int					=					preds[qid]
																# Take max over all gold answers
																_lowerCamelCase  :    List[str]					=					max(compute_exact(lowercase__							,					lowercase__	) for a in gold_answers	)
																_lowerCamelCase  :    List[Any]					=					max(compute_fa(lowercase__							,					lowercase__	) for a in gold_answers	)
				return exact_scores, fa_scores







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				_lowerCamelCase  :    Any					=					{}
				for qid, s in scores.items():
								_lowerCamelCase  :    List[str]					=					na_probs[qid] > na_prob_thresh
								if pred_na:
												_lowerCamelCase  :    Any					=					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[Any]					=					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:
								_lowerCamelCase  :    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   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__	):
				for k in new_eval:
								_lowerCamelCase  :    List[str]					=					new_eval[k]







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				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   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__=None							,					lowercase__=None	):
				_lowerCamelCase  :    Tuple					=					sorted(lowercase__							,					key=lambda lowercase__	: na_probs[k]	)
				_lowerCamelCase  :    Any					=					0.0
				_lowerCamelCase  :    List[Any]					=					1.0
				_lowerCamelCase  :    Union[str, Any]					=					0.0
				_lowerCamelCase  :    Dict					=					[1.0]
				_lowerCamelCase  :    Optional[Any]					=					[0.0]
				_lowerCamelCase  :    str					=					0.0
				for i, qid in enumerate(lowercase__	):
								if qid_to_has_ans[qid]:
												true_pos += scores[qid]
								_lowerCamelCase  :    Tuple					=					true_pos / float(i + 1	)
								_lowerCamelCase  :    str					=					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   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				if out_image_dir and not os.path.exists(lowercase__	):
								os.makedirs(lowercase__	)
				_lowerCamelCase  :    str					=					sum(1 for v in qid_to_has_ans.values() if v	)
				if num_true_pos == 0:
								return
				_lowerCamelCase  :    Tuple					=					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'							,					)
				_lowerCamelCase  :    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'							,					)
				_lowerCamelCase  :    List[Any]					=					{k: float(lowercase__	) for k, v in qid_to_has_ans.items()}
				_lowerCamelCase  :    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   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				if not qid_list:
								return
				_lowerCamelCase  :    Union[str, Any]					=					[na_probs[k] for k in qid_list]
				_lowerCamelCase  :    Union[str, 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   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__							,					lowercase__	):
				_lowerCamelCase  :    Tuple					=					sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]	)
				_lowerCamelCase  :    Optional[int]					=					num_no_ans
				_lowerCamelCase  :    Optional[int]					=					cur_score
				_lowerCamelCase  :    List[Any]					=					0.0
				_lowerCamelCase  :    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]:
												_lowerCamelCase  :    str					=					scores[qid]
								else:
												if preds[qid]:
																_lowerCamelCase  :    int					=					-1
												else:
																_lowerCamelCase  :    Optional[Any]					=					0
								cur_score += diff
								if cur_score > best_score:
												_lowerCamelCase  :    List[Any]					=					cur_score
												_lowerCamelCase  :    Optional[int]					=					na_probs[qid]
				return 1_0_0.0 * best_score / len(lowercase__	), best_thresh







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







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

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





"""simple docstring"""






import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase__  		=		logging.get_logger(__name__)

lowercase__  		=		{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    """sew-d"""
			def __init__(						self						,   lowercase=32						,   lowercase=768						,   lowercase=12						,   lowercase=12						,   lowercase=3072						,   lowercase=2						,   lowercase=512						,   lowercase=256						,   lowercase=True						,   lowercase=True						,   lowercase=("p2c", "c2p")						,   lowercase="layer_norm"						,   lowercase="gelu_python"						,   lowercase=0.1						,   lowercase=0.1						,   lowercase=0.1						,   lowercase=0.0						,   lowercase=0.1						,   lowercase=0.02						,   lowercase=1E-7						,   lowercase=1E-5						,   lowercase="group"						,   lowercase="gelu"						,   lowercase=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)						,   lowercase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)						,   lowercase=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)						,   lowercase=False						,   lowercase=128						,   lowercase=16						,   lowercase=True						,   lowercase=0.05						,   lowercase=10						,   lowercase=2						,   lowercase=0.0						,   lowercase=10						,   lowercase=0						,   lowercase="mean"						,   lowercase=False						,   lowercase=False						,   lowercase=256						,   lowercase=0						,   lowercase=1						,   lowercase=2						,   **lowercase						,   ):
							super().__init__(**lowercase						,   pad_token_id=lowercase						,   bos_token_id=lowercase						,   eos_token_id=lowercase						)
							_lowerCamelCase  :    List[str]					=					hidden_size
							_lowerCamelCase  :    int					=					feat_extract_norm
							_lowerCamelCase  :    Optional[Any]					=					feat_extract_activation
							_lowerCamelCase  :    Optional[Any]					=					list(lowercase						)
							_lowerCamelCase  :    Union[str, Any]					=					list(lowercase						)
							_lowerCamelCase  :    Optional[Any]					=					list(lowercase						)
							_lowerCamelCase  :    List[str]					=					conv_bias
							_lowerCamelCase  :    str					=					num_conv_pos_embeddings
							_lowerCamelCase  :    Optional[Any]					=					num_conv_pos_embedding_groups
							_lowerCamelCase  :    Tuple					=					len(self.conv_dim						)
							_lowerCamelCase  :    Optional[int]					=					num_hidden_layers
							_lowerCamelCase  :    List[str]					=					intermediate_size
							_lowerCamelCase  :    Dict					=					squeeze_factor
							_lowerCamelCase  :    Any					=					max_position_embeddings
							_lowerCamelCase  :    List[str]					=					position_buckets
							_lowerCamelCase  :    Dict					=					share_att_key
							_lowerCamelCase  :    List[str]					=					relative_attention
							_lowerCamelCase  :    Optional[Any]					=					norm_rel_ebd
							_lowerCamelCase  :    List[Any]					=					list(lowercase						)
							_lowerCamelCase  :    List[Any]					=					hidden_act
							_lowerCamelCase  :    Optional[Any]					=					num_attention_heads
							_lowerCamelCase  :    Optional[int]					=					hidden_dropout
							_lowerCamelCase  :    Optional[int]					=					attention_dropout
							_lowerCamelCase  :    Any					=					activation_dropout
							_lowerCamelCase  :    Tuple					=					feat_proj_dropout
							_lowerCamelCase  :    Any					=					final_dropout
							_lowerCamelCase  :    str					=					layer_norm_eps
							_lowerCamelCase  :    Tuple					=					feature_layer_norm_eps
							_lowerCamelCase  :    Any					=					initializer_range
							_lowerCamelCase  :    Dict					=					vocab_size

							if (
							    (len(self.conv_stride						) != self.num_feat_extract_layers)
							    or (len(self.conv_kernel						) != self.num_feat_extract_layers)
							    or (len(self.conv_dim						) != self.num_feat_extract_layers)
							):
											raise ValueError(
											    'Configuration for convolutional layers is incorrect.'
											    'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'
											    F'''but is `len(config.conv_dim) = {len(self.conv_dim						)}`, `len(config.conv_stride)'''
											    F'''= {len(self.conv_stride						)}`, `len(config.conv_kernel) = {len(self.conv_kernel						)}`.'''						)

							# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
							_lowerCamelCase  :    Dict					=					apply_spec_augment
							_lowerCamelCase  :    int					=					mask_time_prob
							_lowerCamelCase  :    Union[str, Any]					=					mask_time_length
							_lowerCamelCase  :    Optional[Any]					=					mask_time_min_masks
							_lowerCamelCase  :    List[Any]					=					mask_feature_prob
							_lowerCamelCase  :    Union[str, Any]					=					mask_feature_length
							_lowerCamelCase  :    List[Any]					=					mask_feature_min_masks

							# ctc loss
							_lowerCamelCase  :    List[str]					=					ctc_loss_reduction
							_lowerCamelCase  :    List[str]					=					ctc_zero_infinity

							# sequence classification
							_lowerCamelCase  :    Dict					=					use_weighted_layer_sum
							_lowerCamelCase  :    List[Any]					=					classifier_proj_size






			@property
			def       A_					(						self						):
							return functools.reduce(operator.mul						,   self.conv_stride						,   1						)