


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


__A :  List[str]    							=				WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"])







def     UpperCamelCase_      (   A__ :       Dict ):
  '''simple docstring'''





  lowerCAmelCase_      :				Union[str, Any]      =       test_results.split(""" """ )

  lowerCAmelCase_      :				Union[str, Any]      =       0
  lowerCAmelCase_      :				List[str]      =       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_      :				str      =       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     UpperCamelCase_      (   A__ :       Optional[Any] ):
  '''simple docstring'''





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

  return failures






class        __snake_case	:







    """simple docstring"""



    def __init__(       self   :  Union[str, Any]   ,						lowerCamelCase   :  str   ,						lowerCamelCase   :  Dict		)       ->  Union[str, Any]:
      lowerCAmelCase_      :				Tuple      =       title

      lowerCAmelCase_      :				str      =       doc_test_results["""time_spent"""].split(""","""		)[0]
      lowerCAmelCase_      :				Dict      =       doc_test_results["""success"""]
      lowerCAmelCase_      :				str      =       doc_test_results["""failures"""]
      lowerCAmelCase_      :				Tuple      =       self.n_success + self.n_failures

      # Failures and success of the modeling tests
      lowerCAmelCase_      :				Tuple      =       doc_test_results

    @property
    def __lowercase       (       self   :  int		)       ->  str:
      lowerCAmelCase_      :				Union[str, Any]      =       [self._time_spent]
      lowerCAmelCase_      :				Tuple      =       0

      for time in time_spent:
        lowerCAmelCase_      :				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(lowerCamelCase		) == 1:
          lowerCAmelCase_      :				Optional[Any]      =       [0, 0, time_parts[0]]

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

      lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_      :				Optional[Any]      =       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   :  Tuple		)       ->  Dict:
      return {"type": "header", "text": {"type": "plain_text", "text": self.title}}

    @property
    def __lowercase       (       self   :  Optional[int]		)       ->  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 __lowercase       (       self   :  List[Any]		)       ->  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 __lowercase       (       self   :  List[str]		)       ->  Dict:
      lowerCAmelCase_      :				Union[str, Any]      =       40
      lowerCAmelCase_      :				int      =       {k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(lowerCamelCase   ,						lowerCamelCase		)}

      lowerCAmelCase_      :				Optional[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   :  Tuple		)       ->  str:
      lowerCAmelCase_      :				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(lowerCamelCase		)

    @staticmethod
    def __lowercase       (       )       ->  Any:
      lowerCAmelCase_      :				Any      =       [
          {
              """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[Any]		)       ->  str:
      print("""Sending the following payload"""		)
      print(json.dumps({"""blocks""": json.loads(self.payload		)}		)		)

      lowerCAmelCase_      :				Any      =       F'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else """All tests passed."""

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

    def __lowercase       (       self   :  List[str]   ,						lowerCamelCase   :  List[str]   ,						lowerCamelCase   :  int   ,						lowerCamelCase   :  Tuple   ,						lowerCamelCase   :  Union[str, Any]		)       ->  Optional[int]:
      lowerCAmelCase_      :				str      =       """"""
      for key, value in failures.items():
        lowerCAmelCase_      :				Tuple      =       value[:2_00] + """ [Truncated]""" if len(lowerCamelCase		) > 2_50 else value
        failures_text += F'*{key}*\n_{value}_\n\n'

      lowerCAmelCase_      :				str      =       job_name
      lowerCAmelCase_      :				Optional[int]      =       {"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}}

      if job_link is not None:
        lowerCAmelCase_      :				Any      =       {
            """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   :  Optional[Any]		)       ->  Union[str, Any]:
      if self.thread_ts is None:
        raise ValueError("""Can only post reply if a post has been made."""		)

      lowerCAmelCase_      :				List[str]      =       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_      :				int      =       sorted(self.doc_test_results.items()   ,						key=lambda lowerCamelCase		: t[0]		)
      for job, job_result in sorted_dict:
        if len(job_result["""failures"""]		):
          lowerCAmelCase_      :				Optional[int]      =       F'*Num failures* :{len(job_result["failed"]		)} \n'
          lowerCAmelCase_      :				Union[str, Any]      =       job_result["""failures"""]
          lowerCAmelCase_      :				Dict      =       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     UpperCamelCase_      (   ):
  '''simple docstring'''





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

  try:
    jobs.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} )
    lowerCAmelCase_      :				Any      =       math.ceil((result["""total_count"""] - 1_00) / 1_00 )

    for i in range(A__ ):
      lowerCAmelCase_      :				Dict      =       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     UpperCamelCase_      (   A__ :       str ):
  '''simple docstring'''





  lowerCAmelCase_      :				int      =       {}

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

  return _artifact







