

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


_UpperCamelCase		     =    WebClient(token=os.environ["""CI_SLACK_BOT_TOKEN"""])



def       SCREAMING_SNAKE_CASE							( lowercase__   )			->						List[Any]:
 lowerCAmelCase__   :				Any 			=				test_results.split(" "   )

 lowerCAmelCase__   :				Dict 			=				0
 lowerCAmelCase__   :				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.
 lowerCAmelCase__   :				int 			=				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       SCREAMING_SNAKE_CASE							( lowercase__   )			->						List[Any]:
 lowerCAmelCase__   :				Union[str, Any] 			=				{}
 lowerCAmelCase__   :				List[Any] 			=				None
 lowerCAmelCase__   :				int 			=				False
 for line in failures_short_lines.split("\n"   ):
  if re.search(r"_ \[doctest\]"					,					lowercase__   ):
   lowerCAmelCase__   :				List[Any] 			=				True
   lowerCAmelCase__   :				int 			=				line.split(" "   )[2]
  elif in_error and not line.split(" "   )[0].isdigit():
   lowerCAmelCase__   :				Any 			=				line
   lowerCAmelCase__   :				int 			=				False

 return failures






class 			__a					:





       """simple docstring"""


       def __init__(   self			,					snake_case			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				title

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

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






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				[self._time_spent]
        lowerCAmelCase__   :				Union[str, Any] 			=				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(snake_case   ) == 1:
          lowerCAmelCase__   :				str 			=				[0, 0, time_parts[0]]

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

        lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__   :				Tuple 			=				total_secs // 3_600, (total_secs % 3_600) // 60, total_secs % 60
        return F"""{int(snake_case   )}h{int(snake_case   )}m{int(snake_case   )}s"""






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

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






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """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 			SCREAMING_SNAKE_CASE_	(   self   ):





        """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 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				40
        lowerCAmelCase__   :				List[str] 			=				{k: v["failed"] for k, v in doc_test_results.items() if isinstance(snake_case			,					snake_case   )}

        lowerCAmelCase__   :				Union[str, Any] 			=				""
        for category, failures in category_failures.items():
         if len(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(snake_case   )
         report += "`"

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






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[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(snake_case   )






       @staticmethod
       def 			SCREAMING_SNAKE_CASE_	(   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[str] 			=				[
            {
                "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(snake_case   )}   )   )

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






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

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

        lowerCAmelCase__   :				Optional[Any] 			=				F"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else "All tests passed."

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






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Optional[int] 			=				""
        for key, value in failures.items():
         lowerCAmelCase__   :				Union[str, Any] 			=				value[:200] + " [Truncated]" if len(snake_case   ) > 250 else value
         failures_text += F"""*{key}*\n_{value}_\n\n"""

        lowerCAmelCase__   :				str 			=				job_name
        lowerCAmelCase__   :				Tuple 			=				{"type": "section", "text": {"type": "mrkdwn", "text": text}}

        if job_link is not None:
         lowerCAmelCase__   :				int 			=				{
             "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 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

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

        lowerCAmelCase__   :				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"   )

        lowerCAmelCase__   :				Optional[int] 			=				sorted(self.doc_test_results.items()			,					key=lambda snake_case   : t[0]   )
        for job, job_result in sorted_dict:
         if len(job_result["failures"]   ):
          lowerCAmelCase__   :				List[str] 			=				F"""*Num failures* :{len(job_result["failed"]   )} \n"""
          lowerCAmelCase__   :				Any 			=				job_result["failures"]
          lowerCAmelCase__   :				int 			=				self.get_reply_blocks(snake_case			,					snake_case			,					snake_case			,					text=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=snake_case			,					thread_ts=self.thread_ts["ts"]			,					)

          time.sleep(1   )




def       SCREAMING_SNAKE_CASE							( )			->						Tuple:
 lowerCAmelCase__   :				Union[str, Any] 			=				os.environ["GITHUB_RUN_ID"]
 lowerCAmelCase__   :				Optional[int] 			=				F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100"""
 lowerCAmelCase__   :				Union[str, Any] 			=				requests.get(lowercase__   ).json()
 lowerCAmelCase__   :				Any 			=				{}

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

  for i in range(lowercase__   ):
   lowerCAmelCase__   :				List[str] 			=				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       SCREAMING_SNAKE_CASE							( lowercase__   )			->						List[Any]:
 lowerCAmelCase__   :				Union[str, Any] 			=				{}

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

 return _artifact



def       SCREAMING_SNAKE_CASE							( )			->						List[str]:






 class 			__a					:





        """simple docstring"""


        def __init__(   self			,					snake_case   ):





         """simple docstring"""

         lowerCAmelCase__   :				List[Any] 			=				name
         lowerCAmelCase__   :				str 			=				[]






        def __str__(   self   ):





         """simple docstring"""

         return self.name






        def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





         """simple docstring"""

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




 lowerCAmelCase__   :				Dict[str, Artifact] 			=				{}

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

   _available_artifacts[artifact_name].add_path(lowercase__   )

 return _available_artifacts


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

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

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

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

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

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

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

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

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









"""simple docstring"""

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_UpperCamelCase		     =    logging.get_logger(__name__)

_UpperCamelCase		     =    {
    """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""",
}






class 			__a					(						__magic_name__       ,	__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      Optional[Any]    =						'focalnet'






       def __init__(   self			,					snake_case=224			,					snake_case=4			,					snake_case=3			,					snake_case=96			,					snake_case=False			,					snake_case=[192, 384, 768, 768]			,					snake_case=[2, 2, 6, 2]			,					snake_case=[2, 2, 2, 2]			,					snake_case=[3, 3, 3, 3]			,					snake_case="gelu"			,					snake_case=4.0			,					snake_case=0.0			,					snake_case=0.1			,					snake_case=False			,					snake_case=1e-4			,					snake_case=False			,					snake_case=False			,					snake_case=False			,					snake_case=0.02			,					snake_case=1e-5			,					snake_case=32			,					snake_case=None			,					snake_case=None			,					**snake_case			,					):





        """simple docstring"""

        super().__init__(**snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				image_size
        lowerCAmelCase__   :				Union[str, Any] 			=				patch_size
        lowerCAmelCase__   :				List[str] 			=				num_channels
        lowerCAmelCase__   :				List[str] 			=				embed_dim
        lowerCAmelCase__   :				List[Any] 			=				use_conv_embed
        lowerCAmelCase__   :				List[str] 			=				hidden_sizes
        lowerCAmelCase__   :				List[Any] 			=				depths
        lowerCAmelCase__   :				Union[str, Any] 			=				focal_levels
        lowerCAmelCase__   :				Union[str, Any] 			=				focal_windows
        lowerCAmelCase__   :				int 			=				hidden_act
        lowerCAmelCase__   :				List[Any] 			=				mlp_ratio
        lowerCAmelCase__   :				str 			=				hidden_dropout_prob
        lowerCAmelCase__   :				Union[str, Any] 			=				drop_path_rate
        lowerCAmelCase__   :				Tuple 			=				use_layerscale
        lowerCAmelCase__   :				Tuple 			=				layerscale_value
        lowerCAmelCase__   :				str 			=				use_post_layernorm
        lowerCAmelCase__   :				str 			=				use_post_layernorm_in_modulation
        lowerCAmelCase__   :				Union[str, Any] 			=				normalize_modulator
        lowerCAmelCase__   :				Optional[int] 			=				initializer_range
        lowerCAmelCase__   :				List[Any] 			=				layer_norm_eps
        lowerCAmelCase__   :				str 			=				encoder_stride
        lowerCAmelCase__   :				Union[str, Any] 			=				["stem"] + [F"""stage{idx}""" for idx in range(1			,					len(self.depths   ) + 1   )]
        lowerCAmelCase__			,						lowerCAmelCase__   :				Union[str, Any] 			=				get_aligned_output_features_output_indices(
            out_features=snake_case			,					out_indices=snake_case			,					stage_names=self.stage_names   )






