




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


__a          =			WebClient(token=os.environ['CI_SLACK_BOT_TOKEN'])







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      test_results.split(''' '''				)

     UpperCAmelCase_      :							Any       =      0
     UpperCAmelCase_      :							Any       =      0

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

     for i, expression in enumerate(_lowercase				):
          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__       (      _lowercase				):

     '''simple docstring'''


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

     return failures

class   __a:






    """simple docstring"""





    def __init__(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Tuple:
         UpperCAmelCase_      :							Optional[Any]       =      title

         UpperCAmelCase_      :							Optional[int]       =      doc_test_results['''time_spent'''].split(''','''  )[0]
         UpperCAmelCase_      :							Dict       =      doc_test_results['''success''']
         UpperCAmelCase_      :							Optional[int]       =      doc_test_results['''failures''']
         UpperCAmelCase_      :							Optional[Any]       =      self.n_success + self.n_failures

         # Failures and success of the modeling tests
         UpperCAmelCase_      :							List[str]       =      doc_test_results





    @property
    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Optional[int]       =      [self._time_spent]
         UpperCAmelCase_      :							Optional[Any]       =      0

         for time in time_spent:
              UpperCAmelCase_      :							Optional[int]       =      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:
                   UpperCAmelCase_      :							str       =      [0, 0, time_parts[0]]

              UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							List[str]       =      int(time_parts[0]  ), int(time_parts[1]  ), float(time_parts[2]  )
              total_secs += hours * 3_600 + minutes * 60 + seconds

         UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							List[Any]       =      total_secs // 3_600, (total_secs % 3_600) // 60, total_secs % 60
         return f'''{int(_SCREAMING_SNAKE_CASE  )}h{int(_SCREAMING_SNAKE_CASE  )}m{int(_SCREAMING_SNAKE_CASE  )}s'''





    @property
    def 							a__				(				self  )			->		Dict:
         return {"type": "header", "text": {"type": "plain_text", "text": self.title}}





    @property
    def 							a__				(				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 							a__				(				self  )			->		Dict:
         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 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							List[str]       =      40
         UpperCAmelCase_      :							Dict       =      {k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )}

         UpperCAmelCase_      :							List[str]       =      ''''''
         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 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Union[str, Any]       =      [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 							a__				(				)			->		Any:
         UpperCAmelCase_      :							int       =      [
             {
                 '''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 							a__				(				self  )			->		Union[str, Any]:
         print('''Sending the following payload'''  )
         print(json.dumps({'''blocks''': json.loads(self.payload  )}  )  )

         UpperCAmelCase_      :							Dict       =      f'''{self.n_failures} failures out of {self.n_tests} tests,''' if self.n_failures else '''All tests passed.'''

         UpperCAmelCase_      :							List[str]       =      client.chat_postMessage(
             channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY''']       ,blocks=self.payload       ,text=_SCREAMING_SNAKE_CASE       ,)





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		int:
         UpperCAmelCase_      :							List[str]       =      ''''''
         for key, value in failures.items():
              UpperCAmelCase_      :							Any       =      value[:200] + ''' [Truncated]''' if len(_SCREAMING_SNAKE_CASE  ) > 250 else value
              failures_text += f'''*{key}*\n_{value}_\n\n'''

         UpperCAmelCase_      :							int       =      job_name
         UpperCAmelCase_      :							int       =      {'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}}

         if job_link is not None:
              UpperCAmelCase_      :							Tuple       =      {
                  '''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 							a__				(				self  )			->		List[Any]:
         if self.thread_ts is None:
              raise ValueError('''Can only post reply if a post has been made.'''  )

         UpperCAmelCase_      :							Dict       =      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'''  )

         UpperCAmelCase_      :							Any       =      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''']  ):
                   UpperCAmelCase_      :							Union[str, Any]       =      f'''*Num failures* :{len(job_result["failed"]  )} \n'''
                   UpperCAmelCase_      :							Union[str, Any]       =      job_result['''failures''']
                   UpperCAmelCase_      :							Tuple       =      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 lowerCamelCase__       (      ):

     '''simple docstring'''


     UpperCAmelCase_      :							Optional[Any]       =      os.environ['''GITHUB_RUN_ID''']
     UpperCAmelCase_      :							str       =      f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100'''
     UpperCAmelCase_      :							Dict       =      requests.get(_lowercase				).json()
     UpperCAmelCase_      :							Union[str, Any]       =      {}

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

          for i in range(_lowercase				):
               UpperCAmelCase_      :							Optional[int]       =      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.'''			,						_lowercase				)

     return {}







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							str       =      {}

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

     return _artifact







def lowerCamelCase__       (      ):

     '''simple docstring'''


     class   __a:






         """simple docstring"""





         def __init__(				self       ,_SCREAMING_SNAKE_CASE  )			->		List[str]:
              UpperCAmelCase_      :							Dict       =      name
              UpperCAmelCase_      :							Optional[int]       =      []





         def __str__(				self  )			->		Dict:
              return self.name





         def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		str:
              self.paths.append({'''name''': self.name, '''path''': path}  )


     UpperCAmelCase_      :							Dict[str, Artifact]       =      {}

     UpperCAmelCase_      :							Union[str, Any]       =      filter(os.path.isdir			,						os.listdir()				)
     for directory in directories:
          UpperCAmelCase_      :							Union[str, Any]       =      directory
          if artifact_name not in _available_artifacts:
               UpperCAmelCase_      :							Dict       =      Artifact(_lowercase				)

               _available_artifacts[artifact_name].add_path(_lowercase				)

     return _available_artifacts


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

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

     # Link to the GitHub Action job
     __a          =			github_actions_job_links.get('run_doctests')

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

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

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

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

                              __a          =			all_failures[test] if test in all_failures else 'N/A'
                              __a          =			failure
                              break

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





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__a          =			{
    'configuration_bloom': ['BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BloomConfig', 'BloomOnnxConfig'],
}
try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     __a          =			['BloomTokenizerFast']

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     __a          =			[
         'BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST',
         'BloomForCausalLM',
         'BloomModel',
         'BloomPreTrainedModel',
         'BloomForSequenceClassification',
         'BloomForTokenClassification',
         'BloomForQuestionAnswering',
     ]

if TYPE_CHECKING:
     from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_bloom_fast import BloomTokenizerFast

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_bloom import (
              BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST,
              BloomForCausalLM,
              BloomForQuestionAnswering,
              BloomForSequenceClassification,
              BloomForTokenClassification,
              BloomModel,
              BloomPreTrainedModel,
          )

else:
     import sys

     __a          =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)