



import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

						if is_vision_available():
												from transformers import MaskFormerImageProcessor

if is_vision_available():
						from PIL import Image



class 						UpperCAmelCase_					:







							def __init__(     self,    __a,    __a=2,    __a=True,    __a=False,    __a=10,    __a=3,    __a=32 * 4,    __a=32 * 6,    __a=4,    __a=32,    ):

														'''simple docstring'''

														_lowerCAmelCase  :							Any				     =					parent
														_lowerCAmelCase  :							Tuple				     =					batch_size
														_lowerCAmelCase  :							List[Any]				     =					is_training
														_lowerCAmelCase  :							Any				     =					use_auxiliary_loss
														_lowerCAmelCase  :							Any				     =					num_queries
														_lowerCAmelCase  :							List[Any]				     =					num_channels
														_lowerCAmelCase  :							Optional[Any]				     =					min_size
														_lowerCAmelCase  :							Optional[Any]				     =					max_size
														_lowerCAmelCase  :							int				     =					num_labels
														_lowerCAmelCase  :							Any				     =					mask_feature_size







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							str				     =					floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
														    __a)

														_lowerCAmelCase  :							Optional[int]				     =					torch.ones([self.batch_size, self.min_size, self.max_size],    device=__a)

														_lowerCAmelCase  :							str				     =					(
														    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size],    device=__a) > 0.5
														).float()
														_lowerCAmelCase  :							Optional[int]				     =					(torch.rand((self.batch_size, self.num_labels),    device=__a) > 0.5).long()

														_lowerCAmelCase  :							Any				     =					self.get_config()
														return config, pixel_values, pixel_mask, mask_labels, class_labels







							def      snake_case__   (     self):

														'''simple docstring'''

														return MaskFormerConfig.from_backbone_and_decoder_configs(
														    backbone_config=SwinConfig(
														        depths=[1, 1, 1, 1],    ),    decoder_config=DetrConfig(
														        decoder_ffn_dim=128,    num_queries=self.num_queries,    decoder_attention_heads=2,    d_model=self.mask_feature_size,    ),    mask_feature_size=self.mask_feature_size,    fpn_feature_size=self.mask_feature_size,    num_channels=self.num_channels,    num_labels=self.num_labels,    )







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase  :							Optional[int]				     =					self.prepare_config_and_inputs()
														_lowerCAmelCase  :							int				     =					{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
														return config, inputs_dict







							def      snake_case__   (     self,    __a,    __a):

														'''simple docstring'''

														_lowerCAmelCase  :							str				     =					output.encoder_hidden_states
														_lowerCAmelCase  :							List[Any]				     =					output.pixel_decoder_hidden_states
														_lowerCAmelCase  :							Dict				     =					output.transformer_decoder_hidden_states

														self.parent.assertTrue(len(__a),    len(config.backbone_config.depths))
														self.parent.assertTrue(len(__a),    len(config.backbone_config.depths))
														self.parent.assertTrue(len(__a),    config.decoder_config.decoder_layers)







							def      snake_case__   (     self,    __a,    __a,    __a,    __a=False):

														'''simple docstring'''

														with torch.no_grad():
																					_lowerCAmelCase  :							List[str]				     =					MaskFormerModel(config=__a)
																					model.to(__a)
																					model.eval()

																					_lowerCAmelCase  :							List[Any]				     =					model(pixel_values=__a,    pixel_mask=__a)
																					_lowerCAmelCase  :							str				     =					model(__a,    output_hidden_states=__a)
														# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
														# encoder and pixel decoder
														self.parent.assertEqual(
														    output.transformer_decoder_last_hidden_state.shape,    (self.batch_size, self.num_queries, self.mask_feature_size),    )
														# let's ensure the other two hidden state exists
														self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None)
														self.parent.assertTrue(output.encoder_last_hidden_state is not None)

														if output_hidden_states:
																					self.check_output_hidden_state(__a,    __a)







							def      snake_case__   (     self,    __a,    __a,    __a,    __a,    __a):

														'''simple docstring'''

														_lowerCAmelCase  :							Dict				     =					MaskFormerForInstanceSegmentation(config=__a)
														model.to(__a)
														model.eval()

														def comm_check_on_output(__a):
																					# let's still check that all the required stuff is there
																					self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None)
																					self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None)
																					self.parent.assertTrue(result.encoder_last_hidden_state is not None)
																					# okay, now we need to check the logits shape
																					# due to the encoder compression, masks have a //4 spatial size
																					self.parent.assertEqual(
																					    result.masks_queries_logits.shape,    (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4),    )
																					# + 1 for null class
																					self.parent.assertEqual(
																					    result.class_queries_logits.shape,    (self.batch_size, self.num_queries, self.num_labels + 1))

														with torch.no_grad():
																					_lowerCAmelCase  :							List[Any]				     =					model(pixel_values=__a,    pixel_mask=__a)
																					_lowerCAmelCase  :							int				     =					model(__a)

																					comm_check_on_output(__a)

																					_lowerCAmelCase  :							Any				     =					model(
																					    pixel_values=__a,    pixel_mask=__a,    mask_labels=__a,    class_labels=__a)

														comm_check_on_output(__a)

														self.parent.assertTrue(result.loss is not None)
														self.parent.assertEqual(result.loss.shape,    torch.Size([1]))



