





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 				_UpperCAmelCase			(    A     ):




   '''simple docstring'''

   UpperCAmelCase__						=test_results.split(" "     )

   UpperCAmelCase__						=0
   UpperCAmelCase__						=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__						=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     ):




   '''simple docstring'''

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

   return failures

class     snake_case_		:






 '''simple docstring'''





 def __init__(  self,		A_,		A_		)	->       Optional[int]:
    UpperCAmelCase__						=title

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

    # Failures and success of the modeling tests
    UpperCAmelCase__						=doc_test_results

 @property
 def  __UpperCAmelCase						(  self		)	->       str:
    UpperCAmelCase__						=[self._time_spent]
    UpperCAmelCase__						=0

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

       UpperCAmelCase__			,							UpperCAmelCase__			,							UpperCAmelCase__						=int(time_parts[0]		), int(time_parts[1]		), float(time_parts[2]		)
       total_secs += hours * 3600 + minutes * 60 + seconds

    UpperCAmelCase__			,							UpperCAmelCase__			,							UpperCAmelCase__						=total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60
    return f"""{int(A_		)}h{int(A_		)}m{int(A_		)}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		)	->       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  __UpperCAmelCase						(  self		)	->       Dict:
    UpperCAmelCase__						=40
    UpperCAmelCase__						={k: v["failed"] for k, v in doc_test_results.items() if isinstance(A_,		A_		)}

    UpperCAmelCase__						=""
    for category, failures in category_failures.items():
       if len(A_		) == 0:
          continue

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

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

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

 @property
 def  __UpperCAmelCase						(  self		)	->       str:
    UpperCAmelCase__						=[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(A_		)

 @staticmethod
 def  __UpperCAmelCase						(  )	->       int:
    UpperCAmelCase__						=[
        {
            "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(A_		)}		)		)

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

 def  __UpperCAmelCase						(  self		)	->       Tuple:
    print("Sending the following payload"		)
    print(json.dumps({"blocks": json.loads(self.payload		)}		)		)

    UpperCAmelCase__						=f"""{self.n_failures} failures out of {self.n_tests} tests,""" if self.n_failures else "All tests passed."

    UpperCAmelCase__						=client.chat_postMessage(
        channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"],		blocks=self.payload,		text=A_,		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_,		A_		)	->       List[Any]:
    UpperCAmelCase__						=""
    for key, value in failures.items():
       UpperCAmelCase__						=value[:200] + " [Truncated]" if len(A_		) > 250 else value
       failures_text += f"""*{key}*\n_{value}_\n\n"""

    UpperCAmelCase__						=job_name
    UpperCAmelCase__						={"type": "section", "text": {"type": "mrkdwn", "text": text}}

    if job_link is not None:
       UpperCAmelCase__						={
           "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."		)

    UpperCAmelCase__						=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__						=sorted(self.doc_test_results.items(),		key=lambda A_		: t[0]		)
    for job, job_result in sorted_dict:
       if len(job_result["failures"]		):
          UpperCAmelCase__						=f"""*Num failures* :{len(job_result['failed']		)} \n"""
          UpperCAmelCase__						=job_result["failures"]
          UpperCAmelCase__						=self.get_reply_blocks(A_,		A_,		A_,		text=A_		)

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

          time.sleep(1		)






def 				_UpperCAmelCase			(    ):




   '''simple docstring'''

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

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

      for i in range(A     ):
         UpperCAmelCase__						=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     ):




   '''simple docstring'''

   UpperCAmelCase__						={}

   if os.path.exists(A     ):
      UpperCAmelCase__						=os.listdir(A     )
      for file in files:
         try:
            with open(os.path.join(A				,							A     )				,							encoding="utf-8"     ) as f:
               UpperCAmelCase__						=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,		A_		)	->       Any:
       UpperCAmelCase__						=name
       UpperCAmelCase__						=[]

    def __str__(  self		)	->       Union[str, Any]:
       return self.name






    def  __UpperCAmelCase						(  self,		A_		)	->       str:
       self.paths.append({"name": self.name, "path": path}		)

   UpperCAmelCase__						={}

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

         _available_artifacts[artifact_name].add_path(A     )

   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()










import functools
import operator

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


UpperCamelCase_												=	logging.get_logger(__name__)

UpperCamelCase_												=	{
    'microsoft/wavlm-base': 'https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json',
    # See all WavLM models at https://huggingface.co/models?filter=wavlm
}

class     snake_case_		(   a							):






 '''simple docstring'''





 __UpperCamelCase       =      'wavlm'

 def __init__(  self,		A_=32,		A_=768,		A_=12,		A_=12,		A_=3072,		A_="gelu",		A_=0.1,		A_=0.1,		A_=0.1,		A_=0.0,		A_=0.1,		A_=0.1,		A_=0.02,		A_=1E-5,		A_="group",		A_="gelu",		A_=(512, 512, 512, 512, 512, 512, 512),		A_=(5, 2, 2, 2, 2, 2, 2),		A_=(10, 3, 3, 3, 3, 2, 2),		A_=False,		A_=128,		A_=16,		A_=320,		A_=800,		A_=False,		A_=True,		A_=0.05,		A_=10,		A_=2,		A_=0.0,		A_=10,		A_=320,		A_=2,		A_=0.1,		A_=100,		A_=256,		A_=256,		A_=0.1,		A_="mean",		A_=False,		A_=False,		A_=256,		A_=(512, 512, 512, 512, 1500),		A_=(5, 3, 3, 1, 1),		A_=(1, 2, 3, 1, 1),		A_=512,		A_=80,		A_=0,		A_=1,		A_=2,		A_=False,		A_=3,		A_=2,		A_=3,		A_=None,		**A_,		)	->       Union[str, Any]:
    super().__init__(**A_,		pad_token_id=A_,		bos_token_id=A_,		eos_token_id=A_		)
    UpperCAmelCase__						=hidden_size
    UpperCAmelCase__						=feat_extract_norm
    UpperCAmelCase__						=feat_extract_activation
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=conv_bias
    UpperCAmelCase__						=num_buckets
    UpperCAmelCase__						=max_bucket_distance
    UpperCAmelCase__						=num_conv_pos_embeddings
    UpperCAmelCase__						=num_conv_pos_embedding_groups
    UpperCAmelCase__						=len(self.conv_dim		)
    UpperCAmelCase__						=num_hidden_layers
    UpperCAmelCase__						=intermediate_size
    UpperCAmelCase__						=hidden_act
    UpperCAmelCase__						=num_attention_heads
    UpperCAmelCase__						=hidden_dropout
    UpperCAmelCase__						=attention_dropout
    UpperCAmelCase__						=activation_dropout
    UpperCAmelCase__						=feat_proj_dropout
    UpperCAmelCase__						=final_dropout
    UpperCAmelCase__						=layerdrop
    UpperCAmelCase__						=layer_norm_eps
    UpperCAmelCase__						=initializer_range
    UpperCAmelCase__						=num_ctc_classes
    UpperCAmelCase__						=vocab_size
    UpperCAmelCase__						=do_stable_layer_norm
    UpperCAmelCase__						=use_weighted_layer_sum
    UpperCAmelCase__						=classifier_proj_size

    if (
        (len(self.conv_stride		) != self.num_feat_extract_layers)
        or (len(self.conv_kernel		) != self.num_feat_extract_layers)
        or (len(self.conv_dim		) != self.num_feat_extract_layers)
    ):
       raise ValueError(
           "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
           " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
           f""" {len(self.conv_dim		)}`, `len(config.conv_stride) = {len(self.conv_stride		)}`,"""
           f""" `len(config.conv_kernel) = {len(self.conv_kernel		)}`."""		)

    # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
    UpperCAmelCase__						=apply_spec_augment
    UpperCAmelCase__						=mask_time_prob
    UpperCAmelCase__						=mask_time_length
    UpperCAmelCase__						=mask_time_min_masks
    UpperCAmelCase__						=mask_feature_prob
    UpperCAmelCase__						=mask_feature_length

    # parameters for pretraining with codevector quantized representations
    UpperCAmelCase__						=num_codevectors_per_group
    UpperCAmelCase__						=num_codevector_groups
    UpperCAmelCase__						=contrastive_logits_temperature
    UpperCAmelCase__						=num_negatives
    UpperCAmelCase__						=codevector_dim
    UpperCAmelCase__						=proj_codevector_dim
    UpperCAmelCase__						=diversity_loss_weight

    # ctc loss
    UpperCAmelCase__						=ctc_loss_reduction
    UpperCAmelCase__						=ctc_zero_infinity

    # adapter
    UpperCAmelCase__						=add_adapter
    UpperCAmelCase__						=adapter_kernel_size
    UpperCAmelCase__						=adapter_stride
    UpperCAmelCase__						=num_adapter_layers
    UpperCAmelCase__						=output_hidden_size or hidden_size

    # SequenceClassification-specific parameter. Feel free to ignore for other classes.
    UpperCAmelCase__						=classifier_proj_size

    # XVector-specific parameters. Feel free to ignore for other classes.
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=list(A_		)
    UpperCAmelCase__						=xvector_output_dim






 @property
 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    return functools.reduce(operator.mul,		self.conv_stride,		1		)



