

'''simple docstring'''



import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


__snake_case			:     Dict										=      datasets.utils.logging.get_logger(__name__)

__snake_case			:     Optional[Any]										=      ['names', 'prefix']
__snake_case			:     Dict										=      ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols']
__snake_case			:     Optional[Any]										=      ['encoding_errors', 'on_bad_lines']
__snake_case			:     Any										=      ['date_format']



@dataclass
class lowerCamelCase			(  datasets.BuilderConfig						):



			'''simple docstring'''






			__snake_case        =	","
			__snake_case        =	None
			__snake_case        =	"infer"
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	True
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	False
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	False
			__snake_case        =	True
			__snake_case        =	None
			__snake_case        =	"."
			__snake_case        =	None
			__snake_case        =	'"'
			__snake_case        =	0
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	None
			__snake_case        =	True
			__snake_case        =	True
			__snake_case        =	0
			__snake_case        =	True
			__snake_case        =	False
			__snake_case        =	None
			__snake_case        =	1_0000
			__snake_case        =	None
			__snake_case        =	"strict"
			__snake_case        =	"error"
			__snake_case        =	None


			def lowercase__						(				self	:						Dict			)      ->		List[str]:





									'''simple docstring'''
									if self.delimiter is not None:
															A__					:       int     =self.delimiter
									if self.column_names is not None:
															A__					:       List[Any]     =self.column_names



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





									'''simple docstring'''
									A__					:       Optional[Any]     ={
									    """sep""": self.sep,
									    """header""": self.header,
									    """names""": self.names,
									    """index_col""": self.index_col,
									    """usecols""": self.usecols,
									    """prefix""": self.prefix,
									    """mangle_dupe_cols""": self.mangle_dupe_cols,
									    """engine""": self.engine,
									    """converters""": self.converters,
									    """true_values""": self.true_values,
									    """false_values""": self.false_values,
									    """skipinitialspace""": self.skipinitialspace,
									    """skiprows""": self.skiprows,
									    """nrows""": self.nrows,
									    """na_values""": self.na_values,
									    """keep_default_na""": self.keep_default_na,
									    """na_filter""": self.na_filter,
									    """verbose""": self.verbose,
									    """skip_blank_lines""": self.skip_blank_lines,
									    """thousands""": self.thousands,
									    """decimal""": self.decimal,
									    """lineterminator""": self.lineterminator,
									    """quotechar""": self.quotechar,
									    """quoting""": self.quoting,
									    """escapechar""": self.escapechar,
									    """comment""": self.comment,
									    """encoding""": self.encoding,
									    """dialect""": self.dialect,
									    """error_bad_lines""": self.error_bad_lines,
									    """warn_bad_lines""": self.warn_bad_lines,
									    """skipfooter""": self.skipfooter,
									    """doublequote""": self.doublequote,
									    """memory_map""": self.memory_map,
									    """float_precision""": self.float_precision,
									    """chunksize""": self.chunksize,
									    """encoding_errors""": self.encoding_errors,
									    """on_bad_lines""": self.on_bad_lines,
									    """date_format""": self.date_format,
									}

									# some kwargs must not be passed if they don't have a default value
									# some others are deprecated and we can also not pass them if they are the default value
									for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
															if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()		,      lowerCAmelCase_			):
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
									if not (datasets.config.PANDAS_VERSION.major >= 2):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
									if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
															for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
																					del pd_read_csv_kwargs[pd_read_csv_parameter]

									return pd_read_csv_kwargs



class lowerCamelCase			(  datasets.ArrowBasedBuilder						):



			'''simple docstring'''






			__snake_case        =	CsvConfig


			def lowercase__						(				self	:						Any			)      ->		str:





									'''simple docstring'''
									return datasets.DatasetInfo(features=self.config.features			)


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





									'''simple docstring'''
									if not self.config.data_files:
															raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}"			)
									A__					:       Optional[int]     =dl_manager.download_and_extract(self.config.data_files			)
									if isinstance(lowerCAmelCase_		,      (str, list, tuple)			):
															A__					:       int     =data_files
															if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
																					A__					:       Union[str, Any]     =[files]
															A__					:       Dict     =[dl_manager.iter_files(lowerCAmelCase_			) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,      gen_kwargs={"""files""": files}			)]
									A__					:       int     =[]
									for split_name, files in data_files.items():
															if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			):
																					A__					:       int     =[files]
															A__					:       List[Any]     =[dl_manager.iter_files(lowerCAmelCase_			) for file in files]
															splits.append(datasets.SplitGenerator(name=lowerCAmelCase_		,      gen_kwargs={"""files""": files}			)			)
									return splits


			def lowercase__						(				self	:						List[Any]		,      lowerCAmelCase_	:						pa.Table			)      ->		pa.Table:





									'''simple docstring'''
									if self.config.features is not None:
															A__					:       Optional[int]     =self.config.features.arrow_schema
															if all(not require_storage_cast(lowerCAmelCase_			) for feature in self.config.features.values()			):
																					# cheaper cast
																					A__					:       Optional[Any]     =pa.Table.from_arrays([pa_table[field.name] for field in schema]		,      schema=lowerCAmelCase_			)
															else:
																					# more expensive cast; allows str <-> int/float or str to Audio for example
																					A__					:       Union[str, Any]     =table_cast(lowerCAmelCase_		,      lowerCAmelCase_			)
									return pa_table



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





									'''simple docstring'''
									A__					:       List[str]     =self.config.features.arrow_schema if self.config.features else None
									# dtype allows reading an int column as str
									A__					:       Union[str, Any]     =(
									    {
									        name: dtype.to_pandas_dtype() if not require_storage_cast(lowerCAmelCase_			) else object
									        for name, dtype, feature in zip(schema.names		,      schema.types		,      self.config.features.values()			)
									    }
									    if schema is not None
									    else None
									)
									for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCAmelCase_			)			):
															A__					:       Tuple     =pd.read_csv(lowerCAmelCase_		,      iterator=lowerCAmelCase_		,      dtype=lowerCAmelCase_		,      **self.config.pd_read_csv_kwargs			)
															try:
																					for batch_idx, df in enumerate(lowerCAmelCase_			):
																											A__					:       int     =pa.Table.from_pandas(lowerCAmelCase_			)
																											# Uncomment for debugging (will print the Arrow table size and elements)
																											# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																											# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																											yield (file_idx, batch_idx), self._cast_table(lowerCAmelCase_			)
															except ValueError as e:
																					logger.error(f"Failed to read file '{file}' with error {type(lowerCAmelCase_			)}: {e}"			)
																					raise




'''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()