def     UpperCamelCase_      (   ):
  '''simple docstring'''





  class        __snake_case	:







      """simple docstring"""



      def __init__(       self   :  List[Any]   ,						lowerCamelCase   :  str		)       ->  str:
        lowerCAmelCase_      :				Dict      =       name
        lowerCAmelCase_      :				Dict      =       []

      def __str__(       self   :  Optional[Any]		)       ->  Any:
        return self.name





      def __lowercase       (       self   :  Optional[int]   ,						lowerCamelCase   :  str		)       ->  Optional[Any]:
        self.paths.append({"""name""": self.name, """path""": path}		)







  lowerCAmelCase_      :				Dict[str, Artifact]      =       {}

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

      _available_artifacts[artifact_name].add_path(A__ )

  return _available_artifacts


if __name__ == "__main__":
  __A :  str    							=				get_job_links()
  __A :  Tuple    							=				retrieve_available_artifacts()

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

  # Link to the GitHub Action job
  __A :  str    							=				github_actions_job_links.get("run_doctests")

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

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

        if "::" in line:
          __A							,			__A :  Dict    							=				line.split("::")
        else:
          __A							,			__A :  List[str]    							=				line, line

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

            __A :  Dict    							=				all_failures[test] if test in all_failures else "N/A"
            __A :  Optional[int]    							=				failure
            break

  __A :  Optional[int]    							=				Message("🤗 Results of the doc tests.", doc_test_results)
  message.post()
  message.post_reply()







'''simple docstring'''






from typing import List

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


__A :  Dict    							=				logging.get_logger(__name__)

__A :  int    							=				{
    "snap-research/efficientformer-l1-300": (
        "https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
    ),
}






class        __snake_case	(       _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase       			= 'efficientformer'

    def __init__(       self   :  Any   ,						lowerCamelCase   :  List[int] = [3, 2, 6, 4]   ,						lowerCamelCase   :  List[int] = [48, 96, 2_24, 4_48]   ,						lowerCamelCase   :  List[bool] = [True, True, True, True]   ,						lowerCamelCase   :  int = 4_48   ,						lowerCamelCase   :  int = 32   ,						lowerCamelCase   :  int = 4   ,						lowerCamelCase   :  int = 7   ,						lowerCamelCase   :  int = 5   ,						lowerCamelCase   :  int = 8   ,						lowerCamelCase   :  int = 4   ,						lowerCamelCase   :  float = 0.0   ,						lowerCamelCase   :  int = 16   ,						lowerCamelCase   :  int = 3   ,						lowerCamelCase   :  int = 3   ,						lowerCamelCase   :  int = 3   ,						lowerCamelCase   :  int = 2   ,						lowerCamelCase   :  int = 1   ,						lowerCamelCase   :  float = 0.0   ,						lowerCamelCase   :  int = 1   ,						lowerCamelCase   :  bool = True   ,						lowerCamelCase   :  bool = True   ,						lowerCamelCase   :  float = 1E-5   ,						lowerCamelCase   :  str = "gelu"   ,						lowerCamelCase   :  float = 0.02   ,						lowerCamelCase   :  float = 1E-12   ,						lowerCamelCase   :  int = 2_24   ,						lowerCamelCase   :  float = 1E-05   ,						**lowerCamelCase   :  int   ,						)       ->  None:
      super().__init__(**lowerCamelCase		)

      lowerCAmelCase_      :				List[str]      =       hidden_act
      lowerCAmelCase_      :				List[Any]      =       hidden_dropout_prob
      lowerCAmelCase_      :				Any      =       hidden_sizes
      lowerCAmelCase_      :				List[Any]      =       num_hidden_layers
      lowerCAmelCase_      :				Union[str, Any]      =       num_attention_heads
      lowerCAmelCase_      :				Tuple      =       initializer_range
      lowerCAmelCase_      :				Union[str, Any]      =       layer_norm_eps
      lowerCAmelCase_      :				int      =       patch_size
      lowerCAmelCase_      :				List[str]      =       num_channels
      lowerCAmelCase_      :				Dict      =       depths
      lowerCAmelCase_      :				int      =       mlp_expansion_ratio
      lowerCAmelCase_      :				Optional[Any]      =       downsamples
      lowerCAmelCase_      :				Union[str, Any]      =       dim
      lowerCAmelCase_      :				Union[str, Any]      =       key_dim
      lowerCAmelCase_      :				str      =       attention_ratio
      lowerCAmelCase_      :				Tuple      =       resolution
      lowerCAmelCase_      :				Optional[Any]      =       pool_size
      lowerCAmelCase_      :				str      =       downsample_patch_size
      lowerCAmelCase_      :				Dict      =       downsample_stride
      lowerCAmelCase_      :				str      =       downsample_pad
      lowerCAmelCase_      :				str      =       drop_path_rate
      lowerCAmelCase_      :				List[Any]      =       num_metaad_blocks
      lowerCAmelCase_      :				Tuple      =       distillation
      lowerCAmelCase_      :				Optional[Any]      =       use_layer_scale
      lowerCAmelCase_      :				Dict      =       layer_scale_init_value
      lowerCAmelCase_      :				Optional[Any]      =       image_size
      lowerCAmelCase_      :				Optional[Any]      =       batch_norm_eps



