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





	def __init__(		self	: Tuple    ,__SCREAMING_SNAKE_CASE	: Tuple    ,__SCREAMING_SNAKE_CASE	: Optional[Any]=1_3    ,__SCREAMING_SNAKE_CASE	: Dict=3_2    ,__SCREAMING_SNAKE_CASE	: List[Any]=3    ,__SCREAMING_SNAKE_CASE	: List[Any]=4    ,__SCREAMING_SNAKE_CASE	: List[Any]=[1_0, 2_0, 3_0, 4_0]    ,__SCREAMING_SNAKE_CASE	: List[Any]=[2, 2, 3, 2]    ,__SCREAMING_SNAKE_CASE	: Optional[int]=True    ,__SCREAMING_SNAKE_CASE	: Any=True    ,__SCREAMING_SNAKE_CASE	: Dict=3_7    ,__SCREAMING_SNAKE_CASE	: int="gelu"    ,__SCREAMING_SNAKE_CASE	: int=1_0    ,__SCREAMING_SNAKE_CASE	: List[str]=0.02    ,__SCREAMING_SNAKE_CASE	: Tuple=["stage2", "stage3", "stage4"]    ,__SCREAMING_SNAKE_CASE	: List[str]=3    ,__SCREAMING_SNAKE_CASE	: List[Any]=None    ,):
						UpperCAmelCase				   =  parent
						UpperCAmelCase				   =  batch_size
						UpperCAmelCase				   =  image_size
						UpperCAmelCase				   =  num_channels
						UpperCAmelCase				   =  num_stages
						UpperCAmelCase				   =  hidden_sizes
						UpperCAmelCase				   =  depths
						UpperCAmelCase				   =  is_training
						UpperCAmelCase				   =  use_labels
						UpperCAmelCase				   =  intermediate_size
						UpperCAmelCase				   =  hidden_act
						UpperCAmelCase				   =  type_sequence_label_size
						UpperCAmelCase				   =  initializer_range
						UpperCAmelCase				   =  out_features
						UpperCAmelCase				   =  num_labels
						UpperCAmelCase				   =  scope
						UpperCAmelCase				   =  num_stages





	def 	_UpperCAmelCase						(		self	: Optional[Any]       ):
						UpperCAmelCase				   =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

						UpperCAmelCase				   =  None
						if self.use_labels:
											UpperCAmelCase				   =  ids_tensor([self.batch_size]    ,self.type_sequence_label_size       )

						UpperCAmelCase				   =  self.get_config()

						return config, pixel_values, labels





	def 	_UpperCAmelCase						(		self	: List[str]       ):
						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]       ):
						return UperNetConfig(
						    backbone_config=self.get_backbone_config()    ,hidden_size=5_1_2    ,pool_scales=[1, 2, 3, 6]    ,use_auxiliary_head=A_    ,auxiliary_loss_weight=0.4    ,auxiliary_in_channels=4_0    ,auxiliary_channels=2_5_6    ,auxiliary_num_convs=1    ,auxiliary_concat_input=A_    ,loss_ignore_index=2_5_5    ,num_labels=self.num_labels    ,)





	def 	_UpperCAmelCase						(		self	: Tuple    ,__SCREAMING_SNAKE_CASE	: str    ,__SCREAMING_SNAKE_CASE	: List[Any]    ,__SCREAMING_SNAKE_CASE	: int       ):
						UpperCAmelCase				   =  UperNetForSemanticSegmentation(config=A_       )
						model.to(A_       )
						model.eval()
						UpperCAmelCase				   =  model(A_       )
						self.parent.assertEqual(
						    result.logits.shape    ,(self.batch_size, self.num_labels, self.image_size, self.image_size)       )





	def 	_UpperCAmelCase						(		self	: List[Any]       ):
						UpperCAmelCase				   =  self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase							
						)   ,     (
						    UpperCAmelCase							
						)   ,     (
						    UpperCAmelCase							
						)   ,     							
						)				   =  config_and_inputs
						UpperCAmelCase				   =  {"pixel_values": pixel_values}
						return config, inputs_dict







