





"""simple docstring"""


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   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  def __init__(		self :							Optional[Any]       , __a :							Optional[int]       , __a :							Optional[Any]=2       , __a :							Any=True       , __a :							Optional[int]=False       , __a :							Optional[Any]=10       , __a :							Union[str, Any]=3       , __a :							Any=32 * 4       , __a :							Optional[Any]=32 * 6       , __a :							Optional[Any]=4       , __a :							Optional[int]=32       , )		->					Tuple:
        _UpperCamelCase   :						List[str]    =							parent
        _UpperCamelCase   :						Any    =							batch_size
        _UpperCamelCase   :						Any    =							is_training
        _UpperCamelCase   :						Tuple    =							use_auxiliary_loss
        _UpperCamelCase   :						Optional[int]    =							num_queries
        _UpperCamelCase   :						Any    =							num_channels
        _UpperCamelCase   :						str    =							min_size
        _UpperCamelCase   :						str    =							max_size
        _UpperCamelCase   :						List[str]    =							num_labels
        _UpperCamelCase   :						Tuple    =							mask_feature_size

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					Any:
        _UpperCamelCase   :						List[Any]    =							floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]						).to(
            __a						)

        _UpperCamelCase   :						Any    =							torch.ones([self.batch_size, self.min_size, self.max_size]       , device=__a						)

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

        _UpperCamelCase   :						Tuple    =							self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Union[str, Any]:
        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  __SCREAMING_SNAKE_CASE					(		self :							int						)		->					Optional[int]:
        _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						Optional[int]    =							self.prepare_config_and_inputs()
        _UpperCamelCase   :						Any    =							{"pixel_values": pixel_values, "pixel_mask": pixel_mask}
        return config, inputs_dict

  def  __SCREAMING_SNAKE_CASE					(		self :							str       , __a :							Optional[Any]       , __a :							Tuple						)		->					List[str]:
        _UpperCamelCase   :						Any    =							output.encoder_hidden_states
        _UpperCamelCase   :						Union[str, Any]    =							output.pixel_decoder_hidden_states
        _UpperCamelCase   :						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  __SCREAMING_SNAKE_CASE					(		self :							Tuple       , __a :							Tuple       , __a :							List[Any]       , __a :							Dict       , __a :							Dict=False						)		->					Optional[int]:
        with torch.no_grad():
              _UpperCamelCase   :						Tuple    =							MaskFormerModel(config=__a						)
              model.to(__a						)
              model.eval()

              _UpperCamelCase   :						Dict    =							model(pixel_values=__a       , pixel_mask=__a						)
              _UpperCamelCase   :						Dict    =							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  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]       , __a :							Any       , __a :							Dict       , __a :							Dict       , __a :							Any       , __a :							int						)		->					int:
        _UpperCamelCase   :						Optional[int]    =							MaskFormerForInstanceSegmentation(config=__a						)
        model.to(__a						)
        model.eval()

        def comm_check_on_output(__a :							Dict						):
              # 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():
              _UpperCamelCase   :						int    =							model(pixel_values=__a       , pixel_mask=__a						)
              _UpperCamelCase   :						Union[str, Any]    =							model(__a						)

              comm_check_on_output(__a						)

              _UpperCamelCase   :						int    =							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   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase		,	_UpperCamelCase		,	unittest.TestCase ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Union[str, Any]						  =       (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__				:Optional[Any]						  =       (
      {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       False
  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       False
  SCREAMING_SNAKE_CASE__				:List[str]						  =       False
  SCREAMING_SNAKE_CASE__				:int						  =       False

  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					List[Any]:
        _UpperCamelCase   :						List[Any]    =							MaskFormerModelTester(self						)
        _UpperCamelCase   :						Union[str, Any]    =							ConfigTester(self       , config_class=__a       , has_text_modality=__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					int:
        self.config_tester.run_common_tests()

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					List[str]:
        _UpperCamelCase,	_UpperCamelCase   :						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  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					Optional[Any]:
        _UpperCamelCase   :						List[str]    =							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  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					str:
        pass

  @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					List[Any]:
        pass

  @unittest.skip(reason="MaskFormer is not a generative model"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					Optional[int]:
        pass

  @unittest.skip(reason="MaskFormer does not use token embeddings"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					List[Any]:
        pass

  @require_torch_multi_gpu
  @unittest.skip(
      reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					List[Any]:
        pass

  @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]						)		->					List[str]:
        pass

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					str:
        _UpperCamelCase,	_UpperCamelCase   :						List[str]    =							self.model_tester.prepare_config_and_inputs_for_common()

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

              _UpperCamelCase   :						Union[str, Any]    =							["pixel_values"]
              self.assertListEqual(arg_names[:1]       , __a						)

  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					List[Any]:
        for model_name in ["facebook/maskformer-swin-small-coco"]:
              _UpperCamelCase   :						int    =							MaskFormerModel.from_pretrained(__a						)
              self.assertIsNotNone(__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Union[str, Any]:
        _UpperCamelCase   :						Union[str, Any]    =							(self.model_tester.min_size,) * 2
        _UpperCamelCase   :						List[str]    =							{
            "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(),
        }

        _UpperCamelCase   :						Any    =							MaskFormerForInstanceSegmentation(MaskFormerConfig()						).to(__a						)
        _UpperCamelCase   :						List[Any]    =							model(**__a						)
        self.assertTrue(outputs.loss is not None						)

  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					Optional[Any]:
        _UpperCamelCase,	_UpperCamelCase   :						str    =							self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskformer_model(__a       , **__a       , output_hidden_states=__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					Optional[int]:
        _UpperCamelCase,	_UpperCamelCase   :						List[Any]    =							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Optional[int]    =							model_class(__a						).to(__a						)
              _UpperCamelCase   :						Tuple    =							model(**__a       , output_attentions=__a						)
              self.assertTrue(outputs.attentions is not None						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					Optional[Any]:
        if not self.model_tester.is_training:
              return
        # only MaskFormerForInstanceSegmentation has the loss
        _UpperCamelCase   :						Union[str, Any]    =							self.all_model_classes[1]
        _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						Any    =							self.model_tester.prepare_config_and_inputs()

        _UpperCamelCase   :						Optional[Any]    =							model_class(__a						)
        model.to(__a						)
        model.train()

        _UpperCamelCase   :						List[str]    =							model(__a       , mask_labels=__a       , class_labels=__a						).loss
        loss.backward()


  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					Any:
        # only MaskFormerForInstanceSegmentation has the loss
        _UpperCamelCase   :						Dict    =							self.all_model_classes[1]
        _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						List[str]    =							self.model_tester.prepare_config_and_inputs()
        _UpperCamelCase   :						List[Any]    =							True
        _UpperCamelCase   :						Dict    =							True

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

        _UpperCamelCase   :						Optional[int]    =							model(__a       , mask_labels=__a       , class_labels=__a						)

        _UpperCamelCase   :						Tuple    =							outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        _UpperCamelCase   :						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
        _UpperCamelCase   :						Optional[Any]    =							outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        _UpperCamelCase   :						int    =							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						)





lowerCamelCase__						= 1E-4




def        lowercase__     (       )       ->		List[Any]:




      """simple docstring"""

      _UpperCamelCase   :						Tuple    =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
      return image



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







  '''simple docstring'''


  @cached_property
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					Any:
        return (
            MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco"						)
            if is_vision_available()
            else None
        )

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					Union[str, Any]:
        _UpperCamelCase   :						str    =							MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco"						).to(__a						)
        _UpperCamelCase   :						Optional[int]    =							self.default_image_processor
        _UpperCamelCase   :						Any    =							prepare_img()
        _UpperCamelCase   :						Optional[Any]    =							image_processor(__a       , return_tensors="pt"						).to(__a						)
        _UpperCamelCase   :						List[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():
              _UpperCamelCase   :						Union[str, Any]    =							model(**__a						)

        _UpperCamelCase   :						int    =							torch.tensor(
            [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]]						).to(__a						)
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3]       , __a       , atol=__a						)						)

        _UpperCamelCase   :						str    =							torch.tensor(
            [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]]						).to(__a						)
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]       , __a       , atol=__a						)						)

        _UpperCamelCase   :						Union[str, Any]    =							torch.tensor(
            [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]]						).to(__a						)
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3]       , __a       , atol=__a						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Union[str, Any]						)		->					int:
        _UpperCamelCase   :						List[str]    =							(
            MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"						)
            .to(__a						)
            .eval()
        )
        _UpperCamelCase   :						Dict    =							self.default_image_processor
        _UpperCamelCase   :						int    =							prepare_img()
        _UpperCamelCase   :						Union[str, Any]    =							image_processor(__a       , return_tensors="pt"						).to(__a						)
        _UpperCamelCase   :						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():
              _UpperCamelCase   :						List[Any]    =							model(**__a						)
        # masks_queries_logits
        _UpperCamelCase   :						Any    =							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)       , )
        _UpperCamelCase   :						Tuple    =							[
            [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33],
            [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95],
            [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42],
        ]
        _UpperCamelCase   :						Any    =							torch.tensor(__a						).to(__a						)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       , __a       , atol=__a						)						)
        # class_queries_logits
        _UpperCamelCase   :						Dict    =							outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape       , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)						)
        _UpperCamelCase   :						Any    =							torch.tensor(
            [
                [1.6_5_1_2e0_0, -5.2_5_7_2e0_0, -3.3_5_1_9e0_0],
                [3.6_1_6_9e-0_2, -5.9_0_2_5e0_0, -2.9_3_1_3e0_0],
                [1.0_7_6_6e-0_4, -7.7_6_3_0e0_0, -5.1_2_6_3e0_0],
            ]						).to(__a						)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       , __a       , atol=__a						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							int						)		->					Dict:
        _UpperCamelCase   :						List[str]    =							(
            MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff"						)
            .to(__a						)
            .eval()
        )
        _UpperCamelCase   :						Any    =							self.default_image_processor
        _UpperCamelCase   :						Tuple    =							prepare_img()
        _UpperCamelCase   :						int    =							image_processor(__a       , return_tensors="pt"						).to(__a						)
        _UpperCamelCase   :						Optional[int]    =							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():
              _UpperCamelCase   :						str    =							model(**__a						)
        # masks_queries_logits
        _UpperCamelCase   :						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)       , )
        _UpperCamelCase   :						int    =							[[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]]
        _UpperCamelCase   :						Union[str, Any]    =							torch.tensor(__a						).to(__a						)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       , __a       , atol=__a						)						)
        # class_queries_logits
        _UpperCamelCase   :						List[str]    =							outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape       , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)						)
        _UpperCamelCase   :						List[str]    =							torch.tensor(
            [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]]						).to(__a						)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       , __a       , atol=__a						)						)


  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					Optional[Any]:
        _UpperCamelCase   :						Optional[Any]    =							(
            MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"						)
            .to(__a						)
            .eval()
        )
        _UpperCamelCase   :						int    =							self.default_image_processor

        _UpperCamelCase   :						List[str]    =							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"       , )

        _UpperCamelCase   :						Union[str, Any]    =							inputs["pixel_values"].to(__a						)
        _UpperCamelCase   :						str    =							[el.to(__a						) for el in inputs["mask_labels"]]
        _UpperCamelCase   :						str    =							[el.to(__a						) for el in inputs["class_labels"]]

        with torch.no_grad():
              _UpperCamelCase   :						Union[str, Any]    =							model(**__a						)

        self.assertTrue(outputs.loss is not None						)







"""simple docstring"""


import re




def        lowercase__     (       lowercase_      )       ->		bool:




      """simple docstring"""

      _UpperCamelCase   :						List[Any]    =							re.compile(
          r"^(?:0|94|\+94|0{2}94)" r"7(0|1|2|4|5|6|7|8)" r"(-| |)" r"\d{7}$"      )

      return bool(re.search(lowercase_		,lowercase_      )      )


if __name__ == "__main__":
  lowerCamelCase__						= "0094702343221"

  print(is_sri_lankan_phone_number(phone))
