

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

import numpy as np


__snake_case			:     Optional[Any]										=      re.compile(r'\b(a|an|the)\b', re.UNICODE)

__snake_case			:     List[str]										=      None
def 						__lowerCamelCase	(       )	->							Dict:






						"""simple docstring"""





						A__					:       Tuple     =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=__snake_case,		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=__snake_case,		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 						__lowerCamelCase	(       __snake_case					:		int	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       int     ={}
						for article in dataset:
												for p in article["paragraphs"]:
																		for qa in p["qas"]:
																								A__					:       List[Any]     =bool(qa["""answers"""]["""text"""]	)
						return qid_to_has_ans
def 						__lowerCamelCase	(       __snake_case					:		Union[str, Any]	)	->							Tuple:






						"""simple docstring"""





						def remove_articles(__snake_case					:		Union[str, Any]	):
												return ARTICLES_REGEX.sub(""" """,		__snake_case	)

						def white_space_fix(__snake_case					:		Optional[Any]	):
												return " ".join(text.split()	)

						def remove_punc(__snake_case					:		Any	):
												A__					:       Optional[Any]     =set(string.punctuation	)
												return "".join(ch for ch in text if ch not in exclude	)

						def lower(__snake_case					:		int	):
												return text.lower()

						return white_space_fix(remove_articles(remove_punc(lower(__snake_case	)	)	)	)
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							Union[str, Any]:






						"""simple docstring"""





						if not s:
												return []
						return normalize_answer(__snake_case	).split()
def 						__lowerCamelCase	(       __snake_case					:		Optional[Any],		__snake_case					:		Union[str, Any]	)	->							str:






						"""simple docstring"""





						return int(normalize_answer(__snake_case	) == normalize_answer(__snake_case	)	)
def 						__lowerCamelCase	(       __snake_case					:		Any,		__snake_case					:		Dict	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Optional[Any]     =get_tokens(__snake_case	)
						A__					:       Union[str, Any]     =get_tokens(__snake_case	)
						A__					:       Optional[Any]     =collections.Counter(__snake_case	) & collections.Counter(__snake_case	)
						A__					:       Dict     =sum(common.values()	)
						if len(__snake_case	) == 0 or len(__snake_case	) == 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__					:       Tuple     =1.0 * num_same / len(__snake_case	)
						A__					:       Dict     =1.0 * num_same / len(__snake_case	)
						A__					:       Tuple     =(2 * precision * recall) / (precision + recall)
						return fa
def 						__lowerCamelCase	(       __snake_case					:		int,		__snake_case					:		Optional[Any]	)	->							Any:






						"""simple docstring"""





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






						"""simple docstring"""





						A__					:       Union[str, Any]     ={}
						for qid, s in scores.items():
												A__					:       Dict     =na_probs[qid] > na_prob_thresh
												if pred_na:
																		A__					:       Union[str, Any]     =float(not qid_to_has_ans[qid]	)
												else:
																		A__					:       Tuple     =s
						return new_scores
def 						__lowerCamelCase	(       __snake_case					:		List[Any],		__snake_case					:		Any,		__snake_case					:		List[Any]=None	)	->							Union[str, Any]:






						"""simple docstring"""





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






						"""simple docstring"""





						for k in new_eval:
												A__					:       str     =new_eval[k]
def 						__lowerCamelCase	(       __snake_case					:		int,		__snake_case					:		List[str],		__snake_case					:		Any,		__snake_case					:		Optional[int]	)	->							Optional[int]:






						"""simple docstring"""





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






						"""simple docstring"""





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






						"""simple docstring"""





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






						"""simple docstring"""





						if not qid_list:
												return
						A__					:       Any     =[na_probs[k] for k in qid_list]
						A__					:       List[Any]     =np.ones_like(__snake_case	) / float(len(__snake_case	)	)
						plt.hist(__snake_case,		weights=__snake_case,		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(__snake_case,		f"na_prob_hist_{name}.png"	)	)
						plt.clf()
def 						__lowerCamelCase	(       __snake_case					:		Optional[Any],		__snake_case					:		List[str],		__snake_case					:		Optional[Any],		__snake_case					:		str	)	->							str:






						"""simple docstring"""





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






						"""simple docstring"""





						A__					:       Optional[int]     =find_best_thresh(__snake_case,		__snake_case,		__snake_case,		__snake_case	)
						A__					:       List[Any]     =find_best_thresh(__snake_case,		__snake_case,		__snake_case,		__snake_case	)
						A__					:       int     =best_exact
						A__					:       int     =exact_thresh
						A__					:       List[str]     =best_fa
						A__					:       str     =fa_thresh
def 						__lowerCamelCase	(       )	->							Union[str, Any]:






						"""simple docstring"""





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


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

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




'''simple docstring'''



import collections
import json
import math
import os
import re
import time
from fnmatch import fnmatch
from typing import Dict

import requests
from slack_sdk import WebClient


__snake_case			:     Optional[int]										=      WebClient(token=os.environ['CI_SLACK_BOT_TOKEN'])
def 						__lowerCamelCase	(       __snake_case					:		List[Any]	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Any     =test_results.split(""" """	)

						A__					:       List[Any]     =0
						A__					:       Optional[int]     =0

						# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
						# When it is too long, those signs are not present.
						A__					:       Dict     =expressions[-2] if """=""" in expressions[-1] else expressions[-1]

						for i, expression in enumerate(__snake_case	):
												if "failed" in expression:
																		failed += int(expressions[i - 1]	)
												if "passed" in expression:
																		success += int(expressions[i - 1]	)

						return failed, success, time_spent
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							Optional[int]:






						"""simple docstring"""





						A__					:       Dict     ={}
						A__					:       List[Any]     =None
						A__					:       Any     =False
						for line in failures_short_lines.split("""\n"""	):
												if re.search(r"""_ \[doctest\]""",		__snake_case	):
																		A__					:       List[str]     =True
																		A__					:       Optional[int]     =line.split(""" """	)[2]
												elif in_error and not line.split(""" """	)[0].isdigit():
																		A__					:       List[str]     =line
																		A__					:       int     =False

						return failures



class lowerCamelCase			:



			'''simple docstring'''






			def __init__(				self	:						str		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Dict			)      ->		Dict:





									'''simple docstring'''
									A__					:       Any     =title

									A__					:       List[Any]     =doc_test_results["""time_spent"""].split(""","""			)[0]
									A__					:       str     =doc_test_results["""success"""]
									A__					:       str     =doc_test_results["""failures"""]
									A__					:       Optional[int]     =self.n_success + self.n_failures

									# Failures and success of the modeling tests
									A__					:       List[Any]     =doc_test_results


			@property
			def lowercase__						(				self	:						Optional[int]			)      ->		str:





									'''simple docstring'''
									A__					:       List[str]     =[self._time_spent]
									A__					:       str     =0

									for time in time_spent:
															A__					:       Union[str, Any]     =time.split(""":"""			)

															# Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
															if len(lowerCAmelCase_			) == 1:
																					A__					:       str     =[0, 0, time_parts[0]]

															A__   ,						A__   ,						A__					:       int     =int(time_parts[0]			), int(time_parts[1]			), float(time_parts[2]			)
															total_secs += hours * 36_00 + minutes * 60 + seconds

									A__   ,						A__   ,						A__					:       Optional[int]     =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60
									return f"{int(lowerCAmelCase_			)}h{int(lowerCAmelCase_			)}m{int(lowerCAmelCase_			)}s"


			@property
			def lowercase__						(				self	:						Any			)      ->		Dict:





									'''simple docstring'''
									return {"type": "header", "text": {"type": "plain_text", "text": self.title}}


			@property
			def lowercase__						(				self	:						Dict			)      ->		Dict:





									'''simple docstring'''
									return {
									    "type": "section",
									    "text": {
									        "type": "plain_text",
									        "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.",
									        "emoji": True,
									    },
									    "accessory": {
									        "type": "button",
									        "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
									        "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
									    },
									}


			@property
			def lowercase__						(				self	:						Tuple			)      ->		Dict:





									'''simple docstring'''
									return {
									    "type": "section",
									    "text": {
									        "type": "plain_text",
									        "text": (
									            f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in"
									            f" {self.time}."
									        ),
									        "emoji": True,
									    },
									    "accessory": {
									        "type": "button",
									        "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
									        "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
									    },
									}


			@property
			def lowercase__						(				self	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Optional[Any]     =40
									A__					:       List[Any]     ={k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			)}

									A__					:       Union[str, Any]     =""""""
									for category, failures in category_failures.items():
															if len(lowerCAmelCase_			) == 0:
																					continue

															if report != "":
																					report += "\n\n"

															report += f"*{category} failures*:".ljust(line_length // 2			).rjust(line_length // 2			) + "\n"
															report += "`"
															report += "`\n`".join(lowerCAmelCase_			)
															report += "`"

									return {
									    "type": "section",
									    "text": {
									        "type": "mrkdwn",
									        "text": f"The following examples had failures:\n\n\n{report}\n",
									    },
									}


			@property
			def lowercase__						(				self	:						Any			)      ->		str:





									'''simple docstring'''
									A__					:       Tuple     =[self.header]

									if self.n_failures > 0:
															blocks.append(self.failures			)

									if self.n_failures > 0:
															blocks.extend([self.category_failures]			)

									if self.n_failures == 0:
															blocks.append(self.no_failures			)

									return json.dumps(lowerCAmelCase_			)


			@staticmethod
			def lowercase__						(				)      ->		Any:





									'''simple docstring'''
									A__					:       Dict     =[
									    {
									        """type""": """section""",
									        """text""": {
									            """type""": """plain_text""",
									            """text""": """There was an issue running the tests.""",
									        },
									        """accessory""": {
									            """type""": """button""",
									            """text""": {"""type""": """plain_text""", """text""": """Check Action results""", """emoji""": True},
									            """url""": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}",
									        },
									    }
									]

									print("""Sending the following payload"""			)
									print(json.dumps({"""blocks""": json.loads(lowerCAmelCase_			)}			)			)

									client.chat_postMessage(
									    channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""]		,      text="""There was an issue running the tests."""		,      blocks=lowerCAmelCase_		,      )


			def lowercase__						(				self	:						Optional[int]			)      ->		Tuple:





									'''simple docstring'''
									print("""Sending the following payload"""			)
									print(json.dumps({"""blocks""": json.loads(self.payload			)}			)			)

									A__					:       Tuple     =f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else """All tests passed."""

									A__					:       Optional[int]     =client.chat_postMessage(
									    channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""]		,      blocks=self.payload		,      text=lowerCAmelCase_		,      )


			def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       int     =""""""
									for key, value in failures.items():
															A__					:       Optional[int]     =value[:2_00] + """ [Truncated]""" if len(lowerCAmelCase_			) > 2_50 else value
															failures_text += f"*{key}*\n_{value}_\n\n"

									A__					:       List[Any]     =job_name
									A__					:       Dict     ={"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}}

									if job_link is not None:
															A__					:       Dict     ={
															    """type""": """button""",
															    """text""": {"""type""": """plain_text""", """text""": """GitHub Action job""", """emoji""": True},
															    """url""": job_link,
															}

									return [
									    {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}},
									    content,
									    {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}},
									]



			def lowercase__						(				self	:						str			)      ->		str:





									'''simple docstring'''
									if self.thread_ts is None:
															raise ValueError("""Can only post reply if a post has been made."""			)

									A__					:       Optional[Any]     =self.doc_test_results.pop("""job_link"""			)
									self.doc_test_results.pop("""failures"""			)
									self.doc_test_results.pop("""success"""			)
									self.doc_test_results.pop("""time_spent"""			)

									A__					:       Union[str, Any]     =sorted(self.doc_test_results.items()		,      key=lambda lowerCAmelCase_			: t[0]			)
									for job, job_result in sorted_dict:
															if len(job_result["""failures"""]			):
																					A__					:       Optional[Any]     =f"*Num failures* :{len(job_result['failed']			)} \n"
																					A__					:       Tuple     =job_result["""failures"""]
																					A__					:       Optional[Any]     =self.get_reply_blocks(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      text=lowerCAmelCase_			)

																					print("""Sending the following reply"""			)
																					print(json.dumps({"""blocks""": blocks}			)			)

																					client.chat_postMessage(
																					    channel=os.environ["""CI_SLACK_CHANNEL_ID_DAILY"""]		,      text=f"Results for {job}"		,      blocks=lowerCAmelCase_		,      thread_ts=self.thread_ts["""ts"""]		,      )

																					time.sleep(1			)


