





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


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase					)     ->	str:
    lowerCamelCase__       : Optional[Any]   					=						test_results.split(' '					)

    lowerCamelCase__       : Union[str, Any]   					=						0
    lowerCamelCase__       : List[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.
    lowerCamelCase__       : List[str]   					=						expressions[-2] if '=' in expressions[-1] else expressions[-1]

    for i, expression in enumerate(_UpperCAmelCase					):
        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 (			_UpperCAmelCase					)     ->	str:
    lowerCamelCase__       : Tuple   					=						{}
    lowerCamelCase__       : List[str]   					=						None
    lowerCamelCase__       : Any   					=						False
    for line in failures_short_lines.split('\n'					):
        if re.search(r'_ \[doctest\]'		,      _UpperCAmelCase					):
            lowerCamelCase__       : List[Any]   					=						True
            lowerCamelCase__       : int   					=						line.split(' '					)[2]
        elif in_error and not line.split(' '					)[0].isdigit():
            lowerCamelCase__       : Optional[Any]   					=						line
            lowerCamelCase__       : Tuple   					=						False

    return failures

class   lowerCAmelCase				:
 def __init__( self    : Any     ,	UpperCAmelCase    : str     ,	UpperCAmelCase    : Dict      )     ->      Union[str, Any]:
     lowerCamelCase__       : Optional[int]   					=						title

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

     # Failures and success of the modeling tests
     lowerCamelCase__       : List[Any]   					=						doc_test_results
 @property
 def 	A_      ( self    : Union[str, Any]      )     ->      str:
     lowerCamelCase__       : Optional[Any]   					=						[self._time_spent]
     lowerCamelCase__       : List[str]   					=						0

     for time in time_spent:
         lowerCamelCase__       : Optional[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(UpperCAmelCase      ) == 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 * 3600 + minutes * 60 + seconds

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

     lowerCamelCase__       : Optional[int]   					=						''
     for category, failures in category_failures.items():
         if len(UpperCAmelCase      ) == 0:
             continue

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

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

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

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

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

     lowerCamelCase__       : str   					=						client.chat_postMessage(
         channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']     ,	blocks=self.payload     ,	text=UpperCAmelCase     ,	)
 def 	A_      ( self    : Dict     ,	UpperCAmelCase    : Optional[int]     ,	UpperCAmelCase    : int     ,	UpperCAmelCase    : Optional[int]     ,	UpperCAmelCase    : List[Any]      )     ->      Optional[int]:
     lowerCamelCase__       : Dict   					=						''
     for key, value in failures.items():
         lowerCamelCase__       : Dict   					=						value[:200] + ' [Truncated]' if len(UpperCAmelCase      ) > 250 else value
         failures_text += F"""*{key}*\n_{value}_\n\n"""

     lowerCamelCase__       : Union[str, Any]   					=						job_name
     lowerCamelCase__       : Dict   					=						{'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}}

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

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

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

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

             time.sleep(1      )


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

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

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

    return {}


def 			SCREAMING_SNAKE_CASE (			_UpperCAmelCase					)     ->	List[str]:
    lowerCamelCase__       : List[str]   					=						{}

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

    return _artifact


def 			SCREAMING_SNAKE_CASE (			)     ->	List[str]:

    class   lowerCAmelCase				:
     def __init__( self    : Union[str, Any]     ,	UpperCAmelCase    : str      )     ->      Any:
         lowerCamelCase__       : List[Any]   					=						name
         lowerCamelCase__       : str   					=						[]
     def __str__( self    : Union[str, Any]      )     ->      Optional[int]:
         return self.name







     def 	A_      ( self    : Optional[int]     ,	UpperCAmelCase    : str      )     ->      Tuple:
         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__       : str   					=						Artifact(_UpperCAmelCase					)

            _available_artifacts[artifact_name].add_path(_UpperCAmelCase					)

    return _available_artifacts


if __name__ == "__main__":
    _UpperCAmelCase							:			Dict        =							get_job_links()
    _UpperCAmelCase							:			List[str]        =							retrieve_available_artifacts()

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

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

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

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

                if "::" in line:
                    _UpperCAmelCase  ,_UpperCAmelCase							:			Optional[Any]        =							line.split("""::""")
                else:
                    _UpperCAmelCase  ,_UpperCAmelCase							:			int        =							line, line

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

                        _UpperCAmelCase							:			Tuple        =							all_failures[test] if test in all_failures else """N/A"""
                        _UpperCAmelCase							:			Union[str, Any]        =							failure
                        break

    _UpperCAmelCase							:			List[str]        =							Message("""🤗 Results of the doc tests.""", doc_test_results)
    message.post()
    message.post_reply()












from typing import List

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


_UpperCAmelCase							:			Any        =							logging.get_logger(__name__)

_UpperCAmelCase							:			Union[str, Any]        =							{
    """snap-research/efficientformer-l1-300""": (
        """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"""
    ),
}

class   lowerCAmelCase				(   __UpperCamelCase     ):
 UpperCAmelCase__						=						"""efficientformer"""
 def __init__( self    : Dict     ,	UpperCAmelCase    : List[int] = [3, 2, 6, 4]     ,	UpperCAmelCase    : List[int] = [48, 96, 224, 448]     ,	UpperCAmelCase    : List[bool] = [True, True, True, True]     ,	UpperCAmelCase    : int = 448     ,	UpperCAmelCase    : int = 32     ,	UpperCAmelCase    : int = 4     ,	UpperCAmelCase    : int = 7     ,	UpperCAmelCase    : int = 5     ,	UpperCAmelCase    : int = 8     ,	UpperCAmelCase    : int = 4     ,	UpperCAmelCase    : float = 0.0     ,	UpperCAmelCase    : int = 16     ,	UpperCAmelCase    : int = 3     ,	UpperCAmelCase    : int = 3     ,	UpperCAmelCase    : int = 3     ,	UpperCAmelCase    : int = 2     ,	UpperCAmelCase    : int = 1     ,	UpperCAmelCase    : float = 0.0     ,	UpperCAmelCase    : int = 1     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : bool = True     ,	UpperCAmelCase    : float = 1e-5     ,	UpperCAmelCase    : str = "gelu"     ,	UpperCAmelCase    : float = 0.0_2     ,	UpperCAmelCase    : float = 1e-12     ,	UpperCAmelCase    : int = 224     ,	UpperCAmelCase    : float = 1e-05     ,	**UpperCAmelCase    : Tuple     ,	)     ->      None:
     super().__init__(**UpperCAmelCase      )

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





