



"""simple docstring"""




import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from ....modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
from ....modeling_utils import ModuleUtilsMixin
from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings


_UpperCamelCase:				List[Any]    							=  logging.get_logger(__name__)

_UpperCamelCase:				str    							=  'MMBTConfig'


class   a__		(						nn.Module     ):


   def __init__(							self      :							Union[str, Any],     lowerCAmelCase      :							List[str],     lowerCAmelCase      :							Optional[Any],     lowerCAmelCase      :							Dict			)    ->       List[Any]:
         super().__init__()
         lowercase  :      Optional[Any]					=   config
         lowercase  :      str					=   encoder
         lowercase  :      List[str]					=   nn.Linear(config.modal_hidden_size,     config.hidden_size			)
         lowercase  :      List[Any]					=   embeddings.position_embeddings
         lowercase  :      Optional[int]					=   embeddings.token_type_embeddings
         lowercase  :      Optional[int]					=   embeddings.word_embeddings
         lowercase  :      List[Any]					=   embeddings.LayerNorm
         lowercase  :      List[Any]					=   nn.Dropout(p=config.hidden_dropout_prob			)






   def        lowercase				(							self      :							str,     lowerCAmelCase      :							Tuple,     lowerCAmelCase      :							Any=None,     lowerCAmelCase      :							Union[str, Any]=None,     lowerCAmelCase      :							Tuple=None,     lowerCAmelCase      :							List[str]=None			)    ->       Tuple:
         lowercase  :      Tuple					=   self.proj_embeddings(self.encoder(lowerCAmelCase			)			)
         lowercase  :      Optional[Any]					=   token_embeddings.size(1			)

         if start_token is not None:
               lowercase  :      Optional[int]					=   self.word_embeddings(lowerCAmelCase			)
               seq_length += 1
               lowercase  :      Optional[Any]					=   torch.cat([start_token_embeds.unsqueeze(1			), token_embeddings],     dim=1			)

         if end_token is not None:
               lowercase  :      List[str]					=   self.word_embeddings(lowerCAmelCase			)
               seq_length += 1
               lowercase  :      Optional[Any]					=   torch.cat([token_embeddings, end_token_embeds.unsqueeze(1			)],     dim=1			)

         if position_ids is None:
               lowercase  :      Optional[Any]					=   torch.arange(lowerCAmelCase,     dtype=torch.long,     device=input_modal.device			)
               lowercase  :      Optional[int]					=   position_ids.unsqueeze(0			).expand(input_modal.size(0			),     lowerCAmelCase			)

         if token_type_ids is None:
               lowercase  :      Dict					=   torch.zeros(
                   (input_modal.size(0			), seq_length),     dtype=torch.long,     device=input_modal.device			)

         lowercase  :      List[Any]					=   self.position_embeddings(lowerCAmelCase			)
         lowercase  :      Optional[int]					=   self.token_type_embeddings(lowerCAmelCase			)
         lowercase  :      List[str]					=   token_embeddings + position_embeddings + token_type_embeddings
         lowercase  :      List[Any]					=   self.LayerNorm(lowerCAmelCase			)
         lowercase  :      List[Any]					=   self.dropout(lowerCAmelCase			)
         return embeddings




_UpperCamelCase:				List[str]    							=  R'\n    MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and\n    Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.\n    It\'s a supervised multimodal bitransformer model that fuses information from text and other image encoders, and\n    obtain state-of-the-art performance on various multimodal classification benchmark tasks.\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`MMBTConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration.\n        transformer (`nn.Module`): A text transformer that is used by MMBT.\n            It should have embeddings, encoder, and pooler attributes.\n        encoder (`nn.Module`): Encoder for the second modality.\n            It should take in a batch of modal inputs and return k, n dimension embeddings.\n'

_UpperCamelCase:				List[Any]    							=  R'\n    Args:\n        input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):\n            The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image\n            Encoder, the shape would be (batch_size, channels, height, width)\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it\'s\n            appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See\n            [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification\n            tasks.\n        modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n            Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.\n        attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:\n            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n            [What are attention masks?](../glossary#attention-mask)\n        token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:\n            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n            1]`:\n\n            - 0 corresponds to a *sentence A* token,\n            - 1 corresponds to a *sentence B* token.\n\n            [What are token type IDs?](../glossary#token-type-ids)\n        modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:\n            Segment token indices to indicate different portions of the non-text modality. The embeddings from these\n            tokens will be summed with the respective token embeddings for the non-text modality.\n        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n            config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):\n            Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.\n            Selected in the range `[0, config.max_position_embeddings - 1]`.\n\n            [What are position IDs?](../glossary#position-ids)\n        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n            - 1 indicates the head is **not masked**,\n            - 0 indicates the head is **masked**.\n\n        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*):\n            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n            model\'s internal embedding lookup matrix.\n        encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):\n            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if\n            the model is configured as a decoder.\n        encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):\n            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in\n            the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:\n\n            - 1 for tokens that are **not masked**,\n            - 0 for tokens that are **masked**.\n\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n            tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'


