from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image


UpperCAmelCase_			    =							['''text''', '''image''', '''audio''']




def       lowerCAmelCase_     (		lowercase:							List[str]		)    ->				Dict:







 '''simple docstring'''
 _UpperCamelCase:     List[Any]							= []

 for input_type in input_types:
  if input_type == "text":
   inputs.append('''Text input'''		)
  elif input_type == "image":
   inputs.append(
       Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO'''		)		) / '''000000039769.png'''		).resize((512, 512)		)		)
  elif input_type == "audio":
   inputs.append(torch.ones(3_000		)		)
  elif isinstance(lowercase  ,					lowercase		):
   inputs.append(create_inputs(lowercase		)		)
  else:
   raise ValueError(F"""Invalid type requested: {input_type}"""		)

 return inputs




def       lowerCAmelCase_     (		lowercase:							List		)    ->				str:







 '''simple docstring'''
 _UpperCamelCase:     int							= []

 for output in outputs:
  if isinstance(lowercase  ,					(str, AgentText)		):
   output_types.append('''text'''		)
  elif isinstance(lowercase  ,					(Image.Image, AgentImage)		):
   output_types.append('''image'''		)
  elif isinstance(lowercase  ,					(torch.Tensor, AgentAudio)		):
   output_types.append('''audio'''		)
  else:
   raise ValueError(F"""Invalid output: {output}"""		)

 return output_types





@is_tool_test
class  __magic_name__  :





   """simple docstring"""




   def   lowerCAmelCase						(	self					:  Optional[int]							):



    """simple docstring"""



    self.assertTrue(hasattr(self.tool		,  '''inputs'''							)							)
    self.assertTrue(hasattr(self.tool		,  '''outputs'''							)							)

    _UpperCamelCase:     List[str]							= self.tool.inputs
    for _input in inputs:
     if isinstance(_input		,  _lowercase							):
      for __input in _input:
       self.assertTrue(__input in authorized_types							)
     else:
      self.assertTrue(_input in authorized_types							)

    _UpperCamelCase:     List[str]							= self.tool.outputs
    for _output in outputs:
     self.assertTrue(_output in authorized_types							)



   def   lowerCAmelCase						(	self					:  List[str]							):



    """simple docstring"""



    _UpperCamelCase:     List[str]							= create_inputs(self.tool.inputs							)
    _UpperCamelCase:     Any							= self.tool(*_lowercase							)

    # There is a single output
    if len(self.tool.outputs							) == 1:
     _UpperCamelCase:     Tuple							= [outputs]

    self.assertListEqual(output_types(_lowercase							)		,  self.tool.outputs							)



   def   lowerCAmelCase						(	self					:  Any							):



    """simple docstring"""



    self.assertTrue(hasattr(self.tool		,  '''description'''							)							)
    self.assertTrue(hasattr(self.tool		,  '''default_checkpoint'''							)							)
    self.assertTrue(self.tool.description.startswith('''This is a tool that'''							)							)



   def   lowerCAmelCase						(	self					:  int							):



    """simple docstring"""



    _UpperCamelCase:     Optional[int]							= create_inputs(self.tool.inputs							)
    _UpperCamelCase:     str							= self.tool(*_lowercase							)

    if not isinstance(_lowercase		,  _lowercase							):
     _UpperCamelCase:     str							= [outputs]

    self.assertEqual(len(_lowercase							)		,  len(self.tool.outputs							)							)

    for output, output_type in zip(_lowercase		,  self.tool.outputs							):
     _UpperCamelCase:     str							= AGENT_TYPE_MAPPING[output_type]
     self.assertTrue(isinstance(_lowercase		,  _lowercase							)							)



   def   lowerCAmelCase						(	self					:  Dict							):



    """simple docstring"""



    _UpperCamelCase:     Optional[Any]							= create_inputs(self.tool.inputs							)

    _UpperCamelCase:     Optional[Any]							= []

    for _input, input_type in zip(_lowercase		,  self.tool.inputs							):
     if isinstance(_lowercase		,  _lowercase							):
      _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input							) for _input_type in input_type]							)
     else:
      _inputs.append(AGENT_TYPE_MAPPING[input_type](_input							)							)

        # Should not raise an error
    _UpperCamelCase:     int							= self.tool(*_lowercase							)

    if not isinstance(_lowercase		,  _lowercase							):
     _UpperCamelCase:     Optional[int]							= [outputs]

    self.assertEqual(len(_lowercase							)		,  len(self.tool.outputs							)							)
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__  :





   """simple docstring"""




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



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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

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

    _UpperCamelCase:     Union[str, Any]							= self.get_config()

    return config, pixel_values, labels



   def   lowerCAmelCase						(	self					:  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   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  Tuple		,  _lowercase					:  Tuple		,  _lowercase					:  Optional[Any]		,  _lowercase					:  Dict							):



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  Union[str, Any]							):



    """simple docstring"""



    _UpperCamelCase:     List[str]							= self.prepare_config_and_inputs()
    (
        (
        _UpperCamelCase
    )	,							(
        _UpperCamelCase
    )	,							(
        _UpperCamelCase
    )	,							
    ):     str							= config_and_inputs
    _UpperCamelCase:     Dict							= {'''pixel_values''': pixel_values}
    return config, inputs_dict




@require_torch
class  __magic_name__  (		__a      ,	__a      ,	unittest.TestCase    ):





   """simple docstring"""




   lowerCAmelCase      :    List[Any]  			=   (UperNetForSemanticSegmentation,) if is_torch_available() else ()
   lowerCAmelCase      :    Tuple  			=   {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
   lowerCAmelCase      :    Dict  			=   False
   lowerCAmelCase      :    str  			=   False
   lowerCAmelCase      :    Optional[Any]  			=   False
   lowerCAmelCase      :    Optional[Any]  			=   False
   lowerCAmelCase      :    List[Any]  			=   False
   lowerCAmelCase      :    Union[str, Any]  			=   False



   def   lowerCAmelCase						(	self					:  Dict							):



    """simple docstring"""



    _UpperCamelCase:     Optional[int]							= UperNetModelTester(self							)
    _UpperCamelCase:     List[str]							= ConfigTester(self		,  config_class=_lowercase		,  has_text_modality=_lowercase		,  hidden_size=37							)



   def   lowerCAmelCase						(	self					:  str							):



    """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   lowerCAmelCase						(	self					:  List[Any]							):



    """simple docstring"""



    return



   def   lowerCAmelCase						(	self					:  List[str]							):



    """simple docstring"""



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

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

     _UpperCamelCase:     List[Any]							= ['''pixel_values''']
     self.assertListEqual(arg_names[:1]		,  _lowercase							)



   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



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



   @unittest.skip(reason='''UperNet does not use inputs_embeds'''							)
   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    pass



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



    """simple docstring"""



    pass



   @unittest.skip(reason='''UperNet does not have a base model'''							)
   def   lowerCAmelCase						(	self					:  Any							):



    """simple docstring"""



    pass



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



    """simple docstring"""



    pass



   @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''							)
   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    pass



   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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

     with torch.no_grad():
      _UpperCamelCase:     Union[str, Any]							= model(**self._prepare_for_class(_lowercase		,  _lowercase							)							)

     _UpperCamelCase:     Optional[Any]							= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

    for model_class in self.all_model_classes:
     _UpperCamelCase:     Optional[int]							= True
     check_hidden_states_output(_lowercase		,  _lowercase		,  _lowercase							)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     _UpperCamelCase:     Union[str, Any]							= True

     check_hidden_states_output(_lowercase		,  _lowercase		,  _lowercase							)



   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



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

    _UpperCamelCase:     int							= _config_zero_init(_lowercase							)
    _UpperCamelCase:     List[Any]							= _config_zero_init(configs_no_init.backbone_config							)
    for model_class in self.all_model_classes:
     _UpperCamelCase:     int							= model_class(config=_lowercase							)
     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   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    pass



   @slow
   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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




def       lowerCAmelCase_     (		)    ->				Dict:







 '''simple docstring'''
 _UpperCamelCase:     Any							= hf_hub_download(
     repo_id='''hf-internal-testing/fixtures_ade20k'''  ,					repo_type='''dataset'''  ,					filename='''ADE_val_00000001.jpg'''		)
 _UpperCamelCase:     Any							= Image.open(lowercase		).convert('''RGB'''		)
 return image





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





   """simple docstring"""




   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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

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

    with torch.no_grad():
     _UpperCamelCase:     Any							= model(**_lowercase							)

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

    _UpperCamelCase:     Tuple							= torch.tensor(
        [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]							).to(_lowercase							)
    self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,  _lowercase		,  atol=1E-4							)							)



   def   lowerCAmelCase						(	self					:  int							):



    """simple docstring"""



    _UpperCamelCase:     Tuple							= AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''							)
    _UpperCamelCase:     int							= UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''							).to(_lowercase							)

    _UpperCamelCase:     int							= prepare_img()
    _UpperCamelCase:     Union[str, Any]							= processor(images=_lowercase		,  return_tensors='''pt'''							).to(_lowercase							)

    with torch.no_grad():
     _UpperCamelCase:     List[Any]							= model(**_lowercase							)

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

    _UpperCamelCase:     Optional[Any]							= torch.tensor(
        [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]							).to(_lowercase							)
    self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,  _lowercase		,  atol=1E-4							)							)