
"""simple docstring"""




import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


lowerCAmelCase__							=				'hf-internal-testing/tiny-random-bert'
lowerCAmelCase__							=				os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
lowerCAmelCase__							=				'9b8c223d42b2188cb49d29af482996f9d0f3e5a6'





class  snake_case     (							unittest.TestCase   ):

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )
									# Should have downloaded the file in here
									self.assertTrue(os.path.isdir(SCREAMING_SNAKE_CASE_    )    )
									# Cache should contain at least those three subfolders:
									for subfolder in ["blobs", "refs", "snapshots"]:
											self.assertTrue(os.path.isdir(os.path.join(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )    )    )
									with open(os.path.join(SCREAMING_SNAKE_CASE_       ,       '''refs'''       ,       '''main'''    )    ) as f:
											SCREAMING_SNAKE_CASE_						 = f.read()
									self.assertEqual(SCREAMING_SNAKE_CASE_       ,       os.path.join(SCREAMING_SNAKE_CASE_       ,       '''snapshots'''       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )    )
									self.assertTrue(os.path.isfile(SCREAMING_SNAKE_CASE_    )    )

									# File is cached at the same place the second time.
									SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )
									self.assertEqual(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )

									# Using a specific revision to test the full commit hash.
									SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       revision='''9b8c223'''    )
									self.assertEqual(SCREAMING_SNAKE_CASE_       ,       os.path.join(SCREAMING_SNAKE_CASE_       ,       '''snapshots'''       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    )    )

							def _lowercase					(self    ):

									"""simple docstring"""







									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''is not a valid model identifier'''    ):
											SCREAMING_SNAKE_CASE_						 = cached_file('''tiny-random-bert'''       ,       SCREAMING_SNAKE_CASE_    )

									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''is not a valid git identifier'''    ):
											SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       revision='''aaaa'''    )

									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''does not appear to have a file named'''    ):
											SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       '''conf'''    )

							def _lowercase					(self    ):

									"""simple docstring"""







									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''does not appear to have a file named'''    ):
											SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       '''conf'''    )

									with open(os.path.join(SCREAMING_SNAKE_CASE_       ,       '''refs'''       ,       '''main'''    )    ) as f:
											SCREAMING_SNAKE_CASE_						 = f.read()
									self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE_       ,       '''.no_exist'''       ,       SCREAMING_SNAKE_CASE_       ,       '''conf'''    )    )    )

									SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       '''conf'''       ,       _raise_exceptions_for_missing_entries=SCREAMING_SNAKE_CASE_    )
									self.assertIsNone(SCREAMING_SNAKE_CASE_    )

									SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       '''conf'''       ,       local_files_only=SCREAMING_SNAKE_CASE_       ,       _raise_exceptions_for_missing_entries=SCREAMING_SNAKE_CASE_    )
									self.assertIsNone(SCREAMING_SNAKE_CASE_    )

									SCREAMING_SNAKE_CASE_						 = mock.Mock()
									SCREAMING_SNAKE_CASE_						 = 5_00
									SCREAMING_SNAKE_CASE_						 = {}
									SCREAMING_SNAKE_CASE_						 = HTTPError
									SCREAMING_SNAKE_CASE_						 = {}

									# Under the mock environment we get a 500 error when trying to reach the tokenizer.
									with mock.patch('''requests.Session.request'''       ,       return_value=SCREAMING_SNAKE_CASE_    ) as mock_head:
											SCREAMING_SNAKE_CASE_						 = cached_file(SCREAMING_SNAKE_CASE_       ,       '''conf'''       ,       _raise_exceptions_for_connection_errors=SCREAMING_SNAKE_CASE_    )
											self.assertIsNone(SCREAMING_SNAKE_CASE_    )
											# This check we did call the fake head request
											mock_head.assert_called()

							def _lowercase					(self    ):

									"""simple docstring"""







									self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only'''       ,       SCREAMING_SNAKE_CASE_    )    )
									self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''       ,       SCREAMING_SNAKE_CASE_    )    )
									self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only'''       ,       SCREAMING_SNAKE_CASE_    )    )

							def _lowercase					(self    ):

									"""simple docstring"""







									self.assertIsNone(get_file_from_repo('''bert-base-cased'''       ,       '''ahah.txt'''    )    )

									# The function raises if the repository does not exist.
									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''is not a valid model identifier'''    ):
											get_file_from_repo('''bert-base-case'''       ,       SCREAMING_SNAKE_CASE_    )

									# The function raises if the revision does not exist.
									with self.assertRaisesRegex(SCREAMING_SNAKE_CASE_       ,       '''is not a valid git identifier'''    ):
											get_file_from_repo('''bert-base-cased'''       ,       SCREAMING_SNAKE_CASE_       ,       revision='''ahaha'''    )

									SCREAMING_SNAKE_CASE_						 = get_file_from_repo('''bert-base-cased'''       ,       SCREAMING_SNAKE_CASE_    )
									# The name is the cached name which is not very easy to test, so instead we load the content.
									SCREAMING_SNAKE_CASE_						 = json.loads(open(SCREAMING_SNAKE_CASE_       ,       '''r'''    ).read()    )
									self.assertEqual(config['''hidden_size''']       ,       7_68    )







							def _lowercase					(self    ):

									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmp_dir:
											SCREAMING_SNAKE_CASE_						 = Path(SCREAMING_SNAKE_CASE_    ) / '''a.txt'''
											filename.touch()
											self.assertEqual(get_file_from_repo(SCREAMING_SNAKE_CASE_       ,       '''a.txt'''    )       ,       str(SCREAMING_SNAKE_CASE_    )    )

											self.assertIsNone(get_file_from_repo(SCREAMING_SNAKE_CASE_       ,       '''b.txt'''    )    )

"""simple docstring"""




import copy
from typing import Dict, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
from ..detr import DetrConfig
from ..swin import SwinConfig


lowerCAmelCase__							=				{
    'facebook/maskformer-swin-base-ade': (
        'https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json'
    )
    # See all MaskFormer models at https://huggingface.co/models?filter=maskformer
}

lowerCAmelCase__							=				logging.get_logger(__name__)





class  snake_case     (							__lowercase   ):
							UpperCAmelCase__						     =      '''maskformer'''
							UpperCAmelCase__						     =      {'''hidden_size''': '''mask_feature_size'''}
							UpperCAmelCase__						     =      ['''resnet''', '''swin''']
							UpperCAmelCase__						     =      ['''detr''']

							def __init__(self       ,       SCREAMING_SNAKE_CASE_ = 2_56       ,       SCREAMING_SNAKE_CASE_ = 2_56       ,       SCREAMING_SNAKE_CASE_ = 0.1       ,       SCREAMING_SNAKE_CASE_ = False       ,       SCREAMING_SNAKE_CASE_ = None       ,       SCREAMING_SNAKE_CASE_ = None       ,       SCREAMING_SNAKE_CASE_ = 0.02       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 1.0       ,       SCREAMING_SNAKE_CASE_ = 20.0       ,       SCREAMING_SNAKE_CASE_ = None       ,       **SCREAMING_SNAKE_CASE_       ,       ):

									"""simple docstring"""







									if backbone_config is None:
											# fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k
											SCREAMING_SNAKE_CASE_						 = SwinConfig(
											    image_size=3_84       ,       in_channels=3       ,       patch_size=4       ,       embed_dim=1_28       ,       depths=[2, 2, 18, 2]       ,       num_heads=[4, 8, 16, 32]       ,       window_size=12       ,       drop_path_rate=0.3       ,       out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4''']       ,       )

									if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):
											SCREAMING_SNAKE_CASE_						 = backbone_config.pop('''model_type'''    )
											SCREAMING_SNAKE_CASE_						 = CONFIG_MAPPING[backbone_model_type]
											SCREAMING_SNAKE_CASE_						 = config_class.from_dict(SCREAMING_SNAKE_CASE_    )

									# verify that the backbone is supported
									if backbone_config.model_type not in self.backbones_supported:
											logger.warning_once(
											    f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. '
											    f'Supported model types: {",".join(self.backbones_supported    )}'    )

									if decoder_config is None:
											# fall back to https://huggingface.co/facebook/detr-resnet-50
											SCREAMING_SNAKE_CASE_						 = DetrConfig()
									else:
											# verify that the decoder is supported
											SCREAMING_SNAKE_CASE_						 = (
											    decoder_config.pop('''model_type'''    ) if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ) else decoder_config.model_type
											)
											if decoder_type not in self.decoders_supported:
													raise ValueError(
													    f'Transformer Decoder {decoder_type} not supported, please use one of'
													    f' {",".join(self.decoders_supported    )}'    )
											if isinstance(SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_    ):
													SCREAMING_SNAKE_CASE_						 = CONFIG_MAPPING[decoder_type]
													SCREAMING_SNAKE_CASE_						 = config_class.from_dict(SCREAMING_SNAKE_CASE_    )

									SCREAMING_SNAKE_CASE_						 = backbone_config
									SCREAMING_SNAKE_CASE_						 = decoder_config
									# main feature dimension for the model
									SCREAMING_SNAKE_CASE_						 = fpn_feature_size
									SCREAMING_SNAKE_CASE_						 = mask_feature_size
									# initializer
									SCREAMING_SNAKE_CASE_						 = init_std
									SCREAMING_SNAKE_CASE_						 = init_xavier_std
									# Hungarian matcher && loss
									SCREAMING_SNAKE_CASE_						 = cross_entropy_weight
									SCREAMING_SNAKE_CASE_						 = dice_weight
									SCREAMING_SNAKE_CASE_						 = mask_weight
									SCREAMING_SNAKE_CASE_						 = use_auxiliary_loss
									SCREAMING_SNAKE_CASE_						 = no_object_weight
									SCREAMING_SNAKE_CASE_						 = output_auxiliary_logits

									SCREAMING_SNAKE_CASE_						 = self.decoder_config.encoder_attention_heads
									SCREAMING_SNAKE_CASE_						 = self.decoder_config.num_hidden_layers
									super().__init__(**SCREAMING_SNAKE_CASE_    )

							@classmethod
							def _lowercase					(cls       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_    ):

									"""simple docstring"""







									return cls(
									    backbone_config=SCREAMING_SNAKE_CASE_       ,       decoder_config=SCREAMING_SNAKE_CASE_       ,       **SCREAMING_SNAKE_CASE_       ,       )







							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = copy.deepcopy(self.__dict__    )
									SCREAMING_SNAKE_CASE_						 = self.backbone_config.to_dict()
									SCREAMING_SNAKE_CASE_						 = self.decoder_config.to_dict()
									SCREAMING_SNAKE_CASE_						 = self.__class__.model_type
									return output