

import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import MaskFormerSwinBackbone
		from transformers.models.maskformer import MaskFormerSwinModel



class lowerCamelCase			:



			'''simple docstring'''






			def __init__(				self	:						Union[str, Any]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						str=13		,      lowerCAmelCase_	:						Dict=32		,      lowerCAmelCase_	:						Optional[int]=2		,      lowerCAmelCase_	:						Dict=3		,      lowerCAmelCase_	:						Dict=16		,      lowerCAmelCase_	:						Optional[int]=[1, 2, 1]		,      lowerCAmelCase_	:						int=[2, 2, 4]		,      lowerCAmelCase_	:						Optional[Any]=2		,      lowerCAmelCase_	:						Optional[Any]=2.0		,      lowerCAmelCase_	:						Tuple=True		,      lowerCAmelCase_	:						Tuple=0.0		,      lowerCAmelCase_	:						Optional[int]=0.0		,      lowerCAmelCase_	:						Any=0.1		,      lowerCAmelCase_	:						List[str]="gelu"		,      lowerCAmelCase_	:						Any=False		,      lowerCAmelCase_	:						Optional[Any]=True		,      lowerCAmelCase_	:						Optional[int]=0.02		,      lowerCAmelCase_	:						Any=1e-5		,      lowerCAmelCase_	:						Dict=True		,      lowerCAmelCase_	:						str=None		,      lowerCAmelCase_	:						Tuple=True		,      lowerCAmelCase_	:						Dict=10		,      lowerCAmelCase_	:						Any=8		,      lowerCAmelCase_	:						List[Any]=["stage1", "stage2", "stage3"]		,      lowerCAmelCase_	:						Any=[1, 2, 3]		,      )      ->		Dict:





									'''simple docstring'''
									A__					:       Tuple     =parent
									A__					:       Union[str, Any]     =batch_size
									A__					:       int     =image_size
									A__					:       Union[str, Any]     =patch_size
									A__					:       Optional[Any]     =num_channels
									A__					:       int     =embed_dim
									A__					:       Optional[Any]     =depths
									A__					:       Optional[Any]     =num_heads
									A__					:       str     =window_size
									A__					:       Optional[Any]     =mlp_ratio
									A__					:       Dict     =qkv_bias
									A__					:       List[str]     =hidden_dropout_prob
									A__					:       Any     =attention_probs_dropout_prob
									A__					:       Optional[int]     =drop_path_rate
									A__					:       List[str]     =hidden_act
									A__					:       Optional[Any]     =use_absolute_embeddings
									A__					:       Tuple     =patch_norm
									A__					:       Union[str, Any]     =layer_norm_eps
									A__					:       List[str]     =initializer_range
									A__					:       str     =is_training
									A__					:       List[Any]     =scope
									A__					:       Dict     =use_labels
									A__					:       Any     =type_sequence_label_size
									A__					:       Union[str, Any]     =encoder_stride
									A__					:       Union[str, Any]     =out_features
									A__					:       Any     =out_indices


			def lowercase__						(				self	:						Union[str, Any]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       List[Any]     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

									A__					:       Dict     =None
									if self.use_labels:
															A__					:       Optional[Any]     =ids_tensor([self.batch_size]		,      self.type_sequence_label_size			)

									A__					:       str     =self.get_config()

									return config, pixel_values, labels


			def lowercase__						(				self	:						int			)      ->		Union[str, Any]:





									'''simple docstring'''
									return MaskFormerSwinConfig(
									    image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      embed_dim=self.embed_dim		,      depths=self.depths		,      num_heads=self.num_heads		,      window_size=self.window_size		,      mlp_ratio=self.mlp_ratio		,      qkv_bias=self.qkv_bias		,      hidden_dropout_prob=self.hidden_dropout_prob		,      attention_probs_dropout_prob=self.attention_probs_dropout_prob		,      drop_path_rate=self.drop_path_rate		,      hidden_act=self.hidden_act		,      use_absolute_embeddings=self.use_absolute_embeddings		,      path_norm=self.patch_norm		,      layer_norm_eps=self.layer_norm_eps		,      initializer_range=self.initializer_range		,      encoder_stride=self.encoder_stride		,      out_features=self.out_features		,      out_indices=self.out_indices		,      )


			def lowercase__						(				self	:						List[Any]		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Any			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       Tuple     =MaskFormerSwinModel(config=_a			)
									model.to(_a			)
									model.eval()
									A__					:       Union[str, Any]     =model(_a			)

									A__					:       int     =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
									A__					:       List[str]     =int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

									self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, expected_seq_len, expected_dim)			)


			def lowercase__						(				self	:						str		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						int			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Tuple     =MaskFormerSwinBackbone(config=_a			)
									model.to(_a			)
									model.eval()
									A__					:       List[str]     =model(_a			)

									# verify feature maps
									self.parent.assertEqual(len(result.feature_maps			)		,      len(config.out_features			)			)
									self.parent.assertListEqual(list(result.feature_maps[0].shape			)		,      [13, 16, 16, 16]			)

									# verify channels
									self.parent.assertEqual(len(model.channels			)		,      len(config.out_features			)			)
									self.parent.assertListEqual(model.channels		,      [16, 32, 64]			)

									# verify ValueError
									with self.parent.assertRaises(_a			):
															A__					:       Optional[Any]     =["stem"]
															A__					:       Optional[Any]     =MaskFormerSwinBackbone(config=_a			)



			def lowercase__						(				self	:						Tuple			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       List[Any]     =self.prepare_config_and_inputs()
									A__					:       Any     =config_and_inputs
									A__					:       Union[str, Any]     ={"pixel_values": pixel_values}
									return config, inputs_dict



@require_torch
class lowerCamelCase			(  _a	,						_a	,						unittest.TestCase						):



			'''simple docstring'''






			__snake_case        =	(
			    (
			        MaskFormerSwinModel,
			        MaskFormerSwinBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			__snake_case        =	{'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
			__snake_case        =	False
			__snake_case        =	False
			__snake_case        =	False
			__snake_case        =	False
			__snake_case        =	False


			def lowercase__						(				self	:						Union[str, Any]			)      ->		int:





									'''simple docstring'''
									A__					:       Tuple     =MaskFormerSwinModelTester(self			)
									A__					:       Any     =ConfigTester(self		,      config_class=_a		,      embed_dim=37			)


			@require_torch_multi_gpu
			@unittest.skip(
			    reason=(
			        """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
			        """ `nn.DataParallel`"""
			    )			)
			def lowercase__						(				self	:						Any			)      ->		Tuple:





									'''simple docstring'''
									pass


			def lowercase__						(				self	:						int			)      ->		Optional[Any]:





									'''simple docstring'''
									self.create_and_test_config_common_properties()
									self.config_tester.create_and_test_config_to_json_string()
									self.config_tester.create_and_test_config_to_json_file()
									self.config_tester.create_and_test_config_from_and_save_pretrained()
									self.config_tester.create_and_test_config_with_num_labels()
									self.config_tester.check_config_can_be_init_without_params()
									self.config_tester.check_config_arguments_init()


			def lowercase__						(				self	:						Tuple			)      ->		int:





									'''simple docstring'''
									return


			def lowercase__						(				self	:						List[str]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Dict     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_a			)


			def lowercase__						(				self	:						str			)      ->		str:





									'''simple docstring'''
									A__					:       List[Any]     =self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*_a			)


			@unittest.skip("""Swin does not use inputs_embeds"""			)
			def lowercase__						(				self	:						Optional[int]			)      ->		Dict:





									'''simple docstring'''
									pass


			@unittest.skip("""Swin does not support feedforward chunking"""			)
			def lowercase__						(				self	:						int			)      ->		Optional[int]:





									'''simple docstring'''
									pass


			def lowercase__						(				self	:						List[Any]			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       List[Any]     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       List[str]     =model_class(_a			)
															self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module)			)
															A__					:       Optional[Any]     =model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(_a		,      nn.Linear			)			)


			def lowercase__						(				self	:						Union[str, Any]			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Optional[int]     =self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															A__					:       List[Any]     =model_class(_a			)
															A__					:       Any     =inspect.signature(model.forward			)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															A__					:       Optional[int]     =[*signature.parameters.keys()]

															A__					:       List[str]     =["pixel_values"]
															self.assertListEqual(arg_names[:1]		,      _a			)


			@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""			)
			def lowercase__						(				self	:						Optional[int]			)      ->		List[Any]:





									'''simple docstring'''
									pass


			@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""			)
			def lowercase__						(				self	:						List[Any]			)      ->		Dict:





									'''simple docstring'''
									pass


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Union[str, Any]			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Optional[int]     =model_class(_a			)
									model.to(_a			)
									model.eval()

									with torch.no_grad():
															A__					:       Optional[int]     =model(**self._prepare_for_class(_a		,      _a			)			)

									A__					:       List[Any]     =outputs.hidden_states

									A__					:       Tuple     =getattr(
									    self.model_tester		,      """expected_num_hidden_layers"""		,      len(self.model_tester.depths			) + 1			)
									self.assertEqual(len(_a			)		,      _a			)

									# Swin has a different seq_length
									A__					:       Tuple     =(
									    config.patch_size
									    if isinstance(config.patch_size		,      collections.abc.Iterable			)
									    else (config.patch_size, config.patch_size)
									)

									A__					:       Optional[Any]     =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]			)		,      [num_patches, self.model_tester.embed_dim]		,      )


			def lowercase__						(				self	:						Union[str, Any]			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Tuple     =self.model_tester.prepare_config_and_inputs_for_common()

									A__					:       Optional[int]     =(
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size		,      collections.abc.Iterable			)
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)

									for model_class in self.all_model_classes:
															A__					:       Tuple     =True
															self.check_hidden_states_output(_a		,      _a		,      _a		,      _a			)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															A__					:       List[str]     =True

															self.check_hidden_states_output(_a		,      _a		,      _a		,      _a			)


			def lowercase__						(				self	:						Optional[Any]			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =self.model_tester.prepare_config_and_inputs_for_common()
									A__					:       Dict     =3

									A__					:       Dict     =(
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size		,      collections.abc.Iterable			)
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)
									A__					:       str     =(
									    config.patch_size
									    if isinstance(config.patch_size		,      collections.abc.Iterable			)
									    else (config.patch_size, config.patch_size)
									)

									A__					:       Optional[Any]     =image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
									A__					:       int     =image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

									for model_class in self.all_model_classes:
															A__					:       List[str]     =True
															self.check_hidden_states_output(_a		,      _a		,      _a		,      (padded_height, padded_width)			)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															A__					:       Optional[int]     =True
															self.check_hidden_states_output(_a		,      _a		,      _a		,      (padded_height, padded_width)			)


			@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""			)
			def lowercase__						(				self	:						Optional[int]			)      ->		int:





									'''simple docstring'''
									pass


			@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""			)
			def lowercase__						(				self	:						Optional[int]			)      ->		Any:





									'''simple docstring'''
									pass


			@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""			)
			def lowercase__						(				self	:						Union[str, Any]			)      ->		Any:





									'''simple docstring'''
									pass



			def lowercase__						(				self	:						Tuple			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =self.model_tester.prepare_config_and_inputs_for_common()

									def set_nan_tensor_to_zero(lowerCAmelCase_	:						Dict			):
															A__					:       Tuple     =0
															return t

									def check_equivalence(lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						List[str]={}			):
															with torch.no_grad():
																					A__					:       Optional[Any]     =model(**_a		,      return_dict=_a		,      **_a			)
																					A__					:       int     =model(**_a		,      return_dict=_a		,      **_a			).to_tuple()

																					def recursive_check(lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						str			):
																											if isinstance(_a		,      (List, Tuple)			):
																																	for tuple_iterable_value, dict_iterable_value in zip(_a		,      _a			):
																																							recursive_check(_a		,      _a			)
																											elif isinstance(_a		,      _a			):
																																	for tuple_iterable_value, dict_iterable_value in zip(
																																	    tuple_object.values()		,      dict_object.values()			):
																																							recursive_check(_a		,      _a			)
																											elif tuple_object is None:
																																	return
																											else:
																																	self.assertTrue(
																																	    torch.allclose(
																																	        set_nan_tensor_to_zero(_a			)		,      set_nan_tensor_to_zero(_a			)		,      atol=1e-5			)		,      msg=(
																																	        """Tuple and dict output are not equal. Difference:"""
																																	        f" {torch.max(torch.abs(tuple_object - dict_object			)			)}. Tuple has `nan`:"
																																	        f" {torch.isnan(_a			).any()} and `inf`: {torch.isinf(_a			)}. Dict has"
																																	        f" `nan`: {torch.isnan(_a			).any()} and `inf`: {torch.isinf(_a			)}."
																																	    )		,      )

																					recursive_check(_a		,      _a			)

									for model_class in self.all_model_classes:
															A__					:       str     =model_class(_a			)
															model.to(_a			)
															model.eval()

															A__					:       str     =self._prepare_for_class(_a		,      _a			)
															A__					:       Union[str, Any]     =self._prepare_for_class(_a		,      _a			)
															check_equivalence(_a		,      _a		,      _a			)

															A__					:       str     =self._prepare_for_class(_a		,      _a		,      return_labels=_a			)
															A__					:       Any     =self._prepare_for_class(_a		,      _a		,      return_labels=_a			)
															check_equivalence(_a		,      _a		,      _a			)

															A__					:       Any     =self._prepare_for_class(_a		,      _a			)
															A__					:       List[Any]     =self._prepare_for_class(_a		,      _a			)
															check_equivalence(_a		,      _a		,      _a		,      {"""output_hidden_states""": True}			)

															A__					:       Any     =self._prepare_for_class(_a		,      _a		,      return_labels=_a			)
															A__					:       str     =self._prepare_for_class(_a		,      _a		,      return_labels=_a			)
															check_equivalence(_a		,      _a		,      _a		,      {"""output_hidden_states""": True}			)



@require_torch
class lowerCamelCase			(  unittest.TestCase	,						_a						):



			'''simple docstring'''






			__snake_case        =	(MaskFormerSwinBackbone,) if is_torch_available() else ()
			__snake_case        =	MaskFormerSwinConfig


			def lowercase__						(				self	:						List[Any]			)      ->		Optional[int]:





									'''simple docstring'''
									A__					:       str     =MaskFormerSwinModelTester(self			)



			def lowercase__						(				self	:						str			)      ->		int:





									'''simple docstring'''
									A__					:       int     =self.model_tester.prepare_config_and_inputs_for_common()
									A__					:       Dict     =inputs_dict["pixel_values"].shape[0]

									for backbone_class in self.all_model_classes:
															A__					:       Any     =backbone_class(_a			)
															backbone.to(_a			)
															backbone.eval()

															A__					:       Dict     =backbone(**_a			)

															# Test default outputs and verify feature maps
															self.assertIsInstance(outputs.feature_maps		,      _a			)
															self.assertTrue(len(outputs.feature_maps			) == len(backbone.channels			)			)
															for feature_map, n_channels in zip(outputs.feature_maps		,      backbone.channels			):
																					self.assertTrue(feature_map.shape[:2]		,      (batch_size, n_channels)			)
															self.assertIsNone(outputs.hidden_states			)
															self.assertIsNone(outputs.attentions			)

															# Test output_hidden_states=True
															A__					:       Union[str, Any]     =backbone(**_a		,      output_hidden_states=_a			)
															self.assertIsNotNone(outputs.hidden_states			)
															self.assertTrue(len(outputs.hidden_states			)		,      len(backbone.stage_names			)			)
															# We skip the stem layer
															for hidden_states, n_channels in zip(outputs.hidden_states[1:]		,      backbone.channels			):
																					for hidden_state in hidden_states:
																											# Hidden states are in the format (batch_size, (height * width), n_channels)
																											A__					:       Dict     =hidden_state.shape
																											self.assertTrue((h_batch_size, h_n_channels)		,      (batch_size, n_channels)			)

            # Test output_attentions=True
															if self.has_attentions:
																					A__					:       Dict     =backbone(**_a		,      output_attentions=_a			)
																					self.assertIsNotNone(outputs.attentions			)




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


__snake_case			:     Optional[int]										=      WebClient(token=os.environ['CI_SLACK_BOT_TOKEN'])
def 						__lowerCamelCase	(       __snake_case					:		List[Any]	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Any     =test_results.split(""" """	)

						A__					:       List[Any]     =0
						A__					:       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.
						A__					:       Dict     =expressions[-2] if """=""" in expressions[-1] else expressions[-1]

						for i, expression in enumerate(__snake_case	):
												if "failed" in expression:
																		failed += int(expressions[i - 1]	)
												if "passed" in expression:
																		success += int(expressions[i - 1]	)

						return failed, success, time_spent
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							Optional[int]:






						"""simple docstring"""





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

						return failures



class lowerCamelCase			:



			'''simple docstring'''






			def __init__(				self	:						str		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Dict			)      ->		Dict:





									'''simple docstring'''
									A__					:       Any     =title

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

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


			@property
			def lowercase__						(				self	:						Optional[int]			)      ->		str:





									'''simple docstring'''
									A__					:       List[str]     =[self._time_spent]
									A__					:       str     =0

									for time in time_spent:
															A__					:       Union[str, 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(lowerCAmelCase_			) == 1:
																					A__					:       str     =[0, 0, time_parts[0]]

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

									A__   ,						A__   ,						A__					:       Optional[int]     =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	:						Any			)      ->		Dict:





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


			@property
			def lowercase__						(				self	:						Dict			)      ->		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 lowercase__						(				self	:						Tuple			)      ->		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 lowercase__						(				self	:						Optional[Any]			)      ->		Dict:





									'''simple docstring'''
									A__					:       Optional[Any]     =40
									A__					:       List[Any]     ={k: v["""failed"""] for k, v in doc_test_results.items() if isinstance(lowerCAmelCase_		,      lowerCAmelCase_			)}

									A__					:       Union[str, 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	:						Any			)      ->		str:





									'''simple docstring'''
									A__					:       Tuple     =[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:





									'''simple docstring'''
									A__					:       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(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[int]			)      ->		Tuple:





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

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

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


			def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Optional[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						List[Any]			)      ->		Any:





									'''simple docstring'''
									A__					:       int     =""""""
									for key, value in failures.items():
															A__					:       Optional[int]     =value[:2_00] + """ [Truncated]""" if len(lowerCAmelCase_			) > 2_50 else value
															failures_text += f"*{key}*\n_{value}_\n\n"

									A__					:       List[Any]     =job_name
									A__					:       Dict     ={"""type""": """section""", """text""": {"""type""": """mrkdwn""", """text""": text}}

									if job_link is not None:
															A__					:       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 lowercase__						(				self	:						str			)      ->		str:





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

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

									A__					:       Union[str, Any]     =sorted(self.doc_test_results.items()		,      key=lambda lowerCAmelCase_			: t[0]			)
									for job, job_result in sorted_dict:
															if len(job_result["""failures"""]			):
																					A__					:       Optional[Any]     =f"*Num failures* :{len(job_result['failed']			)} \n"
																					A__					:       Tuple     =job_result["""failures"""]
																					A__					:       Optional[Any]     =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 						__lowerCamelCase	(       )	->							Any:






						"""simple docstring"""





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

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

												for i in range(__snake_case	):
																		A__					:       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.""",		__snake_case	)

						return {}
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							Union[str, Any]:






						"""simple docstring"""





						A__					:       Any     ={}

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

						return _artifact
def 						__lowerCamelCase	(       )	->							Union[str, Any]:






						"""simple docstring"""





						class lowerCamelCase			:



									'''simple docstring'''






									def __init__(				self	:						List[str]		,      lowerCAmelCase_	:						str			)      ->		Any:





															'''simple docstring'''
															A__					:       List[Any]     =name
															A__					:       str     =[]


									def __str__(				self	:						Optional[Any]			)      ->		List[Any]:





															'''simple docstring'''
															return self.name



									def lowercase__						(				self	:						Any		,      lowerCAmelCase_	:						str			)      ->		Tuple:





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


						A__					:       Dict[str, Artifact]     ={}

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

																		_available_artifacts[artifact_name].add_path(__snake_case	)

						return _available_artifacts


if __name__ == "__main__":
		__snake_case			:     List[str]										=      get_job_links()
		__snake_case			:     int										=      retrieve_available_artifacts()

		__snake_case			:     Union[str, Any]										=      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'
		__snake_case			:     Dict										=      {
		    v: {
		        'failed': [],
		        'failures': {},
		    }
		    for v in docs.values()
		}

		# Link to the GitHub Action job
		__snake_case			:     List[Any]										=      github_actions_job_links.get('run_doctests')

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

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

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

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

												__snake_case			:     List[str]										=      all_failures[test] if test in all_failures else 'N/A'
												__snake_case			:     Optional[Any]										=      failure
												break

		__snake_case			:     int										=      Message('🤗 Results of the doc tests.', doc_test_results)
		message.post()
		message.post_reply()