def 						__lowerCamelCase	(       )	->							Any:






						"""simple docstring"""





						A__					:       Optional[Any]     =os.environ["""GITHUB_RUN_ID"""]
						A__					:       Tuple     =f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100"
						A__					:       List[str]     =requests.get(__snake_case	).json()
						A__					:       List[str]     ={}

						try:
												jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]}	)
												A__					:       Optional[int]     =math.ceil((result["""total_count"""] - 100) / 100	)

												for i in range(__snake_case	):
																		A__					:       List[Any]     =requests.get(url + f"&page={i + 2}"	).json()
																		jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]}	)

												return jobs
						except Exception as e:
												print("""Unknown error, could not fetch links.""",		__snake_case	)

						return {}
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Any     ={}

						if os.path.exists(__snake_case	):
												A__					:       str     =os.listdir(__snake_case	)
												for file in files:
																		try:
																								with open(os.path.join(__snake_case,		__snake_case	),		encoding="""utf-8"""	) as f:
																														A__					:       Tuple     =f.read()
																		except UnicodeDecodeError as e:
																								raise ValueError(f"Could not open {os.path.join(__snake_case,		__snake_case	)}."	) from e

						return _artifact
def 						__lowerCamelCase	(       )	->							Union[str, Any]:






						"""simple docstring"""





						class lowerCamelCase			:



									'''simple docstring'''






									def __init__(				self	:						List[str]		,      lowerCAmelCase_	:						str			)      ->		Any:





															'''simple docstring'''
															A__					:       List[Any]     =name
															A__					:       str     =[]


									def __str__(				self	:						Optional[Any]			)      ->		List[Any]:





															'''simple docstring'''
															return self.name



									def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						str			)      ->		Tuple:





															'''simple docstring'''
															self.paths.append({"""name""": self.name, """path""": path}			)


						A__					:       Dict[str, Artifact]     ={}

						A__					:       int     =filter(os.path.isdir,		os.listdir()	)
						for directory in directories:
												A__					:       List[Any]     =directory
												if artifact_name not in _available_artifacts:
																		A__					:       str     =Artifact(__snake_case	)

																		_available_artifacts[artifact_name].add_path(__snake_case	)

						return _available_artifacts