@add_start_docstrings(
    'The bare MMBT Model outputting raw hidden-states without any specific head on top.',  SCREAMING_SNAKE_CASE__,  )
class   a__		(						nn.Module,  SCREAMING_SNAKE_CASE__     ):


   def __init__(							self      :							Dict,     lowerCAmelCase      :							Dict,     lowerCAmelCase      :							Dict,     lowerCAmelCase      :							Optional[int]			)    ->       Tuple:
         super().__init__()
         lowercase  :      Union[str, Any]					=   config
         lowercase  :      Dict					=   transformer
         lowercase  :      int					=   ModalEmbeddings(lowerCAmelCase,     lowerCAmelCase,     transformer.embeddings			)


   @add_start_docstrings_to_model_forward(lowerCAmelCase			)
   @replace_return_docstrings(output_type=lowerCAmelCase,     config_class=_CONFIG_FOR_DOC			)
   def        lowercase				(							self      :							Optional[Any],     lowerCAmelCase      :							Dict,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Optional[Any]=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Any=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Optional[int]=None,     lowerCAmelCase      :							Any=None,     lowerCAmelCase      :							Union[str, Any]=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Optional[Any]=None,     lowerCAmelCase      :							List[str]=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Dict=None,     )    ->       List[str]:
         lowercase  :      Optional[int]					=   output_attentions if output_attentions is not None else self.config.output_attentions
         lowercase  :      Dict					=   (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         lowercase  :      List[str]					=   return_dict if return_dict is not None else self.config.use_return_dict

         if input_ids is not None and inputs_embeds is not None:
               raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time'			)
         elif input_ids is not None:
               lowercase  :      int					=   input_ids.size()
         elif inputs_embeds is not None:
               lowercase  :      List[str]					=   inputs_embeds.size()[:-1]
         else:
               raise ValueError('You have to specify either input_ids or inputs_embeds'			)

         lowercase  :      Union[str, Any]					=   input_ids.device if input_ids is not None else inputs_embeds.device

         lowercase  :      List[Any]					=   self.modal_encoder(
             lowerCAmelCase,     start_token=lowerCAmelCase,     end_token=lowerCAmelCase,     position_ids=lowerCAmelCase,     token_type_ids=lowerCAmelCase,     )

         lowercase  :      Dict					=   modal_embeddings.size()[:-1]

         if token_type_ids is None:
               lowercase  :      List[Any]					=   torch.ones(lowerCAmelCase,     dtype=torch.long,     device=lowerCAmelCase			)

         lowercase  :      str					=   self.transformer.embeddings(
             input_ids=lowerCAmelCase,     position_ids=lowerCAmelCase,     token_type_ids=lowerCAmelCase,     inputs_embeds=lowerCAmelCase			)

         lowercase  :      List[Any]					=   torch.cat([modal_embeddings, txt_embeddings],     1			)

         lowercase  :      int					=   embedding_output.size()[:-1]

         if attention_mask is None:
               lowercase  :      Optional[Any]					=   torch.ones(lowerCAmelCase,     device=lowerCAmelCase			)
         else:
               lowercase  :      Union[str, Any]					=   torch.cat(
                   [torch.ones(lowerCAmelCase,     device=lowerCAmelCase,     dtype=torch.long			), attention_mask],     dim=1			)
         if encoder_attention_mask is None:
               lowercase  :      List[str]					=   torch.ones(lowerCAmelCase,     device=lowerCAmelCase			)
         else:
               lowercase  :      int					=   torch.cat(
                   [torch.ones(lowerCAmelCase,     device=lowerCAmelCase			), encoder_attention_mask],     dim=1			)

         lowercase  :      Optional[int]					=   self.get_extended_attention_mask(lowerCAmelCase,     lowerCAmelCase			)
         lowercase  :      str					=   self.invert_attention_mask(lowerCAmelCase			)
         lowercase  :      Any					=   self.get_head_mask(lowerCAmelCase,     self.config.num_hidden_layers			)

         lowercase  :      int					=   self.transformer.encoder(
             lowerCAmelCase,     attention_mask=lowerCAmelCase,     head_mask=lowerCAmelCase,     encoder_hidden_states=lowerCAmelCase,     encoder_attention_mask=lowerCAmelCase,     output_attentions=lowerCAmelCase,     output_hidden_states=lowerCAmelCase,     return_dict=lowerCAmelCase,     )

         lowercase  :      List[Any]					=   encoder_outputs[0]
         lowercase  :      Union[str, Any]					=   self.transformer.pooler(lowerCAmelCase			)

         if not return_dict:
               return (sequence_output, pooled_output) + encoder_outputs[1:]

         return BaseModelOutputWithPooling(
             last_hidden_state=lowerCAmelCase,     pooler_output=lowerCAmelCase,     hidden_states=encoder_outputs.hidden_states,     attentions=encoder_outputs.attentions,     )


   def        lowercase				(							self      :							str			)    ->       Optional[Any]:
         return self.embeddings.word_embeddings






   def        lowercase				(							self      :							List[str],     lowerCAmelCase      :							Union[str, Any]			)    ->       Any:
         lowercase  :      Optional[Any]					=   value




@add_start_docstrings(
    '\n    MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n    ',  SCREAMING_SNAKE_CASE__,  SCREAMING_SNAKE_CASE__,  )
class   a__		(						nn.Module     ):


   def __init__(							self      :							Tuple,     lowerCAmelCase      :							Union[str, Any],     lowerCAmelCase      :							Optional[Any],     lowerCAmelCase      :							Optional[Any]			)    ->       List[str]:
         super().__init__()
         lowercase  :      Dict					=   config.num_labels

         lowercase  :      Optional[Any]					=   MMBTModel(lowerCAmelCase,     lowerCAmelCase,     lowerCAmelCase			)
         lowercase  :      int					=   nn.Dropout(config.hidden_dropout_prob			)
         lowercase  :      List[Any]					=   nn.Linear(config.hidden_size,     config.num_labels			)






   def        lowercase				(							self      :							str,     lowerCAmelCase      :							Union[str, Any],     lowerCAmelCase      :							Optional[int]=None,     lowerCAmelCase      :							List[Any]=None,     lowerCAmelCase      :							int=None,     lowerCAmelCase      :							Dict=None,     lowerCAmelCase      :							Tuple=None,     lowerCAmelCase      :							str=None,     lowerCAmelCase      :							List[str]=None,     lowerCAmelCase      :							Any=None,     lowerCAmelCase      :							Union[str, Any]=None,     lowerCAmelCase      :							str=None,     lowerCAmelCase      :							Union[str, Any]=None,     lowerCAmelCase      :							List[str]=None,     )    ->       str:
         lowercase  :      List[str]					=   return_dict if return_dict is not None else self.config.use_return_dict

         lowercase  :      Union[str, Any]					=   self.mmbt(
             input_modal=lowerCAmelCase,     input_ids=lowerCAmelCase,     modal_start_tokens=lowerCAmelCase,     modal_end_tokens=lowerCAmelCase,     attention_mask=lowerCAmelCase,     token_type_ids=lowerCAmelCase,     modal_token_type_ids=lowerCAmelCase,     position_ids=lowerCAmelCase,     modal_position_ids=lowerCAmelCase,     head_mask=lowerCAmelCase,     inputs_embeds=lowerCAmelCase,     return_dict=lowerCAmelCase,     )

         lowercase  :      str					=   outputs[1]

         lowercase  :      Dict					=   self.dropout(lowerCAmelCase			)
         lowercase  :      Tuple					=   self.classifier(lowerCAmelCase			)

         lowercase  :      Dict					=   None
         if labels is not None:
               if self.num_labels == 1:
                     #  We are doing regression
                     lowercase  :      List[str]					=   MSELoss()
                     lowercase  :      List[str]					=   loss_fct(logits.view(-1			),     labels.view(-1			)			)
               else:
                     lowercase  :      List[Any]					=   CrossEntropyLoss()
                     lowercase  :      Union[str, Any]					=   loss_fct(logits.view(-1,     self.num_labels			),     labels.view(-1			)			)

         if not return_dict:
               lowercase  :      Dict					=   (logits,) + outputs[2:]
               return ((loss,) + output) if loss is not None else output

         return SequenceClassifierOutput(
             loss=lowerCAmelCase,     logits=lowerCAmelCase,     hidden_states=outputs.hidden_states,     attentions=outputs.attentions,     )





"""simple docstring"""




import os
import pathlib
import tempfile
import uuid

import numpy as np

from ..utils import is_soundfile_availble, is_torch_available, is_vision_available, logging


_UpperCamelCase:				List[str]    							=  logging.get_logger(__name__)

if is_vision_available():
     import PIL.Image
     from PIL import Image
     from PIL.Image import Image as ImageType
else:
     _UpperCamelCase:				Tuple    							=  object

if is_torch_available():
     import torch

if is_soundfile_availble():
     import soundfile as sf


class   a__		:


   def __init__(							self      :							Union[str, Any],     lowerCAmelCase      :							Optional[int]			)    ->       Any:
         lowercase  :      Dict					=   value


   def __str__(							self      :							List[str]			)    ->       Union[str, Any]:
         return self.to_string()


   def        lowercase				(							self      :							Dict			)    ->       Optional[Any]:
         logger.error(
             'This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable'			)
         return self._value






   def        lowercase				(							self      :							List[Any]			)    ->       str:
         logger.error(
             'This is a raw AgentType of unknown type. Display in notebooks and string conversion will be unreliable'			)
         return str(self._value			)




class   a__		(						SCREAMING_SNAKE_CASE__,  SCREAMING_SNAKE_CASE__     ):


   def        lowercase				(							self      :							List[Any]			)    ->       List[Any]:
         return self._value






   def        lowercase				(							self      :							str			)    ->       Optional[int]:
         return self._value




class   a__		(						SCREAMING_SNAKE_CASE__,  SCREAMING_SNAKE_CASE__     ):


   def __init__(							self      :							int,     lowerCAmelCase      :							Optional[Any]			)    ->       Any:
         super().__init__(lowerCAmelCase			)

         if not is_vision_available():
               raise ImportError('PIL must be installed in order to handle images.'			)

         lowercase  :      Union[str, Any]					=   None
         lowercase  :      List[str]					=   None
         lowercase  :      Optional[Any]					=   None

         if isinstance(lowerCAmelCase,     lowerCAmelCase			):
               lowercase  :      List[Any]					=   value
         elif isinstance(lowerCAmelCase,     (str, pathlib.Path)			):
               lowercase  :      Any					=   value
         elif isinstance(lowerCAmelCase,     torch.Tensor			):
               lowercase  :      str					=   value
         else:
               raise ValueError(f'''Unsupported type for {self.__class__.__name__}: {type(lowerCAmelCase			)}'''			)


   def        lowercase				(							self      :							int,     lowerCAmelCase      :							Union[str, Any]=None,     lowerCAmelCase      :							Optional[Any]=None			)    ->       List[Any]:
         from IPython.display import Image, display

         display(Image(self.to_string()			)			)


   def        lowercase				(							self      :							int			)    ->       List[str]:
         if self._raw is not None:
               return self._raw

         if self._path is not None:
               lowercase  :      Any					=   Image.open(self._path			)
               return self._raw






   def        lowercase				(							self      :							List[Any]			)    ->       List[Any]:
         if self._path is not None:
               return self._path

         if self._raw is not None:
               lowercase  :      Tuple					=   tempfile.mkdtemp()
               lowercase  :      Dict					=   os.path.join(lowerCAmelCase,     str(uuid.uuida()			) + '.png'			)
               self._raw.save(self._path			)

               return self._path

         if self._tensor is not None:
               lowercase  :      Optional[int]					=   self._tensor.cpu().detach().numpy()

               # There is likely simpler than load into image into save
               lowercase  :      Dict					=   Image.fromarray((array * 255).astype(np.uinta			)			)

               lowercase  :      Optional[int]					=   tempfile.mkdtemp()
               lowercase  :      Any					=   os.path.join(lowerCAmelCase,     str(uuid.uuida()			) + '.png'			)

               img.save(self._path			)

               return self._path




class   a__		(						SCREAMING_SNAKE_CASE__     ):


   def __init__(							self      :							Dict,     lowerCAmelCase      :							Any,     lowerCAmelCase      :							Any=16000			)    ->       Tuple:
         super().__init__(lowerCAmelCase			)

         if not is_soundfile_availble():
               raise ImportError('soundfile must be installed in order to handle audio.'			)

         lowercase  :      List[str]					=   None
         lowercase  :      List[Any]					=   None

         lowercase  :      Optional[Any]					=   samplerate

         if isinstance(lowerCAmelCase,     (str, pathlib.Path)			):
               lowercase  :      List[Any]					=   value
         elif isinstance(lowerCAmelCase,     torch.Tensor			):
               lowercase  :      List[str]					=   value
         else:
               raise ValueError(f'''Unsupported audio type: {type(lowerCAmelCase			)}'''			)


   def        lowercase				(							self      :							Optional[int],     lowerCAmelCase      :							Optional[Any]=None,     lowerCAmelCase      :							int=None			)    ->       Optional[Any]:
         from IPython.display import Audio, display

         display(Audio(self.to_string(),     rate=self.samplerate			)			)


   def        lowercase				(							self      :							Any			)    ->       Union[str, Any]:
         if self._tensor is not None:
               return self._tensor

         if self._path is not None:
               lowercase	,    lowercase  :      List[Any]					=   sf.read(self._path			)
               lowercase  :      int					=   torch.tensor(lowerCAmelCase			)
               return self._tensor






   def        lowercase				(							self      :							Tuple			)    ->       Tuple:
         if self._path is not None:
               return self._path

         if self._tensor is not None:
               lowercase  :      str					=   tempfile.mkdtemp()
               lowercase  :      Union[str, Any]					=   os.path.join(lowerCAmelCase,     str(uuid.uuida()			) + '.wav'			)
               sf.write(self._path,     self._tensor,     samplerate=self.samplerate			)
               return self._path




_UpperCamelCase:				Optional[int]    							=  {'text': AgentText, 'image': AgentImage, 'audio': AgentAudio}
_UpperCamelCase:				Optional[int]    							=  {str: AgentText}

if is_vision_available():
     _UpperCamelCase:				str    							=  AgentImage


def   lowercase__     (			*_UpperCAmelCase	,      **_UpperCAmelCase				)     ->			Any:






      '''simple docstring'''


      lowercase  :      str					=   [(arg.to_raw() if isinstance(_UpperCAmelCase	,      _UpperCAmelCase				) else arg) for arg in args]
      lowercase  :      Optional[Any]					=   {k: (v.to_raw() if isinstance(_UpperCAmelCase	,      _UpperCAmelCase				) else v) for k, v in kwargs.items()}
      return args, kwargs





def   lowercase__     (			_UpperCAmelCase	,      _UpperCAmelCase=None				)     ->			Tuple:






      '''simple docstring'''


      if isinstance(_UpperCAmelCase	,      _UpperCAmelCase				):
            lowercase  :      List[Any]					=   {}
            for i, (k, v) in enumerate(outputs.items()				):
                  if output_types is not None:
                        # If the class has defined outputs, we can map directly according to the class definition
                        if output_types[i] in AGENT_TYPE_MAPPING:
                              lowercase  :      int					=   AGENT_TYPE_MAPPING[output_types[i]](_UpperCAmelCase				)
                        else:
                              lowercase  :      Union[str, Any]					=   AgentType(_UpperCAmelCase				)

                  else:
                        # If the class does not have defined output, then we map according to the type
                        for _k, _v in INSTANCE_TYPE_MAPPING.items():
                              if isinstance(_UpperCAmelCase	,      _k				):
                                    lowercase  :      Optional[int]					=   _v(_UpperCAmelCase				)
                        if k not in decoded_outputs:
                              lowercase  :      str					=   AgentType[v]

      elif isinstance(_UpperCAmelCase	,      (list, tuple)				):
            lowercase  :      Union[str, Any]					=   type(_UpperCAmelCase				)()
            for i, v in enumerate(_UpperCAmelCase				):
                  if output_types is not None:
                        # If the class has defined outputs, we can map directly according to the class definition
                        if output_types[i] in AGENT_TYPE_MAPPING:
                              decoded_outputs.append(AGENT_TYPE_MAPPING[output_types[i]](_UpperCAmelCase				)				)
                        else:
                              decoded_outputs.append(AgentType(_UpperCAmelCase				)				)
                  else:
                        # If the class does not have defined output, then we map according to the type
                        lowercase  :      Any					=   False
                        for _k, _v in INSTANCE_TYPE_MAPPING.items():
                              if isinstance(_UpperCAmelCase	,      _k				):
                                    decoded_outputs.append(_v(_UpperCAmelCase				)				)
                                    lowercase  :      Optional[Any]					=   True

                        if not found:
                              decoded_outputs.append(AgentType(_UpperCAmelCase				)				)

      else:
            if output_types[0] in AGENT_TYPE_MAPPING:
                  # If the class has defined outputs, we can map directly according to the class definition
                  lowercase  :      List[Any]					=   AGENT_TYPE_MAPPING[output_types[0]](_UpperCAmelCase				)

            else:
                  # If the class does not have defined output, then we map according to the type
                  for _k, _v in INSTANCE_TYPE_MAPPING.items():
                        if isinstance(_UpperCAmelCase	,      _k				):
                              return _v(_UpperCAmelCase				)
                  return AgentType(_UpperCAmelCase				)

      return decoded_outputs
