


import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 torch import nn

	from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
	from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import DPTImageProcessor






class     UpperCamelCase:


					def __init__(						self	:		Dict     ,    SCREAMING_SNAKE_CASE	:		Tuple     ,    SCREAMING_SNAKE_CASE	:		List[str]=2     ,    SCREAMING_SNAKE_CASE	:		Optional[int]=3_2     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]=1_6     ,    SCREAMING_SNAKE_CASE	:		str=3     ,    SCREAMING_SNAKE_CASE	:		str=True     ,    SCREAMING_SNAKE_CASE	:		List[str]=True     ,    SCREAMING_SNAKE_CASE	:		List[str]=3_2     ,    SCREAMING_SNAKE_CASE	:		Dict=4     ,    SCREAMING_SNAKE_CASE	:		List[str]=[0, 1, 2, 3]     ,    SCREAMING_SNAKE_CASE	:		List[str]=4     ,    SCREAMING_SNAKE_CASE	:		List[Any]=3_7     ,    SCREAMING_SNAKE_CASE	:		Dict="gelu"     ,    SCREAMING_SNAKE_CASE	:		int=0.1     ,    SCREAMING_SNAKE_CASE	:		Union[str, Any]=0.1     ,    SCREAMING_SNAKE_CASE	:		List[Any]=0.02     ,    SCREAMING_SNAKE_CASE	:		int=3     ,    SCREAMING_SNAKE_CASE	:		Dict=[1, 3_8_4, 2_4, 2_4]     ,    SCREAMING_SNAKE_CASE	:		Union[str, Any]=True     ,    SCREAMING_SNAKE_CASE	:		Any=None     ,    )			->	Any:




											'''simple docstring'''

											__snake_case				=		parent
											__snake_case				=		batch_size
											__snake_case				=		image_size
											__snake_case				=		patch_size
											__snake_case				=		num_channels
											__snake_case				=		is_training
											__snake_case				=		use_labels
											__snake_case				=		hidden_size
											__snake_case				=		num_hidden_layers
											__snake_case				=		backbone_out_indices
											__snake_case				=		num_attention_heads
											__snake_case				=		intermediate_size
											__snake_case				=		hidden_act
											__snake_case				=		hidden_dropout_prob
											__snake_case				=		attention_probs_dropout_prob
											__snake_case				=		initializer_range
											__snake_case				=		num_labels
											__snake_case				=		backbone_featmap_shape
											__snake_case				=		scope
											__snake_case				=		is_hybrid
											# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
											__snake_case				=		(image_size // patch_size) ** 2
											__snake_case				=		num_patches + 1


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




											'''simple docstring'''

											__snake_case				=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

											__snake_case				=		None
											if self.use_labels:
																	__snake_case				=		ids_tensor([self.batch_size, self.image_size, self.image_size]     ,    self.num_labels						)

											__snake_case				=		self.get_config()

											return config, pixel_values, labels


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




											'''simple docstring'''

											__snake_case				=		{
											    "global_padding": "same",
											    "layer_type": "bottleneck",
											    "depths": [3, 4, 9],
											    "out_features": ["stage1", "stage2", "stage3"],
											    "embedding_dynamic_padding": True,
											    "hidden_sizes": [9_6, 1_9_2, 3_8_4, 7_6_8],
											    "num_groups": 2,
											}

											return DPTConfig(
											    image_size=self.image_size     ,    patch_size=self.patch_size     ,    num_channels=self.num_channels     ,    hidden_size=self.hidden_size     ,    num_hidden_layers=self.num_hidden_layers     ,    backbone_out_indices=self.backbone_out_indices     ,    num_attention_heads=self.num_attention_heads     ,    intermediate_size=self.intermediate_size     ,    hidden_act=self.hidden_act     ,    hidden_dropout_prob=self.hidden_dropout_prob     ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,    is_decoder=SCREAMING_SNAKE_CASE     ,    initializer_range=self.initializer_range     ,    is_hybrid=self.is_hybrid     ,    backbone_config=SCREAMING_SNAKE_CASE     ,    backbone_featmap_shape=self.backbone_featmap_shape     ,    )


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		Dict     ,    SCREAMING_SNAKE_CASE	:		Optional[int]     ,    SCREAMING_SNAKE_CASE	:		Optional[int]						)			->	Union[str, Any]:




											'''simple docstring'''

											__snake_case				=		DPTModel(config=SCREAMING_SNAKE_CASE						)
											model.to(SCREAMING_SNAKE_CASE						)
											model.eval()
											__snake_case				=		model(SCREAMING_SNAKE_CASE						)
											self.parent.assertEqual(result.last_hidden_state.shape     ,    (self.batch_size, self.seq_length, self.hidden_size)						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		int     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		List[Any]     ,    SCREAMING_SNAKE_CASE	:		Optional[Any]						)			->	Tuple:




											'''simple docstring'''

											__snake_case				=		self.num_labels
											__snake_case				=		DPTForDepthEstimation(SCREAMING_SNAKE_CASE						)
											model.to(SCREAMING_SNAKE_CASE						)
											model.eval()
											__snake_case				=		model(SCREAMING_SNAKE_CASE						)
											self.parent.assertEqual(result.predicted_depth.shape     ,    (self.batch_size, self.image_size, self.image_size)						)


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




											'''simple docstring'''

											__snake_case				=		self.num_labels
											__snake_case				=		DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE						)
											model.to(SCREAMING_SNAKE_CASE						)
											model.eval()
											__snake_case				=		model(SCREAMING_SNAKE_CASE     ,    labels=SCREAMING_SNAKE_CASE						)
											self.parent.assertEqual(
											    result.logits.shape     ,    (self.batch_size, self.num_labels, self.image_size, self.image_size)						)






					def 							SCREAMING_SNAKE_CASE_  (						self	:		str						)			->	Optional[int]:




											'''simple docstring'''

											__snake_case				=		self.prepare_config_and_inputs()
											__snake_case		,					__snake_case		,					__snake_case				=		config_and_inputs
											__snake_case				=		{"pixel_values": pixel_values}
											return config, inputs_dict






