



'''simple docstring'''

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




	'''simple docstring'''



	def __init__(  self				:	Dict     ,  UpperCamelCase_				:	Optional[int]     ,  UpperCamelCase_				:	Any=13     ,  UpperCamelCase_				:	int=32     ,  UpperCamelCase_				:	List[Any]=3     ,  UpperCamelCase_				:	str=4     ,  UpperCamelCase_				:	Optional[int]=[10, 20, 30, 40]     ,  UpperCamelCase_				:	Optional[Any]=[2, 2, 3, 2]     ,  UpperCamelCase_				:	List[Any]=True     ,  UpperCamelCase_				:	Dict=True     ,  UpperCamelCase_				:	Tuple=37     ,  UpperCamelCase_				:	str="gelu"     ,  UpperCamelCase_				:	List[Any]=10     ,  UpperCamelCase_				:	Dict=0.02     ,  UpperCamelCase_				:	int=["stage2", "stage3", "stage4"]     ,  UpperCamelCase_				:	Union[str, Any]=3     ,  UpperCamelCase_				:	List[str]=None     ,  )  ->       Optional[int]:



		'''simple docstring'''





		_lowercase					:       Union[str, Any]       =		parent
		_lowercase					:       Optional[int]       =		batch_size
		_lowercase					:       List[Any]       =		image_size
		_lowercase					:       Union[str, Any]       =		num_channels
		_lowercase					:       List[Any]       =		num_stages
		_lowercase					:       Optional[int]       =		hidden_sizes
		_lowercase					:       int       =		depths
		_lowercase					:       Optional[int]       =		is_training
		_lowercase					:       Any       =		use_labels
		_lowercase					:       Any       =		intermediate_size
		_lowercase					:       Union[str, Any]       =		hidden_act
		_lowercase					:       Tuple       =		type_sequence_label_size
		_lowercase					:       Union[str, Any]       =		initializer_range
		_lowercase					:       Tuple       =		out_features
		_lowercase					:       Tuple       =		num_labels
		_lowercase					:       Any       =		scope
		_lowercase					:       int       =		num_stages




	def 						__UpperCAmelCase     (  self				:	int					)  ->       str:



		'''simple docstring'''





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

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

		_lowercase					:       List[Any]       =		self.get_config()

		return config, pixel_values, labels




	def 						__UpperCAmelCase     (  self				:	int					)  ->       str:



		'''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				:	List[str]					)  ->       Union[str, Any]:



		'''simple docstring'''





		return UperNetConfig(
		    backbone_config=self.get_backbone_config()     ,  hidden_size=512     ,  pool_scales=[1, 2, 3, 6]     ,  use_auxiliary_head=UpperCamelCase_     ,  auxiliary_loss_weight=0.4     ,  auxiliary_in_channels=40     ,  auxiliary_channels=256     ,  auxiliary_num_convs=1     ,  auxiliary_concat_input=UpperCamelCase_     ,  loss_ignore_index=255     ,  num_labels=self.num_labels     ,  )




	def 						__UpperCAmelCase     (  self				:	Dict     ,  UpperCamelCase_				:	Union[str, Any]     ,  UpperCamelCase_				:	Union[str, Any]     ,  UpperCamelCase_				:	List[str]					)  ->       List[str]:



		'''simple docstring'''





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




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



		'''simple docstring'''





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






@require_torch
class 		lowerCamelCase__      (						A	,   A	,   unittest.TestCase     ):




	'''simple docstring'''



	A_						    =						(UperNetForSemanticSegmentation,) if is_torch_available() else ()
	A_						    =						{"""image-segmentation""": UperNetForSemanticSegmentation} if is_torch_available() else {}
	A_						    =						False
	A_						    =						False
	A_						    =						False
	A_						    =						False
	A_						    =						False
	A_						    =						False




	def 						__UpperCAmelCase     (  self				:	str					)  ->       Any:



		'''simple docstring'''





		_lowercase					:       Tuple       =		UperNetModelTester(self					)
		_lowercase					:       str       =		ConfigTester(self     ,  config_class=UpperCamelCase_     ,  has_text_modality=UpperCamelCase_     ,  hidden_size=37					)




	def 						__UpperCAmelCase     (  self				:	Tuple					)  ->       Optional[int]:



		'''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				:	Tuple					)  ->       Any:



		'''simple docstring'''





		return




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



		'''simple docstring'''





		_lowercase					:       str       =		self.model_tester.prepare_config_and_inputs_for_common()

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

			_lowercase					:       int       =		['pixel_values']
			self.assertListEqual(arg_names[:1]     ,  UpperCamelCase_					)




	def 						__UpperCAmelCase     (  self				:	Dict					)  ->       Dict:



		'''simple docstring'''





		_lowercase					:       Optional[int]       =		self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_					)




	@unittest.skip(reason='UperNet does not use inputs_embeds'					)
	def 						__UpperCAmelCase     (  self				:	List[Any]					)  ->       int:



		'''simple docstring'''





		pass




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



		'''simple docstring'''





		pass




	@unittest.skip(reason='UperNet does not have a base model'					)
	def 						__UpperCAmelCase     (  self				:	Union[str, Any]					)  ->       int:



		'''simple docstring'''





		pass




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



		'''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				:	Any					)  ->       Union[str, Any]:



		'''simple docstring'''





		pass




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



		'''simple docstring'''





		pass




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



		'''simple docstring'''





		def check_hidden_states_output(UpperCamelCase_				:	List[str]     ,  UpperCamelCase_				:	str     ,  UpperCamelCase_				:	Dict					):
			_lowercase					:       Optional[int]       =		model_class(UpperCamelCase_					)
			model.to(UpperCamelCase_					)
			model.eval()

			with torch.no_grad():
				_lowercase					:       str       =		model(**self._prepare_for_class(UpperCamelCase_     ,  UpperCamelCase_					)					)

			_lowercase					:       List[Any]       =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

			_lowercase					:       Tuple       =		self.model_tester.num_stages
			self.assertEqual(len(UpperCamelCase_					)     ,  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					:       List[Any]       =		self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			_lowercase					:       int       =		True
			check_hidden_states_output(UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)

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

			check_hidden_states_output(UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)




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



		'''simple docstring'''





		_lowercase					:       Dict       =		self.model_tester.prepare_config_and_inputs_for_common()

		_lowercase					:       List[str]       =		_config_zero_init(UpperCamelCase_					)
		_lowercase					:       Any       =		_config_zero_init(configs_no_init.backbone_config					)
		for model_class in self.all_model_classes:
			_lowercase					:       str       =		model_class(config=UpperCamelCase_					)
			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				:	Optional[Any]					)  ->       List[Any]:



		'''simple docstring'''





		pass




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



		'''simple docstring'''





		for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			_lowercase					:       Any       =		UperNetForSemanticSegmentation.from_pretrained(UpperCamelCase_					)
			self.assertIsNotNone(UpperCamelCase_					)







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






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




	'''simple docstring'''



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



		'''simple docstring'''





		_lowercase					:       List[Any]       =		AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'					)
		_lowercase					:       List[str]       =		UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'					).to(UpperCamelCase_					)

		_lowercase					:       Optional[Any]       =		prepare_img()
		_lowercase					:       Optional[int]       =		processor(images=UpperCamelCase_     ,  return_tensors='pt'					).to(UpperCamelCase_					)

		with torch.no_grad():
			_lowercase					:       List[str]       =		model(**UpperCamelCase_					)

		_lowercase					:       Dict       =		torch.Size((1, model.config.num_labels, 512, 512)					)
		self.assertEqual(outputs.logits.shape     ,  UpperCamelCase_					)

		_lowercase					:       Optional[Any]       =		torch.tensor(
		    [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]					).to(UpperCamelCase_					)
		self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,  UpperCamelCase_     ,  atol=1E-4					)					)




	def 						__UpperCAmelCase     (  self				:	str					)  ->       int:



		'''simple docstring'''





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

		_lowercase					:       Tuple       =		prepare_img()
		_lowercase					:       List[Any]       =		processor(images=UpperCamelCase_     ,  return_tensors='pt'					).to(UpperCamelCase_					)

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

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

		_lowercase					:       int       =		torch.tensor(
		    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]					).to(UpperCamelCase_					)
		self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]     ,  UpperCamelCase_     ,  atol=1E-4					)					)





'''simple docstring'''

def 						__UpperCamelCase				(							_lowercase,				_lowercase					) ->			list:
	_lowercase					:       List[str]       =		word.split()

	def justify(_lowercase,				_lowercase,				_lowercase					) -> str:
		_lowercase					:       Dict       =		max_width - width
		_lowercase					:       Tuple       =		len(_lowercase					)
		if len(_lowercase					) == 1:
			# if there is only word in line
			# just insert overall_spaces_count for the remainder of line
			return line[0] + " " * overall_spaces_count
		else:
			_lowercase					:       Tuple       =		words_count - 1
			# num_spaces_between_words_list[i] : tells you to insert
			# num_spaces_between_words_list[i] spaces
			# after word on line[i]
			_lowercase					:       str       =		spaces_to_insert_between_words * [
			    overall_spaces_count // spaces_to_insert_between_words
			]
			_lowercase					:       Optional[int]       =		(
			    overall_spaces_count % spaces_to_insert_between_words
			)
			# distribute spaces via round robin to the left words
			for i in range(_lowercase					):
				num_spaces_between_words_list[i] += 1
			_lowercase					:       Union[str, Any]       =		[]
			for i in range(_lowercase					):
				# add the word
				aligned_words_list.append(line[i]					)
				# add the spaces to insert
				aligned_words_list.append(num_spaces_between_words_list[i] * ' '					)
			# just add the last word to the sentence
			aligned_words_list.append(line[-1]					)
			# join the aligned words list to form a justified line
			return "".join(_lowercase					)

	_lowercase					:       str       =		[]
	_lowercase					:       list[str]       =		[]
	_lowercase					:       Union[str, Any]       =		0
	for word in words:
		if width + len(_lowercase					) + len(_lowercase					) <= max_width:
			# keep adding words until we can fill out max_width
			# width = sum of length of all words (without overall_spaces_count)
			# len(word) = length of current word
			# len(line) = number of overall_spaces_count to insert between words
			line.append(_lowercase					)
			width += len(_lowercase					)
		else:
			# justify the line and add it to result
			answer.append(justify(_lowercase,				_lowercase,				_lowercase					)					)
			# reset new line and new width
			_lowercase  ,    _lowercase					:       Optional[Any]       =		[word], len(_lowercase					)
	_lowercase					:       Optional[int]       =		max_width - width - len(_lowercase					)
	answer.append(' '.join(_lowercase					) + (remaining_spaces + 1) * ' '					)
	return answer


if __name__ == "__main__":
		from doctest import testmod

		testmod()