@require_torch
class 						UpperCAmelCase_					( a     ,      a     ,      unittest.TestCase):
							lowerCamelCase__         =	(MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
							lowerCamelCase__         =	(
							    {'feature-extraction': MaskFormerModel, 'image-segmentation': MaskFormerForInstanceSegmentation}
							    if is_torch_available()
							    else {}
							)

							lowerCamelCase__         =	False
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False
							lowerCamelCase__         =	False







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Tuple				     =					MaskFormerModelTester(self)
														_lowerCAmelCase  :							Union[str, Any]				     =					ConfigTester(self,    config_class=__a,    has_text_modality=__a)







							def      snake_case__   (     self):

														'''simple docstring'''

														self.config_tester.run_common_tests()







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							Optional[int]				     =					self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.create_and_check_maskformer_model(__a,    **__a,    output_hidden_states=__a)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Optional[int]				     =					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__a)







							@unittest.skip(reason="MaskFormer does not use inputs_embeds")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@unittest.skip(reason="MaskFormer does not have a get_input_embeddings method")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@unittest.skip(reason="MaskFormer is not a generative model")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@unittest.skip(reason="MaskFormer does not use token embeddings")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@require_torch_multi_gpu
							@unittest.skip(
							    reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
							def      snake_case__   (     self):

														'''simple docstring'''

														pass







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							Optional[int]				     =					self.model_tester.prepare_config_and_inputs_for_common()

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

																					_lowerCAmelCase  :							Optional[int]				     =					["pixel_values"]
																					self.assertListEqual(arg_names[:1],    __a)







							@slow
							def      snake_case__   (     self):

														'''simple docstring'''

														for model_name in ["facebook/maskformer-swin-small-coco"]:
																					_lowerCAmelCase  :							str				     =					MaskFormerModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							List[Any]				     =					(self.model_tester.min_size,) * 2
														_lowerCAmelCase  :							Any				     =					{
														    "pixel_values": torch.randn((2, 3, *size),    device=__a),
														    "mask_labels": torch.randn((2, 10, *size),    device=__a),
														    "class_labels": torch.zeros(2,    10,    device=__a).long(),
														}

														_lowerCAmelCase  :							str				     =					MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(__a)
														_lowerCAmelCase  :							Tuple				     =					model(**__a)
														self.assertTrue(outputs.loss is not None)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							List[Any]				     =					self.model_tester.prepare_config_and_inputs_for_common()
														self.model_tester.create_and_check_maskformer_model(__a,    **__a,    output_hidden_states=__a)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase     ,					_lowerCAmelCase  :							Tuple				     =					self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					_lowerCAmelCase  :							Any				     =					model_class(__a).to(__a)
																					_lowerCAmelCase  :							Tuple				     =					model(**__a,    output_attentions=__a)
																					self.assertTrue(outputs.attentions is not None)







							def      snake_case__   (     self):

														'''simple docstring'''

														if not self.model_tester.is_training:
																					return
														# only MaskFormerForInstanceSegmentation has the loss
														_lowerCAmelCase  :							Any				     =					self.all_model_classes[1]
														_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase  :							Optional[int]				     =					self.model_tester.prepare_config_and_inputs()

														_lowerCAmelCase  :							List[str]				     =					model_class(__a)
														model.to(__a)
														model.train()

														_lowerCAmelCase  :							Optional[int]				     =					model(__a,    mask_labels=__a,    class_labels=__a).loss
														loss.backward()







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Union[str, Any]				     =					self.all_model_classes[1]
														_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase  :							int				     =					self.model_tester.prepare_config_and_inputs()
														_lowerCAmelCase  :							Dict				     =					True
														_lowerCAmelCase  :							str				     =					True

														_lowerCAmelCase  :							List[Any]				     =					model_class(__a)
														model.to(__a)
														model.train()

														_lowerCAmelCase  :							Optional[Any]				     =					model(__a,    mask_labels=__a,    class_labels=__a)

														_lowerCAmelCase  :							List[Any]				     =					outputs.encoder_hidden_states[0]
														encoder_hidden_states.retain_grad()

														_lowerCAmelCase  :							Optional[Any]				     =					outputs.pixel_decoder_hidden_states[0]
														pixel_decoder_hidden_states.retain_grad()
														# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
														_lowerCAmelCase  :							Optional[Any]				     =					outputs.transformer_decoder_hidden_states[0]
														transformer_decoder_hidden_states.retain_grad()

														_lowerCAmelCase  :							Optional[Any]				     =					outputs.attentions[0]
														attentions.retain_grad()

														outputs.loss.backward(retain_graph=__a)

														self.assertIsNotNone(encoder_hidden_states.grad)
														self.assertIsNotNone(pixel_decoder_hidden_states.grad)
														self.assertIsNotNone(transformer_decoder_hidden_states.grad)
														self.assertIsNotNone(attentions.grad)



_snake_case	=						1e-4






def        A       (      ):





							'''simple docstring'''




							_lowerCAmelCase  :							Union[str, Any]				     =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
							return image



@require_vision
@slow
class 						UpperCAmelCase_					( unittest.TestCase):







							@cached_property
							def      snake_case__   (     self):

														'''simple docstring'''

														return (
														    MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco")
														    if is_vision_available()
														    else None
														)







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							str				     =					MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco").to(__a)
														_lowerCAmelCase  :							str				     =					self.default_image_processor
														_lowerCAmelCase  :							List[Any]				     =					prepare_img()
														_lowerCAmelCase  :							Union[str, Any]				     =					image_processor(__a,    return_tensors="pt").to(__a)
														_lowerCAmelCase  :							Tuple				     =					inputs["pixel_values"].shape
														# check size is divisible by 32
														self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
														# check size
														self.assertEqual(__a,    (1, 3, 800, 1088))

														with torch.no_grad():
																					_lowerCAmelCase  :							int				     =					model(**__a)

														_lowerCAmelCase  :							Optional[Any]				     =					torch.tensor(
														    [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]).to(__a)
														self.assertTrue(
														    torch.allclose(
														        outputs.encoder_last_hidden_state[0, 0, :3, :3],    __a,    atol=__a))

														_lowerCAmelCase  :							List[Any]				     =					torch.tensor(
														    [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]).to(__a)
														self.assertTrue(
														    torch.allclose(
														        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3],    __a,    atol=__a))

														_lowerCAmelCase  :							Optional[int]				     =					torch.tensor(
														    [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]).to(__a)
														self.assertTrue(
														    torch.allclose(
														        outputs.transformer_decoder_last_hidden_state[0, :3, :3],    __a,    atol=__a))







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							List[str]				     =					(
														    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco")
														    .to(__a)
														    .eval()
														)
														_lowerCAmelCase  :							Tuple				     =					self.default_image_processor
														_lowerCAmelCase  :							List[Any]				     =					prepare_img()
														_lowerCAmelCase  :							Any				     =					image_processor(__a,    return_tensors="pt").to(__a)
														_lowerCAmelCase  :							Union[str, Any]				     =					inputs["pixel_values"].shape
														# check size is divisible by 32
														self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
														# check size
														self.assertEqual(__a,    (1, 3, 800, 1088))

														with torch.no_grad():
																					_lowerCAmelCase  :							int				     =					model(**__a)
														# masks_queries_logits
														_lowerCAmelCase  :							List[str]				     =					outputs.masks_queries_logits
														self.assertEqual(
														    masks_queries_logits.shape,    (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4),    )
														_lowerCAmelCase  :							List[str]				     =					[
														    [-1.3_737_124, -1.7_724_937, -1.9_364_233],
														    [-1.5_977_281, -1.9_867_939, -2.1_523_695],
														    [-1.5_795_398, -1.9_269_832, -2.093_942],
														]
														_lowerCAmelCase  :							Tuple				     =					torch.tensor(__a).to(__a)
														self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3],    __a,    atol=__a))
														# class_queries_logits
														_lowerCAmelCase  :							int				     =					outputs.class_queries_logits
														self.assertEqual(
														    class_queries_logits.shape,    (1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
														_lowerCAmelCase  :							List[str]				     =					torch.tensor(
														    [
														        [1.6512E00, -5.2572E00, -3.3519E00],
														        [3.6169E-02, -5.9025E00, -2.9313E00],
														        [1.0766E-04, -7.7630E00, -5.1263E00],
														    ]).to(__a)
														self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3],    __a,    atol=__a))







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							Tuple				     =					(
														    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff")
														    .to(__a)
														    .eval()
														)
														_lowerCAmelCase  :							List[Any]				     =					self.default_image_processor
														_lowerCAmelCase  :							int				     =					prepare_img()
														_lowerCAmelCase  :							Dict				     =					image_processor(__a,    return_tensors="pt").to(__a)
														_lowerCAmelCase  :							List[str]				     =					inputs["pixel_values"].shape
														# check size is divisible by 32
														self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
														# check size
														self.assertEqual(__a,    (1, 3, 800, 1088))

														with torch.no_grad():
																					_lowerCAmelCase  :							str				     =					model(**__a)
														# masks_queries_logits
														_lowerCAmelCase  :							Optional[int]				     =					outputs.masks_queries_logits
														self.assertEqual(
														    masks_queries_logits.shape,    (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4),    )
														_lowerCAmelCase  :							List[Any]				     =					[[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
														_lowerCAmelCase  :							int				     =					torch.tensor(__a).to(__a)
														self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3],    __a,    atol=__a))
														# class_queries_logits
														_lowerCAmelCase  :							int				     =					outputs.class_queries_logits
														self.assertEqual(
														    class_queries_logits.shape,    (1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
														_lowerCAmelCase  :							Dict				     =					torch.tensor(
														    [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]).to(__a)
														self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3],    __a,    atol=__a))







							def      snake_case__   (     self):

														'''simple docstring'''

														_lowerCAmelCase  :							str				     =					(
														    MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco")
														    .to(__a)
														    .eval()
														)
														_lowerCAmelCase  :							Tuple				     =					self.default_image_processor

														_lowerCAmelCase  :							Optional[Any]				     =					image_processor(
														    [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))],    segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)],    return_tensors="pt",    )

														_lowerCAmelCase  :							int				     =					inputs["pixel_values"].to(__a)
														_lowerCAmelCase  :							List[Any]				     =					[el.to(__a) for el in inputs["mask_labels"]]
														_lowerCAmelCase  :							Dict				     =					[el.to(__a) for el in inputs["class_labels"]]

														with torch.no_grad():
																					_lowerCAmelCase  :							Optional[Any]				     =					model(**__a)

														self.assertTrue(outputs.loss is not None)





import requests
from bsa import BeautifulSoup






def        A       (      _lowerCamelCase = "https://www.worldometers.info/coronavirus"						):





							'''simple docstring'''




							_lowerCAmelCase  :							str				     =					BeautifulSoup(requests.get(_lowerCamelCase						).text       ,				"html.parser"						)
							_lowerCAmelCase  :							str				     =					soup.findAll("h1"						)
							_lowerCAmelCase  :							Optional[int]				     =					soup.findAll("div"       ,				{"class": "maincounter-number"}						)
							keys += soup.findAll("span"       ,				{"class": "panel-title"}						)
							values += soup.findAll("div"       ,				{"class": "number-table-main"}						)
							return {key.text.strip(): value.text.strip() for key, value in zip(_lowerCamelCase       ,				_lowerCamelCase						)}


if __name__ == "__main__":
						print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n")
						for key, value in world_covidaa_stats().items():
												print(f'''{key}\n{value}\n''')