@require_torch
class     UpperCamelCase(  _a     ,							_a     ,							unittest.TestCase   ):
					snake_case_		:				List[str]										=	(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
					snake_case_		:				Optional[Any]										=	(
					    {
					        """depth-estimation""": DPTForDepthEstimation,
					        """feature-extraction""": DPTModel,
					        """image-segmentation""": DPTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					snake_case_		:				List[Any]										=	False
					snake_case_		:				Optional[int]										=	False
					snake_case_		:				Optional[Any]										=	False


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




											'''simple docstring'''

											__snake_case				=		DPTModelTester(self						)
											__snake_case				=		ConfigTester(self     ,    config_class=SCREAMING_SNAKE_CASE     ,    has_text_modality=SCREAMING_SNAKE_CASE     ,    hidden_size=3_7						)


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




											'''simple docstring'''

											self.config_tester.run_common_tests()


					@unittest.skip(reason="DPT does not use inputs_embeds"						)
					def 							SCREAMING_SNAKE_CASE_  (						self	:		int						)			->	str:




											'''simple docstring'''

											pass


					def 							SCREAMING_SNAKE_CASE_  (						self	:		int						)			->	Any:




											'''simple docstring'''

											__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__snake_case				=		model_class(SCREAMING_SNAKE_CASE						)
																	self.assertIsInstance(model.get_input_embeddings()     ,    (nn.Module)						)
																	__snake_case				=		model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE     ,    nn.Linear						)						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[str]						)			->	str:




											'''simple docstring'''

											__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	__snake_case				=		["pixel_values"]
																	self.assertListEqual(arg_names[:1]     ,    SCREAMING_SNAKE_CASE						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Dict						)			->	Tuple:




											'''simple docstring'''

											__snake_case				=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[Any]						)			->	Dict:




											'''simple docstring'''

											__snake_case				=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Tuple						)			->	Any:




											'''simple docstring'''

											__snake_case				=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE						)


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Any						)			->	Any:




											'''simple docstring'''

											for model_class in self.all_model_classes:
																	if model_class.__name__ == "DPTForDepthEstimation":
																							continue

																	__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()
																	__snake_case				=		True

																	if model_class in get_values(SCREAMING_SNAKE_CASE						):
																							continue

																	__snake_case				=		model_class(SCREAMING_SNAKE_CASE						)
																	model.to(SCREAMING_SNAKE_CASE						)
																	model.train()
																	__snake_case				=		self._prepare_for_class(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    return_labels=SCREAMING_SNAKE_CASE						)
																	__snake_case				=		model(**SCREAMING_SNAKE_CASE						).loss
																	loss.backward()


					def 							SCREAMING_SNAKE_CASE_  (						self	:		Any						)			->	Optional[Any]:




											'''simple docstring'''

											for model_class in self.all_model_classes:
																	if model_class.__name__ == "DPTForDepthEstimation":
																							continue

																	__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()
																	__snake_case				=		False
																	__snake_case				=		True

																	if model_class in get_values(SCREAMING_SNAKE_CASE						) or not model_class.supports_gradient_checkpointing:
																							continue
																	__snake_case				=		model_class(SCREAMING_SNAKE_CASE						)
																	model.to(SCREAMING_SNAKE_CASE						)
																	model.gradient_checkpointing_enable()
																	model.train()
																	__snake_case				=		self._prepare_for_class(SCREAMING_SNAKE_CASE     ,    SCREAMING_SNAKE_CASE     ,    return_labels=SCREAMING_SNAKE_CASE						)
																	__snake_case				=		model(**SCREAMING_SNAKE_CASE						).loss
																	loss.backward()


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




											'''simple docstring'''

											__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()

											__snake_case				=		_config_zero_init(SCREAMING_SNAKE_CASE						)
											for model_class in self.all_model_classes:
																	__snake_case				=		model_class(config=SCREAMING_SNAKE_CASE						)
																	# Skip the check for the backbone
																	__snake_case				=		[]
																	for name, module in model.named_modules():
																							if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																													__snake_case				=		[f'''{name}.{key}''' for key in module.state_dict().keys()]
																													break

																	for name, param in model.named_parameters():
																							if param.requires_grad:
																													if name in backbone_params:
																																			continue
																													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("Will be fixed soon by reducing the size of the model used for common tests."						)
					def 							SCREAMING_SNAKE_CASE_  (						self	:		Optional[int]						)			->	Dict:




											'''simple docstring'''

											pass


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




											'''simple docstring'''

											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																	__snake_case				=		DPTModel.from_pretrained(SCREAMING_SNAKE_CASE						)
																	self.assertIsNotNone(SCREAMING_SNAKE_CASE						)






					def 							SCREAMING_SNAKE_CASE_  (						self	:		List[str]						)			->	Any:




											'''simple docstring'''

											__snake_case		,					__snake_case				=		self.model_tester.prepare_config_and_inputs_for_common()
											__snake_case				=		"add"
											with self.assertRaises(SCREAMING_SNAKE_CASE						):
																	__snake_case				=		DPTForDepthEstimation(SCREAMING_SNAKE_CASE						)