@require_torch
class  __magic_name__						(     _a  ,							_a  ,							unittest.TestCase):
	_UpperCAmelCase	:			Dict		   =     (UperNetForSemanticSegmentation,) if is_torch_available() else ()
	_UpperCAmelCase	:			Optional[int]		   =     {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
	_UpperCAmelCase	:			Optional[Any]		   =     False
	_UpperCAmelCase	:			List[str]		   =     False
	_UpperCAmelCase	:			str		   =     False
	_UpperCAmelCase	:			Dict		   =     False
	_UpperCAmelCase	:			Dict		   =     False
	_UpperCAmelCase	:			List[Any]		   =     False





	def 	_UpperCAmelCase						(		self	: Optional[int]       ):
						UpperCAmelCase				   =  UperNetModelTester(self       )
						UpperCAmelCase				   =  ConfigTester(self    ,config_class=A_    ,has_text_modality=A_    ,hidden_size=3_7       )





	def 	_UpperCAmelCase						(		self	: List[str]       ):
						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	: Optional[Any]       ):
						return





	def 	_UpperCAmelCase						(		self	: Optional[Any]       ):
						UpperCAmelCase   ,     UpperCAmelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

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

											UpperCAmelCase				   =  ["pixel_values"]
											self.assertListEqual(arg_names[:1]    ,A_       )





	def 	_UpperCAmelCase						(		self	: str       ):
						UpperCAmelCase				   =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*A_       )





	@unittest.skip(reason="UperNet does not use inputs_embeds"       )
	def 	_UpperCAmelCase						(		self	: int       ):
						pass





	@unittest.skip(reason="UperNet does not support input and output embeddings"       )
	def 	_UpperCAmelCase						(		self	: str       ):
						pass





	@unittest.skip(reason="UperNet does not have a base model"       )
	def 	_UpperCAmelCase						(		self	: Tuple       ):
						pass





	@unittest.skip(reason="UperNet does not have a base model"       )
	def 	_UpperCAmelCase						(		self	: Dict       ):
						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	: Dict       ):
						pass





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





	def 	_UpperCAmelCase						(		self	: Optional[int]       ):
						def check_hidden_states_output(__SCREAMING_SNAKE_CASE	: List[Any]    ,__SCREAMING_SNAKE_CASE	: int    ,__SCREAMING_SNAKE_CASE	: Dict       ):
											UpperCAmelCase				   =  model_class(A_       )
											model.to(A_       )
											model.eval()

											with torch.no_grad():
																UpperCAmelCase				   =  model(**self._prepare_for_class(A_    ,A_       )       )

											UpperCAmelCase				   =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											UpperCAmelCase				   =  self.model_tester.num_stages
											self.assertEqual(len(A_       )    ,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]    ,)

						UpperCAmelCase   ,     UpperCAmelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											UpperCAmelCase				   =  True
											check_hidden_states_output(A_    ,A_    ,A_       )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											UpperCAmelCase				   =  True

											check_hidden_states_output(A_    ,A_    ,A_       )





	def 	_UpperCAmelCase						(		self	: str       ):
						UpperCAmelCase   ,     UpperCAmelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

						UpperCAmelCase				   =  _config_zero_init(A_       )
						UpperCAmelCase				   =  _config_zero_init(configs_no_init.backbone_config       )
						for model_class in self.all_model_classes:
											UpperCAmelCase				   =  model_class(config=A_       )
											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]       ):
						pass





	@slow
	def 	_UpperCAmelCase						(		self	: str       ):
						for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCAmelCase				   =  UperNetForSemanticSegmentation.from_pretrained(A_       )
											self.assertIsNotNone(A_       )







def   __UpperCamelCase						(				):
					"""simple docstring"""





					UpperCAmelCase				   =  hf_hub_download(
					    repo_id="hf-internal-testing/fixtures_ade20k"	,						repo_type="dataset"	,						filename="ADE_val_00000001.jpg" )
					UpperCAmelCase				   =  Image.open(_lowerCAmelCase ).convert("RGB" )
					return image





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





	def 	_UpperCAmelCase						(		self	: Optional[int]       ):
						UpperCAmelCase				   =  AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"       )
						UpperCAmelCase				   =  UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"       ).to(A_       )

						UpperCAmelCase				   =  prepare_img()
						UpperCAmelCase				   =  processor(images=A_    ,return_tensors="pt"       ).to(A_       )

						with torch.no_grad():
											UpperCAmelCase				   =  model(**A_       )

						UpperCAmelCase				   =  torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)       )
						self.assertEqual(outputs.logits.shape    ,A_       )

						UpperCAmelCase				   =  torch.tensor(
						    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]       ).to(A_       )
						self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]    ,A_    ,atol=1e-4       )       )





	def 	_UpperCAmelCase						(		self	: Dict       ):
						UpperCAmelCase				   =  AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"       )
						UpperCAmelCase				   =  UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"       ).to(A_       )

						UpperCAmelCase				   =  prepare_img()
						UpperCAmelCase				   =  processor(images=A_    ,return_tensors="pt"       ).to(A_       )

						with torch.no_grad():
											UpperCAmelCase				   =  model(**A_       )

						UpperCAmelCase				   =  torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)       )
						self.assertEqual(outputs.logits.shape    ,A_       )

						UpperCAmelCase				   =  torch.tensor(
						    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]       ).to(A_       )
						self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]    ,A_    ,atol=1e-4       )       )









