



'''simple docstring'''





from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase      						=	logging.get_logger(__name__)

_lowerCAmelCase      						=	{
    '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json''',
}






class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  __lowercase							:      List[str]				=      '''lxmert'''
  __lowercase							:      str				=      {}




  def __init__(    self  ,__UpperCAmelCase=3_0522  ,__UpperCAmelCase=768  ,__UpperCAmelCase=12  ,__UpperCAmelCase=9500  ,__UpperCAmelCase=1600  ,__UpperCAmelCase=400  ,__UpperCAmelCase=3072  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=512  ,__UpperCAmelCase=2  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=1E-12  ,__UpperCAmelCase=9  ,__UpperCAmelCase=5  ,__UpperCAmelCase=5  ,__UpperCAmelCase=2048  ,__UpperCAmelCase=4  ,__UpperCAmelCase=6.6_7  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,**__UpperCAmelCase  ,)    ->		Any:
      lowerCAmelCase__ :  str							      =					vocab_size
      lowerCAmelCase__ :  int							      =					hidden_size
      lowerCAmelCase__ :  List[str]							      =					num_attention_heads
      lowerCAmelCase__ :  Tuple							      =					hidden_act
      lowerCAmelCase__ :  List[str]							      =					intermediate_size
      lowerCAmelCase__ :  Dict							      =					hidden_dropout_prob
      lowerCAmelCase__ :  Optional[Any]							      =					attention_probs_dropout_prob
      lowerCAmelCase__ :  Optional[int]							      =					max_position_embeddings
      lowerCAmelCase__ :  Optional[Any]							      =					type_vocab_size
      lowerCAmelCase__ :  Tuple							      =					initializer_range
      lowerCAmelCase__ :  Dict							      =					layer_norm_eps
      lowerCAmelCase__ :  Union[str, Any]							      =					num_qa_labels
      lowerCAmelCase__ :  Optional[int]							      =					num_object_labels
      lowerCAmelCase__ :  Dict							      =					num_attr_labels
      lowerCAmelCase__ :  Tuple							      =					l_layers
      lowerCAmelCase__ :  str							      =					x_layers
      lowerCAmelCase__ :  Any							      =					r_layers
      lowerCAmelCase__ :  Dict							      =					visual_feat_dim
      lowerCAmelCase__ :  Union[str, Any]							      =					visual_pos_dim
      lowerCAmelCase__ :  Union[str, Any]							      =					visual_loss_normalizer
      lowerCAmelCase__ :  Optional[Any]							      =					task_matched
      lowerCAmelCase__ :  Any							      =					task_mask_lm
      lowerCAmelCase__ :  Union[str, Any]							      =					task_obj_predict
      lowerCAmelCase__ :  List[str]							      =					task_qa
      lowerCAmelCase__ :  Any							      =					visual_obj_loss
      lowerCAmelCase__ :  Dict							      =					visual_attr_loss
      lowerCAmelCase__ :  List[str]							      =					visual_feat_loss
      lowerCAmelCase__ :  Optional[Any]							      =					{"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers}
      super().__init__(**__UpperCAmelCase      )







'''simple docstring'''





import uuid
from typing import Any, Dict, List, Optional, Union

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
 import tensorflow as tf

if is_torch_available():
 import torch


_lowerCAmelCase      						=	logging.get_logger(__name__)






class        lowerCAmelCase_:
  '''simple docstring'''




  def __init__(    self  ,__UpperCAmelCase = None  ,__UpperCAmelCase = None  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None      )    ->		str:
      if not conversation_id:
          lowerCAmelCase__ :  List[str]							      =					uuid.uuida()
      if past_user_inputs is None:
          lowerCAmelCase__ :  List[Any]							      =					[]
      if generated_responses is None:
          lowerCAmelCase__ :  str							      =					[]

      lowerCAmelCase__ :  uuid.UUID							      =					conversation_id
      lowerCAmelCase__ :  List[str]							      =					past_user_inputs
      lowerCAmelCase__ :  List[str]							      =					generated_responses
      lowerCAmelCase__ :  Optional[str]							      =					text




  def __eq__(    self  ,__UpperCAmelCase      )    ->		Dict:
      if not isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ):
          return False
      if self.uuid == other.uuid:
          return True
      return (
          self.new_user_input == other.new_user_input
          and self.past_user_inputs == other.past_user_inputs
          and self.generated_responses == other.generated_responses
      )




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase = False      )    ->		Optional[Any]:
      if self.new_user_input:
          if overwrite:
              logger.warning(
                  F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """
                  F"""with: \"{text}\"."""      )
              lowerCAmelCase__ :  Optional[int]							      =					text
          else:
              logger.warning(
                  F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """
                  F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input"""      )
      else:
          lowerCAmelCase__ :  Optional[Any]							      =					text




  def 							UpperCAmelCase_	(    self      )    ->		List[Any]:
      if self.new_user_input:
          self.past_user_inputs.append(self.new_user_input      )
      lowerCAmelCase__ :  Union[str, Any]							      =					None




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Tuple:
      self.generated_responses.append(__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self      )    ->		List[str]:
      for user_input, generated_response in zip(self.past_user_inputs  ,self.generated_responses      ):
          yield True, user_input
          yield False, generated_response
      if self.new_user_input:
          yield True, self.new_user_input






  def __repr__(    self      )    ->		Tuple:
      lowerCAmelCase__ :  Tuple							      =					F"""Conversation id: {self.uuid} \n"""
      for is_user, text in self.iter_texts():
          lowerCAmelCase__ :  Any							      =					"""user""" if is_user else """bot"""
          output += F"""{name} >> {text} \n"""
      return output