def 	_lowerCAmelCase       (    )						->	Union[str, Any]:


						'''simple docstring'''






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






@require_torch
@require_vision
@slow
class     UpperCamelCase(  unittest.TestCase   ):


					def 							SCREAMING_SNAKE_CASE_  (						self	:		str						)			->	str:




											'''simple docstring'''

											__snake_case				=		DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"						)
											__snake_case				=		DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"						).to(SCREAMING_SNAKE_CASE						)

											__snake_case				=		prepare_img()
											__snake_case				=		image_processor(images=SCREAMING_SNAKE_CASE     ,    return_tensors="pt"						).to(SCREAMING_SNAKE_CASE						)

											# forward pass
											with torch.no_grad():
																	__snake_case				=		model(**SCREAMING_SNAKE_CASE						)
																	__snake_case				=		outputs.predicted_depth

											# verify the predicted depth
											__snake_case				=		torch.Size((1, 3_8_4, 3_8_4)						)
											self.assertEqual(predicted_depth.shape     ,    SCREAMING_SNAKE_CASE						)

											__snake_case				=		torch.tensor(
											    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]						).to(SCREAMING_SNAKE_CASE						)

											self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0     ,    SCREAMING_SNAKE_CASE     ,    atol=1e-4						)						)









from __future__ import annotations

import csv

import requests
from bsa import BeautifulSoup





def 	_lowerCAmelCase       (    _lowerCAmelCase = "" )						->	dict[str, float]:


						'''simple docstring'''






						__snake_case				=		url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250"
						__snake_case				=		BeautifulSoup(requests.get(_lowerCAmelCase ).text      ,	"html.parser" )
						__snake_case				=		soup.find_all("td"      ,	attrs="titleColumn" )
						__snake_case				=		soup.find_all("td"      ,	class_="ratingColumn imdbRating" )
						return {
						    title.a.text: float(rating.strong.text )
						    for title, rating in zip(_lowerCAmelCase      ,	_lowerCAmelCase )
						}





def 	_lowerCAmelCase       (    _lowerCAmelCase = "IMDb_Top_250_Movies.csv" )						->	None:


						'''simple docstring'''






						__snake_case				=		get_imdb_top_aaa_movies()
						with open(_lowerCAmelCase      ,	"w"      ,	newline="" ) as out_file:
												__snake_case				=		csv.writer(_lowerCAmelCase )
												writer.writerow(["Movie title", "IMDb rating"] )
												for title, rating in movies.items():
																		writer.writerow([title, rating] )


if __name__ == "__main__":
	write_movies()





