


"""simple docstring"""


import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")

_snake_case          =							logging.getLogger(__name__)



@dataclass
class   _a      :
    a_    :				Optional[int]             =    field(
        default=128		,		metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }		,		)
    a_    :				bool             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} )
    a_    :				bool             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={
            'help': (
                'Whether to pad all samples to `max_seq_length`. '
                'If False, will pad the samples dynamically when batching to the maximum length in the batch.'
            )
        }		,		)
    a_    :				Optional[int]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={
            'help': (
                'For debugging purposes or quicker training, truncate the number of training examples to this '
                'value if set.'
            )
        }		,		)
    a_    :				Optional[int]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={
            'help': (
                'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
                'value if set.'
            )
        }		,		)
    a_    :				Optional[int]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={
            'help': (
                'For debugging purposes or quicker training, truncate the number of prediction examples to this '
                'value if set.'
            )
        }		,		)






@dataclass
class   _a      :
    a_    :				str             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
    a_    :				str             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Evaluation language. Also train language if `train_language` is set to None.'} )
    a_    :				Optional[str]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Train language if it is different from the evaluation language.'} )
    a_    :				Optional[str]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
    a_    :				Optional[str]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
    a_    :				Optional[str]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}		,		)
    a_    :				Optional[bool]             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'}		,		)
    a_    :				bool             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'}		,		)
    a_    :				str             =    field(
        default='main'		,		metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}		,		)
    a_    :				bool             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={
            'help': (
                'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
                'with private models).'
            )
        }		,		)
    a_    :				bool             =    field(
        default=SCREAMING_SNAKE_CASE_		,		metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}		,		)