if __name__ == "__main__":
		__snake_case			:     List[str]										=      get_job_links()
		__snake_case			:     int										=      retrieve_available_artifacts()

		__snake_case			:     Union[str, Any]										=      collections.OrderedDict(
		    [
		        ('*.py', 'API Examples'),
		        ('*.md', 'MD Examples'),
		    ]
		)

		# This dict will contain all the information relative to each doc test category:
		# - failed: list of failed tests
		# - failures: dict in the format 'test': 'error_message'
		__snake_case			:     Dict										=      {
		    v: {
		        'failed': [],
		        'failures': {},
		    }
		    for v in docs.values()
		}

		# Link to the GitHub Action job
		__snake_case			:     List[Any]										=      github_actions_job_links.get('run_doctests')

		__snake_case			:     Tuple										=      available_artifacts['doc_tests_gpu_test_reports'].paths[0]
		__snake_case			:     Optional[int]										=      retrieve_artifact(artifact_path['name'])
		if "stats" in artifact:
				__snake_case						,       __snake_case						,       __snake_case			:     Optional[Any]										=      handle_test_results(artifact['stats'])
				__snake_case			:     Optional[Any]										=      failed
				__snake_case			:     Union[str, Any]										=      success
				__snake_case			:     Union[str, Any]										=      time_spent[1:-1] + ', '

				__snake_case			:     int										=      extract_first_line_failure(artifact['failures_short'])
				for line in artifact["summary_short"].split('\n'):
						if re.search('FAILED', line):
								__snake_case			:     Optional[int]										=      line.replace('FAILED ', '')
								__snake_case			:     str										=      line.split()[0].replace('\n', '')

								if "::" in line:
										__snake_case						,       __snake_case			:     Optional[Any]										=      line.split('::')
								else:
										__snake_case						,       __snake_case			:     Any										=      line, line

								for file_regex in docs.keys():
										if fnmatch(file_path, file_regex):
												__snake_case			:     List[Any]										=      docs[file_regex]
												doc_test_results[category]["failed"].append(test)

												__snake_case			:     List[str]										=      all_failures[test] if test in all_failures else 'N/A'
												__snake_case			:     Optional[Any]										=      failure
												break

		__snake_case			:     int										=      Message('🤗 Results of the doc tests.', doc_test_results)
		message.post()
		message.post_reply()