import os
import tempfile
import unittest
import uuid
from pathlib import Path

from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText
from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available


if is_torch_available():
    import torch

if is_soundfile_availble():
    import soundfile as sf

if is_vision_available():
    from PIL import Image






def 				_UpperCAmelCase			(    A=""     ):




   '''simple docstring'''

   UpperCAmelCase__						=tempfile.mkdtemp()
   return os.path.join(A				,							str(uuid.uuida()     ) + suffix     )

@require_soundfile
@require_torch
class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       str:
    UpperCAmelCase__						=torch.rand(12,		dtype=torch.floataa		) - 0.5
    UpperCAmelCase__						=AgentAudio(A_		)
    UpperCAmelCase__						=str(agent_type.to_string()		)

    # Ensure that the tensor and the agent_type's tensor are the same
    self.assertTrue(torch.allclose(A_,		agent_type.to_raw(),		atol=1E-4		)		)

    del agent_type

    # Ensure the path remains even after the object deletion
    self.assertTrue(os.path.exists(A_		)		)

    # Ensure that the file contains the same value as the original tensor
    UpperCAmelCase__			,							UpperCAmelCase__						=sf.read(A_		)
    self.assertTrue(torch.allclose(A_,		torch.tensor(A_		),		atol=1E-4		)		)






 def  __UpperCAmelCase						(  self		)	->       Optional[Any]:
    UpperCAmelCase__						=torch.rand(12,		dtype=torch.floataa		) - 0.5
    UpperCAmelCase__						=get_new_path(suffix=".wav"		)
    sf.write(A_,		A_,		1_6000		)

    UpperCAmelCase__						=AgentAudio(A_		)

    self.assertTrue(torch.allclose(A_,		agent_type.to_raw(),		atol=1E-4		)		)
    self.assertEqual(agent_type.to_string(),		A_		)

@require_vision
@require_torch
class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       int:
    UpperCAmelCase__						=torch.randint(0,		256,		(64, 64, 3)		)
    UpperCAmelCase__						=AgentImage(A_		)
    UpperCAmelCase__						=str(agent_type.to_string()		)

    # Ensure that the tensor and the agent_type's tensor are the same
    self.assertTrue(torch.allclose(A_,		agent_type._tensor,		atol=1E-4		)		)

    self.assertIsInstance(agent_type.to_raw(),		Image.Image		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)

 def  __UpperCAmelCase						(  self		)	->       List[str]:
    UpperCAmelCase__						=Path(get_tests_dir("fixtures/tests_samples/COCO"		)		) / "000000039769.png"
    UpperCAmelCase__						=Image.open(A_		)
    UpperCAmelCase__						=AgentImage(A_		)

    self.assertTrue(path.samefile(agent_type.to_string()		)		)
    self.assertTrue(image == agent_type.to_raw()		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)






 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=Path(get_tests_dir("fixtures/tests_samples/COCO"		)		) / "000000039769.png"
    UpperCAmelCase__						=Image.open(A_		)
    UpperCAmelCase__						=AgentImage(A_		)

    self.assertFalse(path.samefile(agent_type.to_string()		)		)
    self.assertTrue(image == agent_type.to_raw()		)

    # Ensure the path remains even after the object deletion
    del agent_type
    self.assertTrue(os.path.exists(A_		)		)

class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    UpperCAmelCase__						="Hey!"
    UpperCAmelCase__						=AgentText(A_		)

    self.assertEqual(A_,		agent_type.to_string()		)
    self.assertEqual(A_,		agent_type.to_raw()		)
    self.assertEqual(A_,		A_		)