def   snake_case						(				)->		Dict:
      '''simple docstring'''


      lowerCamelCase__           =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
      lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__           =		parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry('run_xnli'		,   _a							)

      # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'		,   datefmt='%m/%d/%Y %H:%M:%S'		,   handlers=[logging.StreamHandler(sys.stdout							)]		,   )

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      lowerCamelCase__           =		training_args.get_process_log_level()
      logger.setLevel(_a							)
      datasets.utils.logging.set_verbosity(_a							)
      transformers.utils.logging.set_verbosity(_a							)
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # Log on each process the small summary:
      logger.warning(
          F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
          + F'distributed training: {bool(training_args.local_rank != -1							)}, 16-bits training: {training_args.fpaa}'							)
      logger.info(F'Training/evaluation parameters {training_args}'							)

      # Detecting last checkpoint.
      lowerCamelCase__           =		None
      if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
            lowerCamelCase__           =		get_last_checkpoint(training_args.output_dir							)
            if last_checkpoint is None and len(os.listdir(training_args.output_dir							)							) > 0:
                  raise ValueError(
                      F'Output directory ({training_args.output_dir}) already exists and is not empty. '
                      'Use --overwrite_output_dir to overcome.'							)
            elif last_checkpoint is not None:
                  logger.info(
                      F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                      'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'							)

    # Set seed before initializing model.
      set_seed(training_args.seed							)

      # In distributed training, the load_dataset function guarantees that only one local process can concurrently
      # download the dataset.
      # Downloading and loading xnli dataset from the hub.
      if training_args.do_train:
            if model_args.train_language is None:
                  lowerCamelCase__           =		load_dataset(
                      'xnli'		,   model_args.language		,   split='train'		,   cache_dir=model_args.cache_dir		,   use_auth_token=True if model_args.use_auth_token else None		,   )
            else:
                  lowerCamelCase__           =		load_dataset(
                      'xnli'		,   model_args.train_language		,   split='train'		,   cache_dir=model_args.cache_dir		,   use_auth_token=True if model_args.use_auth_token else None		,   )
            lowerCamelCase__           =		train_dataset.features['label'].names

      if training_args.do_eval:
            lowerCamelCase__           =		load_dataset(
                'xnli'		,   model_args.language		,   split='validation'		,   cache_dir=model_args.cache_dir		,   use_auth_token=True if model_args.use_auth_token else None		,   )
            lowerCamelCase__           =		eval_dataset.features['label'].names

      if training_args.do_predict:
            lowerCamelCase__           =		load_dataset(
                'xnli'		,   model_args.language		,   split='test'		,   cache_dir=model_args.cache_dir		,   use_auth_token=True if model_args.use_auth_token else None		,   )
            lowerCamelCase__           =		predict_dataset.features['label'].names

      # Labels
      lowerCamelCase__           =		len(_a							)

      # Load pretrained model and tokenizer
      # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      lowerCamelCase__           =		AutoConfig.from_pretrained(
          model_args.config_name if model_args.config_name else model_args.model_name_or_path		,   num_labels=_a		,   idalabel={str(_a							): label for i, label in enumerate(_a							)}		,   labelaid={label: i for i, label in enumerate(_a							)}		,   finetuning_task='xnli'		,   cache_dir=model_args.cache_dir		,   revision=model_args.model_revision		,   use_auth_token=True if model_args.use_auth_token else None		,   )
      lowerCamelCase__           =		AutoTokenizer.from_pretrained(
          model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path		,   do_lower_case=model_args.do_lower_case		,   cache_dir=model_args.cache_dir		,   use_fast=model_args.use_fast_tokenizer		,   revision=model_args.model_revision		,   use_auth_token=True if model_args.use_auth_token else None		,   )
      lowerCamelCase__           =		AutoModelForSequenceClassification.from_pretrained(
          model_args.model_name_or_path		,   from_tf=bool('.ckpt' in model_args.model_name_or_path							)		,   config=_a		,   cache_dir=model_args.cache_dir		,   revision=model_args.model_revision		,   use_auth_token=True if model_args.use_auth_token else None		,   ignore_mismatched_sizes=model_args.ignore_mismatched_sizes		,   )

      # Preprocessing the datasets
      # Padding strategy
      if data_args.pad_to_max_length:
            lowerCamelCase__           =		'max_length'
      else:
            # We will pad later, dynamically at batch creation, to the max sequence length in each batch
            lowerCamelCase__           =		False

      def preprocess_function(_a:     List[str]							):
            # Tokenize the texts
            return tokenizer(
                examples['premise']		,   examples['hypothesis']		,   padding=_a		,   max_length=data_args.max_seq_length		,   truncation=_a		,   )

      if training_args.do_train:
            if data_args.max_train_samples is not None:
                  lowerCamelCase__           =		min(len(_a							)		,   data_args.max_train_samples							)
                  lowerCamelCase__           =		train_dataset.select(range(_a							)							)
            with training_args.main_process_first(desc='train dataset map pre-processing'							):
                  lowerCamelCase__           =		train_dataset.map(
                      _a		,   batched=_a		,   load_from_cache_file=not data_args.overwrite_cache		,   desc='Running tokenizer on train dataset'		,   )
            # Log a few random samples from the training set:
            for index in random.sample(range(len(_a							)							)		,   3							):
                  logger.info(F'Sample {index} of the training set: {train_dataset[index]}.'							)

      if training_args.do_eval:
            if data_args.max_eval_samples is not None:
                  lowerCamelCase__           =		min(len(_a							)		,   data_args.max_eval_samples							)
                  lowerCamelCase__           =		eval_dataset.select(range(_a							)							)
            with training_args.main_process_first(desc='validation dataset map pre-processing'							):
                  lowerCamelCase__           =		eval_dataset.map(
                      _a		,   batched=_a		,   load_from_cache_file=not data_args.overwrite_cache		,   desc='Running tokenizer on validation dataset'		,   )

      if training_args.do_predict:
            if data_args.max_predict_samples is not None:
                  lowerCamelCase__           =		min(len(_a							)		,   data_args.max_predict_samples							)
                  lowerCamelCase__           =		predict_dataset.select(range(_a							)							)
            with training_args.main_process_first(desc='prediction dataset map pre-processing'							):
                  lowerCamelCase__           =		predict_dataset.map(
                      _a		,   batched=_a		,   load_from_cache_file=not data_args.overwrite_cache		,   desc='Running tokenizer on prediction dataset'		,   )

    # Get the metric function
      lowerCamelCase__           =		evaluate.load('xnli'							)

      # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      def compute_metrics(_a:     EvalPrediction							):
            lowerCamelCase__           =		p.predictions[0] if isinstance(p.predictions		,   _a							) else p.predictions
            lowerCamelCase__           =		np.argmax(_a		,   axis=1							)
            return metric.compute(predictions=_a		,   references=p.label_ids							)

      # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
      if data_args.pad_to_max_length:
            lowerCamelCase__           =		default_data_collator
      elif training_args.fpaa:
            lowerCamelCase__           =		DataCollatorWithPadding(_a		,   pad_to_multiple_of=8							)
      else:
            lowerCamelCase__           =		None

      # Initialize our Trainer
      lowerCamelCase__           =		Trainer(
          model=_a		,   args=_a		,   train_dataset=train_dataset if training_args.do_train else None		,   eval_dataset=eval_dataset if training_args.do_eval else None		,   compute_metrics=_a		,   tokenizer=_a		,   data_collator=_a		,   )

      # Training
      if training_args.do_train:
            lowerCamelCase__           =		None
            if training_args.resume_from_checkpoint is not None:
                  lowerCamelCase__           =		training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  lowerCamelCase__           =		last_checkpoint
            lowerCamelCase__           =		trainer.train(resume_from_checkpoint=_a							)
            lowerCamelCase__           =		train_result.metrics
            lowerCamelCase__           =		(
                data_args.max_train_samples if data_args.max_train_samples is not None else len(_a							)
            )
            lowerCamelCase__           =		min(_a		,   len(_a							)							)

            trainer.save_model()  # Saves the tokenizer too for easy upload

            trainer.log_metrics('train'		,   _a							)
            trainer.save_metrics('train'		,   _a							)
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            logger.info('*** Evaluate ***'							)
            lowerCamelCase__           =		trainer.evaluate(eval_dataset=_a							)

            lowerCamelCase__           =		data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_a							)
            lowerCamelCase__           =		min(_a		,   len(_a							)							)

            trainer.log_metrics('eval'		,   _a							)
            trainer.save_metrics('eval'		,   _a							)

      # Prediction
      if training_args.do_predict:
            logger.info('*** Predict ***'							)
            lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__           =		trainer.predict(_a		,   metric_key_prefix='predict'							)

            lowerCamelCase__           =		(
                data_args.max_predict_samples if data_args.max_predict_samples is not None else len(_a							)
            )
            lowerCamelCase__           =		min(_a		,   len(_a							)							)

            trainer.log_metrics('predict'		,   _a							)
            trainer.save_metrics('predict'		,   _a							)

            lowerCamelCase__           =		np.argmax(_a		,   axis=1							)
            lowerCamelCase__           =		os.path.join(training_args.output_dir		,   'predictions.txt'							)
            if trainer.is_world_process_zero():
                  with open(_a		,   'w'							) as writer:
                        writer.write('index\tprediction\n'							)
                        for index, item in enumerate(_a							):
                              lowerCamelCase__           =		label_list[item]
                              writer.write(F'{index}\t{item}\n'							)