@add_end_docstrings(
    SCREAMING_SNAKE_CASE_						, R'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''						, )
class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  def __init__(    self  ,*__UpperCAmelCase  ,**__UpperCAmelCase      )    ->		Tuple:
      super().__init__(*__UpperCAmelCase  ,**__UpperCAmelCase      )
      if self.tokenizer.pad_token_id is None:
          lowerCAmelCase__ :  Tuple							      =					self.tokenizer.eos_token




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,__UpperCAmelCase=None  ,**__UpperCAmelCase      )    ->		Optional[int]:
      lowerCAmelCase__ :  List[Any]							      =					{}
      lowerCAmelCase__ :  Optional[int]							      =					{}
      lowerCAmelCase__ :  List[str]							      =					{}

      if min_length_for_response is not None:
          lowerCAmelCase__ :  Any							      =					min_length_for_response
      if minimum_tokens is not None:
          lowerCAmelCase__ :  Optional[int]							      =					minimum_tokens

      if "max_length" in generate_kwargs:
          lowerCAmelCase__ :  Optional[Any]							      =					generate_kwargs["""max_length"""]
          # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
      if clean_up_tokenization_spaces is not None:
          lowerCAmelCase__ :  int							      =					clean_up_tokenization_spaces

      if generate_kwargs:
          forward_params.update(__UpperCAmelCase      )
      return preprocess_params, forward_params, postprocess_params




  def __call__(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=0  ,**__UpperCAmelCase      )    ->		List[str]:
      lowerCAmelCase__ :  Optional[int]							      =					super().__call__(__UpperCAmelCase  ,num_workers=__UpperCAmelCase  ,**__UpperCAmelCase      )
      if isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ) and len(__UpperCAmelCase      ) == 1:
          return outputs[0]
      return outputs




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=32      )    ->		Dict[str, Any]:
      if not isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ):
          raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""      )
      if conversation.new_user_input is None:
          raise ValueError(
              F"""Conversation with UUID {type(conversation.uuid      )} does not contain new user input to process. """
              """Add user inputs with the conversation's `add_user_input` method"""      )
      if hasattr(self.tokenizer  ,"""_build_conversation_input_ids"""      ):
          lowerCAmelCase__ :  str							      =					self.tokenizer._build_conversation_input_ids(__UpperCAmelCase      )
      else:
          # If the tokenizer cannot handle conversations, we default to only the old version
          lowerCAmelCase__ :  List[Any]							      =					self._legacy_parse_and_tokenize(__UpperCAmelCase      )

      if self.framework == "pt":
          lowerCAmelCase__ :  List[Any]							      =					torch.LongTensor([input_ids]      )
      elif self.framework == "tf":
          lowerCAmelCase__ :  Dict							      =					tf.constant([input_ids]      )
      return {"input_ids": input_ids, "conversation": conversation}




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=10  ,**__UpperCAmelCase      )    ->		Dict:
      lowerCAmelCase__ :  Optional[Any]							      =					generate_kwargs.get("""max_length"""  ,self.model.config.max_length      )

      lowerCAmelCase__ :  Optional[Any]							      =					model_inputs["""input_ids"""].shape[1]
      if max_length - minimum_tokens < n:
          logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})"""      )
          lowerCAmelCase__ :  str							      =					max_length - minimum_tokens
          lowerCAmelCase__ :  Union[str, Any]							      =					model_inputs["""input_ids"""][:, -trim:]
          if "attention_mask" in model_inputs:
              lowerCAmelCase__ :  Tuple							      =					model_inputs["""attention_mask"""][:, -trim:]
      lowerCAmelCase__ :  str							      =					model_inputs.pop("""conversation"""      )
      lowerCAmelCase__ :  Union[str, Any]							      =					max_length
      lowerCAmelCase__ :  Any							      =					self.model.generate(**__UpperCAmelCase  ,**__UpperCAmelCase      )
      if self.model.config.is_encoder_decoder:
          lowerCAmelCase__ :  int							      =					1
      else:
          lowerCAmelCase__ :  int							      =					n
      return {"output_ids": output_ids[:, start_position:], "conversation": conversation}




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=True      )    ->		List[str]:
      lowerCAmelCase__ :  Optional[int]							      =					model_outputs["""output_ids"""]
      lowerCAmelCase__ :  Tuple							      =					self.tokenizer.decode(
          output_ids[0]  ,skip_special_tokens=__UpperCAmelCase  ,clean_up_tokenization_spaces=__UpperCAmelCase  ,)
      lowerCAmelCase__ :  Union[str, Any]							      =					model_outputs["""conversation"""]
      conversation.mark_processed()
      conversation.append_response(__UpperCAmelCase      )
      return conversation






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Dict:
      lowerCAmelCase__ :  Dict							      =					self.tokenizer.eos_token_id
      lowerCAmelCase__ :  int							      =					[]
      for is_user, text in conversation.iter_texts():
          if eos_token_id is not None:
              input_ids.extend(self.tokenizer.encode(__UpperCAmelCase  ,add_special_tokens=__UpperCAmelCase      ) + [eos_token_id]      )
          else:
              input_ids.extend(self.tokenizer.encode(__UpperCAmelCase  ,add_special_tokens=__UpperCAmelCase      )      )

      if len(__UpperCAmelCase      ) > self.tokenizer.model_max_length:
          lowerCAmelCase__ :  Optional[Any]							      =					input_ids[-self.tokenizer.model_max_length :]
      return input_ids


