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





def 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				__lowercase 			=							test_results.split(''' '''							)

				__lowercase 			=							0
				__lowercase 			=							0

				# When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
				# When it is too long, those signs are not present.
				__lowercase 			=							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 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



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

				return failures




class    _UpperCamelCase      :


			"""simple docstring"""






			def __init__(   self      ,   lowerCAmelCase__      ,   lowerCAmelCase__						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							title

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

							# Failures and success of the modeling tests
							__lowercase 			=							doc_test_results





			@property
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							[self._time_spent]
							__lowercase 			=							0

							for time in time_spent:
											__lowercase 			=							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:
															__lowercase 			=							[0, 0, time_parts[0]]

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

							__lowercase			,     __lowercase			,     __lowercase 			=							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        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

							'''simple docstring'''


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





			@property
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					Dict:

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

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

							'''simple docstring'''


							__lowercase 			=							40
							__lowercase 			=							{k: v['''failed'''] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase__      ,   lowerCAmelCase__						)}

							__lowercase 			=							''''''
							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        _SCREAMING_SNAKE_CASE			(   self						)     ->					str:

							'''simple docstring'''


							__lowercase 			=							[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        _SCREAMING_SNAKE_CASE			(   )     ->					Any:

							'''simple docstring'''


							__lowercase 			=							[
							    {
							        '''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        _SCREAMING_SNAKE_CASE			(   self						)     ->					Tuple:

							'''simple docstring'''


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

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

							__lowercase 			=							client.chat_postMessage(
							    channel=os.environ['''CI_SLACK_CHANNEL_ID_DAILY''']      ,   blocks=self.payload      ,   text=lowerCAmelCase__      ,   )





			def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__      ,   lowerCAmelCase__						)     ->					int:

							'''simple docstring'''


							__lowercase 			=							''''''
							for key, value in failures.items():
											__lowercase 			=							value[:2_00] + ''' [Truncated]''' if len(lowerCAmelCase__						) > 2_50 else value
											failures_text += F"*{key}*\n_{value}_\n\n"

							__lowercase 			=							job_name
							__lowercase 			=							{'''type''': '''section''', '''text''': {'''type''': '''mrkdwn''', '''text''': text}}

							if job_link is not None:
											__lowercase 			=							{
											    '''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						)     ->					List[str]:

							'''simple docstring'''


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

							__lowercase 			=							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'''						)

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



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

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

								for i in range(lowercase							):
												__lowercase 			=							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 				UpperCAmelCase						(    lowercase							):







				"""simple docstring"""



				__lowercase 			=							{}

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

				return _artifact





def 				UpperCAmelCase						(    ):







				"""simple docstring"""



				class    _UpperCamelCase      :


							"""simple docstring"""






							def __init__(   self      ,   lowerCAmelCase__						)     ->					Optional[Any]:

											'''simple docstring'''


											__lowercase 			=							name
											__lowercase 			=							[]





							def __str__(   self						)     ->					int:

											'''simple docstring'''


											return self.name





							def        _SCREAMING_SNAKE_CASE			(   self      ,   lowerCAmelCase__						)     ->					Any:

											'''simple docstring'''


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


				__lowercase 			=							{}

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

												_available_artifacts[artifact_name].add_path(lowercase							)

				return _available_artifacts


if __name__ == "__main__":
		__a  :     Optional[int]       =  get_job_links()
		__a  :     Optional[int]       =  retrieve_available_artifacts()

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

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

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

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

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

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

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

		__a  :     Tuple       =  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


__a  :     str       =  logging.get_logger(__name__)

__a  :     int       =  {
    """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    _UpperCamelCase      (						_UpperCAmelCase ):


			"""simple docstring"""






			__a  : Any			 =						'''wavlm'''





			def __init__(   self      ,   lowerCAmelCase__=32      ,   lowerCAmelCase__=7_68      ,   lowerCAmelCase__=12      ,   lowerCAmelCase__=12      ,   lowerCAmelCase__=30_72      ,   lowerCAmelCase__="gelu"      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=0.0      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=0.02      ,   lowerCAmelCase__=1E-5      ,   lowerCAmelCase__="group"      ,   lowerCAmelCase__="gelu"      ,   lowerCAmelCase__=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12)      ,   lowerCAmelCase__=(5, 2, 2, 2, 2, 2, 2)      ,   lowerCAmelCase__=(10, 3, 3, 3, 3, 2, 2)      ,   lowerCAmelCase__=False      ,   lowerCAmelCase__=1_28      ,   lowerCAmelCase__=16      ,   lowerCAmelCase__=3_20      ,   lowerCAmelCase__=8_00      ,   lowerCAmelCase__=False      ,   lowerCAmelCase__=True      ,   lowerCAmelCase__=0.05      ,   lowerCAmelCase__=10      ,   lowerCAmelCase__=2      ,   lowerCAmelCase__=0.0      ,   lowerCAmelCase__=10      ,   lowerCAmelCase__=3_20      ,   lowerCAmelCase__=2      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__=1_00      ,   lowerCAmelCase__=2_56      ,   lowerCAmelCase__=2_56      ,   lowerCAmelCase__=0.1      ,   lowerCAmelCase__="mean"      ,   lowerCAmelCase__=False      ,   lowerCAmelCase__=False      ,   lowerCAmelCase__=2_56      ,   lowerCAmelCase__=(5_12, 5_12, 5_12, 5_12, 15_00)      ,   lowerCAmelCase__=(5, 3, 3, 1, 1)      ,   lowerCAmelCase__=(1, 2, 3, 1, 1)      ,   lowerCAmelCase__=5_12      ,   lowerCAmelCase__=80      ,   lowerCAmelCase__=0      ,   lowerCAmelCase__=1      ,   lowerCAmelCase__=2      ,   lowerCAmelCase__=False      ,   lowerCAmelCase__=3      ,   lowerCAmelCase__=2      ,   lowerCAmelCase__=3      ,   lowerCAmelCase__=None      ,   **lowerCAmelCase__      ,   )     ->					Tuple:

							'''simple docstring'''


							super().__init__(**lowerCAmelCase__      ,   pad_token_id=lowerCAmelCase__      ,   bos_token_id=lowerCAmelCase__      ,   eos_token_id=lowerCAmelCase__						)
							__lowercase 			=							hidden_size
							__lowercase 			=							feat_extract_norm
							__lowercase 			=							feat_extract_activation
							__lowercase 			=							list(lowerCAmelCase__						)
							__lowercase 			=							list(lowerCAmelCase__						)
							__lowercase 			=							list(lowerCAmelCase__						)
							__lowercase 			=							conv_bias
							__lowercase 			=							num_buckets
							__lowercase 			=							max_bucket_distance
							__lowercase 			=							num_conv_pos_embeddings
							__lowercase 			=							num_conv_pos_embedding_groups
							__lowercase 			=							len(self.conv_dim						)
							__lowercase 			=							num_hidden_layers
							__lowercase 			=							intermediate_size
							__lowercase 			=							hidden_act
							__lowercase 			=							num_attention_heads
							__lowercase 			=							hidden_dropout
							__lowercase 			=							attention_dropout
							__lowercase 			=							activation_dropout
							__lowercase 			=							feat_proj_dropout
							__lowercase 			=							final_dropout
							__lowercase 			=							layerdrop
							__lowercase 			=							layer_norm_eps
							__lowercase 			=							initializer_range
							__lowercase 			=							num_ctc_classes
							__lowercase 			=							vocab_size
							__lowercase 			=							do_stable_layer_norm
							__lowercase 			=							use_weighted_layer_sum
							__lowercase 			=							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
							__lowercase 			=							apply_spec_augment
							__lowercase 			=							mask_time_prob
							__lowercase 			=							mask_time_length
							__lowercase 			=							mask_time_min_masks
							__lowercase 			=							mask_feature_prob
							__lowercase 			=							mask_feature_length

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

							# ctc loss
							__lowercase 			=							ctc_loss_reduction
							__lowercase 			=							ctc_zero_infinity

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

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

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





			@property
			def        _SCREAMING_SNAKE_CASE			(   self						)     ->					int:

							'''simple docstring'''


							return functools.reduce(operator.mul      ,   self.conv_stride      ,   1						)