if __name__ == "__main__":
   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          =							WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])



def   snake_case						(				_a:     Any							)->		Optional[Any]:
      '''simple docstring'''


      lowerCamelCase__           =		test_results.split(' '							)

      lowerCamelCase__           =		0
      lowerCamelCase__           =		0

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

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

      return failed, success, time_spent



def   snake_case						(				_a:     Optional[int]							)->		Optional[int]:
      '''simple docstring'''


      lowerCamelCase__           =		{}
      lowerCamelCase__           =		None
      lowerCamelCase__           =		False
      for line in failures_short_lines.split('\n'							):
            if re.search(R'_ \[doctest\]'		,   _a							):
                  lowerCamelCase__           =		True
                  lowerCamelCase__           =		line.split(' '							)[2]
            elif in_error and not line.split(' '							)[0].isdigit():
                  lowerCamelCase__           =		line
                  lowerCamelCase__           =		False

      return failures



class   _a      :
    def __init__( self							:					Optional[Any]							,					SCREAMING_SNAKE_CASE__							:					str							,					SCREAMING_SNAKE_CASE__							:					Dict				):
          lowerCamelCase__           =		title

          lowerCamelCase__           =		doc_test_results['time_spent'].split(','				)[0]
          lowerCamelCase__           =		doc_test_results['success']
          lowerCamelCase__           =		doc_test_results['failures']
          lowerCamelCase__           =		self.n_success + self.n_failures

          # Failures and success of the modeling tests
          lowerCamelCase__           =		doc_test_results
    @property
    def      _UpperCamelCase       ( self							:					List[str]				):
          lowerCamelCase__           =		[self._time_spent]
          lowerCamelCase__           =		0

          for time in time_spent:
                lowerCamelCase__           =		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(SCREAMING_SNAKE_CASE__				) == 1:
                      lowerCamelCase__           =		[0, 0, time_parts[0]]

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

          lowerCamelCase__    ,  lowerCamelCase__    ,  lowerCamelCase__           =		total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60
          return F'{int(SCREAMING_SNAKE_CASE__				)}h{int(SCREAMING_SNAKE_CASE__				)}m{int(SCREAMING_SNAKE_CASE__				)}s'
    @property
    def      _UpperCamelCase       ( self							:					Dict				):
          return {"type": "header", "text": {"type": "plain_text", "text": self.title}}
    @property
    def      _UpperCamelCase       ( self							:					Dict				):
          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      _UpperCamelCase       ( self							:					Any				):
          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      _UpperCamelCase       ( self							:					Union[str, Any]				):
          lowerCamelCase__           =		40
          lowerCamelCase__           =		{k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__				)}

          lowerCamelCase__           =		''
          for category, failures in category_failures.items():
                if len(SCREAMING_SNAKE_CASE__				) == 0:
                      continue

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

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

          return {
              "type": "section",
              "text": {
                  "type": "mrkdwn",
                  "text": F'The following examples had failures:\n\n\n{report}\n',
              },
          }
    @property
    def      _UpperCamelCase       ( self							:					str				):
          lowerCamelCase__           =		[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(SCREAMING_SNAKE_CASE__				)
    @staticmethod
    def      _UpperCamelCase       ( ):
          lowerCamelCase__           =		[
              {
                  '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(SCREAMING_SNAKE_CASE__				)}				)				)

          client.chat_postMessage(
              channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']							,					text='There was an issue running the tests.'							,					blocks=SCREAMING_SNAKE_CASE__							,					)
    def      _UpperCamelCase       ( self							:					Optional[int]				):
          print('Sending the following payload'				)
          print(json.dumps({'blocks': json.loads(self.payload				)}				)				)

          lowerCamelCase__           =		F'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.'

          lowerCamelCase__           =		client.chat_postMessage(
              channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']							,					blocks=self.payload							,					text=SCREAMING_SNAKE_CASE__							,					)
    def      _UpperCamelCase       ( self							:					Optional[Any]							,					SCREAMING_SNAKE_CASE__							:					Dict							,					SCREAMING_SNAKE_CASE__							:					List[Any]							,					SCREAMING_SNAKE_CASE__							:					Tuple							,					SCREAMING_SNAKE_CASE__							:					Tuple				):
          lowerCamelCase__           =		''
          for key, value in failures.items():
                lowerCamelCase__           =		value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__				) > 2_50 else value
                failures_text += F'*{key}*\n_{value}_\n\n'

          lowerCamelCase__           =		job_name
          lowerCamelCase__           =		{'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}}

          if job_link is not None:
                lowerCamelCase__           =		{
                    '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      _UpperCamelCase       ( self							:					Optional[int]				):
          if self.thread_ts is None:
                raise ValueError('Can only post reply if a post has been made.'				)

          lowerCamelCase__           =		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'				)

          lowerCamelCase__           =		sorted(self.doc_test_results.items()							,					key=lambda SCREAMING_SNAKE_CASE__				: t[0]				)
          for job, job_result in sorted_dict:
                if len(job_result['failures']				):
                      lowerCamelCase__           =		F'*Num failures* :{len(job_result["failed"]				)} \n'
                      lowerCamelCase__           =		job_result['failures']
                      lowerCamelCase__           =		self.get_reply_blocks(SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					text=SCREAMING_SNAKE_CASE__				)

                      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=SCREAMING_SNAKE_CASE__							,					thread_ts=self.thread_ts['ts']							,					)

                      time.sleep(1				)





def   snake_case						(				)->		Optional[Any]:
      '''simple docstring'''


      lowerCamelCase__           =		os.environ['GITHUB_RUN_ID']
      lowerCamelCase__           =		F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100'
      lowerCamelCase__           =		requests.get(_a							).json()
      lowerCamelCase__           =		{}

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

            for i in range(_a							):
                  lowerCamelCase__           =		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.'		,   _a							)

      return {}



def   snake_case						(				_a:     str							)->		Dict:
      '''simple docstring'''


      lowerCamelCase__           =		{}

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

      return _artifact



def   snake_case						(				)->		Optional[int]:
      '''simple docstring'''


      class   _a      :
          def __init__( self							:					Tuple							,					SCREAMING_SNAKE_CASE__							:					str				):
                lowerCamelCase__           =		name
                lowerCamelCase__           =		[]
          def __str__( self							:					Dict				):
                return self.name


          def      _UpperCamelCase       ( self							:					Union[str, Any]							,					SCREAMING_SNAKE_CASE__							:					str				):
                self.paths.append({'name': self.name, 'path': path}				)





      lowerCamelCase__           =		{}

      lowerCamelCase__           =		filter(os.path.isdir		,   os.listdir()							)
      for directory in directories:
            lowerCamelCase__           =		directory
            if artifact_name not in _available_artifacts:
                  lowerCamelCase__           =		Artifact(_a							)

                  _available_artifacts[artifact_name].add_path(_a							)

      return _available_artifacts


if __name__ == "__main__":
   _snake_case          =							get_job_links()
   _snake_case          =							retrieve_available_artifacts()

   _snake_case          =							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          =							{
       v: {
           "failed": [],
           "failures": {},
       }
       for v in docs.values()
   }

   # Link to the GitHub Action job
   _snake_case          =							github_actions_job_links.get("run_doctests")

   _snake_case          =							available_artifacts["doc_tests_gpu_test_reports"].paths[0]
   _snake_case          =							retrieve_artifact(artifact_path["name"])
   if "stats" in artifact:
      _snake_case      ,					_snake_case      ,					_snake_case          =							handle_test_results(artifact["stats"])
      _snake_case          =							failed
      _snake_case          =							success
      _snake_case          =							time_spent[1:-1] + ", "

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

            if "::" in line:
               _snake_case      ,					_snake_case          =							line.split("::")
            else:
               _snake_case      ,					_snake_case          =							line, line

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

                  _snake_case          =							all_failures[test] if test in all_failures else "N/A"
                  _snake_case          =							failure
                  break

   _snake_case          =							Message("🤗 Results of the doc tests.", doc_test_results)
   message.post()
   message.post_reply()



