


import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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


if is_torch_available():
 import torch

 from transformers import UperNetForSemanticSegmentation
 from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=13,   lowerCamelCase=32,   lowerCamelCase=3,   lowerCamelCase=4,   lowerCamelCase=[10, 20, 30, 40],   lowerCamelCase=[2, 2, 3, 2],   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=37,   lowerCamelCase="gelu",   lowerCamelCase=10,   lowerCamelCase=0.0_2,   lowerCamelCase=["stage2", "stage3", "stage4"],   lowerCamelCase=3,   lowerCamelCase=None,   ) ->     str:




           """simple docstring"""

           _lowercase :							List[str]   	=	parent
           _lowercase :							List[str]   	=	batch_size
           _lowercase :							List[str]   	=	image_size
           _lowercase :							int   	=	num_channels
           _lowercase :							Tuple   	=	num_stages
           _lowercase :							Tuple   	=	hidden_sizes
           _lowercase :							Optional[int]   	=	depths
           _lowercase :							int   	=	is_training
           _lowercase :							Dict   	=	use_labels
           _lowercase :							Tuple   	=	intermediate_size
           _lowercase :							str   	=	hidden_act
           _lowercase :							Optional[Any]   	=	type_sequence_label_size
           _lowercase :							Dict   	=	initializer_range
           _lowercase :							Union[str, Any]   	=	out_features
           _lowercase :							Union[str, Any]   	=	num_labels
           _lowercase :							str   	=	scope
           _lowercase :							str   	=	num_stages
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           _lowercase :							List[Any]   	=	None
           if self.use_labels:
               _lowercase :							Union[str, Any]   	=	ids_tensor([self.batch_size],   self.type_sequence_label_size)

           _lowercase :							Optional[int]   	=	self.get_config()

           return config, pixel_values, labels
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           return ConvNextConfig(
               num_channels=self.num_channels,   num_stages=self.num_stages,   hidden_sizes=self.hidden_sizes,   depths=self.depths,   is_training=self.is_training,   intermediate_size=self.intermediate_size,   hidden_act=self.hidden_act,   out_features=self.out_features,   )
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           return UperNetConfig(
               backbone_config=self.get_backbone_config(),   hidden_size=5_12,   pool_scales=[1, 2, 3, 6],   use_auxiliary_head=lowerCamelCase,   auxiliary_loss_weight=0.4,   auxiliary_in_channels=40,   auxiliary_channels=2_56,   auxiliary_num_convs=1,   auxiliary_concat_input=lowerCamelCase,   loss_ignore_index=2_55,   num_labels=self.num_labels,   )
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							Dict   	=	UperNetForSemanticSegmentation(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[Any]   	=	model(lowerCamelCase)
           self.parent.assertEqual(
               result.logits.shape,   (self.batch_size, self.num_labels, self.image_size, self.image_size))




       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							Optional[int]   	=	config_and_inputs
           _lowercase :							int   	=	{'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,				_a,				unittest.TestCase     ):
       lowercase_				:			str									=    (UperNetForSemanticSegmentation,) if is_torch_available() else ()
       lowercase_				:			Dict									=    {"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
       lowercase_				:			Tuple									=    False
       lowercase_				:			Tuple									=    False
       lowercase_				:			List[str]									=    False
       lowercase_				:			Dict									=    False
       lowercase_				:			str									=    False
       lowercase_				:			Dict									=    False
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	UperNetModelTester(self)
           _lowercase :							int   	=	ConfigTester(self,   config_class=lowerCamelCase,   has_text_modality=lowerCamelCase,   hidden_size=37)
       def     UpperCamelCase  (      self) ->     Dict:




           """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     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           return
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           _lowercase	,       _lowercase :							List[Any]   	=	self.model_tester.prepare_config_and_inputs_for_common()

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

               _lowercase :							int   	=	['pixel_values']
               self.assertListEqual(arg_names[:1],   lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase)
       @unittest.skip(reason='UperNet does not use inputs_embeds')
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           pass
       @unittest.skip(reason='UperNet does not support input and output embeddings')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           pass
       @unittest.skip(reason='UperNet does not have a base model')
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           pass
       @unittest.skip(reason='UperNet does not have a base model')
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           pass
       @require_torch_multi_gpu
       @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`')
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           pass
       @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           pass
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           def check_hidden_states_output(lowerCamelCase,   lowerCamelCase,   lowerCamelCase):
               _lowercase :							List[str]   	=	model_class(lowerCamelCase)
               model.to(lowerCamelCase)
               model.eval()

               with torch.no_grad():
                   _lowercase :							List[str]   	=	model(**self._prepare_for_class(lowerCamelCase,   lowerCamelCase))

               _lowercase :							Dict   	=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               _lowercase :							Tuple   	=	self.model_tester.num_stages
               self.assertEqual(len(lowerCamelCase),   expected_num_stages + 1)

               # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]),   [self.model_tester.image_size // 4, self.model_tester.image_size // 4],   )

           _lowercase	,       _lowercase :							Dict   	=	self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               _lowercase :							List[Any]   	=	True
               check_hidden_states_output(lowerCamelCase,   lowerCamelCase,   lowerCamelCase)

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

               check_hidden_states_output(lowerCamelCase,   lowerCamelCase,   lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase	,       _lowercase :							List[str]   	=	self.model_tester.prepare_config_and_inputs_for_common()

           _lowercase :							List[str]   	=	_config_zero_init(lowerCamelCase)
           _lowercase :							Optional[Any]   	=	_config_zero_init(configs_no_init.backbone_config)
           for model_class in self.all_model_classes:
               _lowercase :							str   	=	model_class(config=lowerCamelCase)
               for name, param in model.named_parameters():
                   if param.requires_grad:
                       self.assertIn(
                           ((param.data.mean() * 1E9).round() / 1E9).item(),   [0.0, 1.0],   msg=F'''Parameter {name} of model {model_class} seems not properly initialized''',   )
       @unittest.skip(reason='UperNet does not have tied weights')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           pass




       @slow
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase :							Union[str, Any]   	=	UperNetForSemanticSegmentation.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)



def        UpperCamelCase_(   )					->		Any:
    _lowercase :							Optional[int]   	=	hf_hub_download(
        repo_id='hf-internal-testing/fixtures_ade20k'							,				repo_type='dataset'							,				filename='ADE_val_00000001.jpg'				)
    _lowercase :							List[Any]   	=	Image.open(lowerCamelCase_				).convert('RGB'				)
    return image






@require_torch
@require_vision
@slow
class _lowerCamelCase(		unittest.TestCase     ):
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny')
           _lowercase :							Union[str, Any]   	=	UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny').to(lowerCamelCase)

           _lowercase :							Dict   	=	prepare_img()
           _lowercase :							int   	=	processor(images=lowerCamelCase,   return_tensors='pt').to(lowerCamelCase)

           with torch.no_grad():
               _lowercase :							Optional[int]   	=	model(**lowerCamelCase)

           _lowercase :							int   	=	torch.Size((1, model.config.num_labels, 5_12, 5_12))
           self.assertEqual(outputs.logits.shape,   lowerCamelCase)

           _lowercase :							List[Any]   	=	torch.tensor(
               [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]]).to(lowerCamelCase)
           self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],   lowerCamelCase,   atol=1E-4))




       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny')
           _lowercase :							Union[str, Any]   	=	UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny').to(lowerCamelCase)

           _lowercase :							str   	=	prepare_img()
           _lowercase :							str   	=	processor(images=lowerCamelCase,   return_tensors='pt').to(lowerCamelCase)

           with torch.no_grad():
               _lowercase :							Optional[int]   	=	model(**lowerCamelCase)

           _lowercase :							Optional[Any]   	=	torch.Size((1, model.config.num_labels, 5_12, 5_12))
           self.assertEqual(outputs.logits.shape,   lowerCamelCase)

           _lowercase :							int   	=	torch.tensor(
               [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]]).to(lowerCamelCase)
           self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],   lowerCamelCase,   atol=1E-4))






from __future__ import annotations

import requests



def        UpperCamelCase_(   lowerCamelCase_				)					->		dict:
    _lowercase :							Dict   	=	F'''https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'''
    return requests.get(lowerCamelCase_				).json()



def        UpperCamelCase_(   lowerCamelCase_ = 10				)					->		list[dict]:
    _lowercase :							Dict   	=	'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'
    _lowercase :							Dict   	=	requests.get(lowerCamelCase_				).json()[:max_stories]
    return [get_hackernews_story(lowerCamelCase_				) for story_id in story_ids]



def        UpperCamelCase_(   lowerCamelCase_ = 10				)					->		str:
    _lowercase :							Optional[int]   	=	hackernews_top_stories(lowerCamelCase_				)
    return "\n".join('* [{title}]({url})'.format(**lowerCamelCase_				) for story in stories				)


if __name__ == "__main__":
 print(hackernews_top_stories_as_markdown())


