
     `i6'                         d Z ddlmZmZ ddlZddlmZ ddlm	Z	m
Z
mZ ddlmZmZmZmZ ddlmZmZ dd	lmZ  ej        e          Z G d
 ded          Z G d de          ZdgZdS )z
Processor class for Llava.
    )OptionalUnionN   )BatchFeature)
ImageInputget_image_sizeto_numpy_array)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)loggingc                       e Zd Zdddi dZdS )LlavaProcessorKwargsF)paddingreturn_mm_token_type_ids)text_kwargsimages_kwargsN)__name__
__module____qualname__	_defaults     ~/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/llava/processing_llava.pyr   r   &   s(        #(eLL IIIr   r   F)totalc            
            e Zd ZdZddgZdZdZ	 	 	 	 	 	 	 d fd		Z	 	 	 	 dd
ee	         de
eeee         ee         f         dee         defdZddZ xZS )LlavaProcessoram  
    Constructs a LLaVa processor which wraps a LLaVa image processor and a LLaMa tokenizer into a single processor.

    [`LlavaProcessor`] offers all the functionalities of [`LlavaImageProcessor`] and [`LlamaTokenizerFast`]. See the
    [`~LlavaProcessor.__call__`] and [`~LlavaProcessor.decode`] for more information.

    Args:
        image_processor ([`LlavaImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`LlamaTokenizerFast`], *optional*):
            The tokenizer is a required input.
        patch_size (`int`, *optional*):
            Patch size from the vision tower.
        vision_feature_select_strategy (`str`, *optional*):
            The feature selection strategy used to select the vision feature from the vision backbone.
            Should be same as in model's config
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
        image_token (`str`, *optional*, defaults to `"<image>"`):
            Special token used to denote image location.
        num_additional_image_tokens (`int`, *optional*, defaults to 0):
            Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
            extra tokens appended, no need to set this arg.
    image_processor	tokenizerAutoImageProcessorAutoTokenizerN<image>r   c                    || _         || _        || _        t          |d          r|j        n|| _        |                    | j        d          d         | _        t                                          |||           d S )Nimage_tokenF)add_special_tokensr   )chat_template)	
patch_sizenum_additional_image_tokensvision_feature_select_strategyhasattrr'   encodeimage_token_idsuper__init__)
selfr!   r"   r*   r,   r)   r'   r+   kwargs	__class__s
            r   r1   zLlavaProcessor.__init__K   s     %+F(.L+4;I}4U4Uf900[f'..t/?TY.ZZ[\])=QQQQQr   imagestextr3   returnc                 Z   ||t          d           | j        t          fd| j        j        i|}| | j        |fi |d         }ni }t          |t                    r|g}n?t          |t                    s*t          |d         t                    st          d          |}|
                    d          |d         }	t          t          |	d                             \  }
}|
| j        z  || j        z  z  | j        z   }| j        dk    r|d	z  }g }|D ]:}|                    | j        | j        |z            }|                    |           ;|d
                             dd          }|d
                             dd          } | j        |fi |d
         ddi}|                     ||dg           |rYt+          j        |d                   }t+          j        |d                   }d	||| j        k    <   |                                |d<   t5          i |||          S )a  
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
        CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
        of the above two methods for more information.

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. Both channels-first and channels-last formats are supported.
            text (`str`, `list[str]`, `list[list[str]]`):
                The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
                (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
                `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:
                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.
                - `'jax'`: Return JAX `jnp.ndarray` objects.

        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
            - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
              `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
              `None`).
            - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
        Nz7You have to specify at least one of `images` or `text`.tokenizer_init_kwargsr   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesdefault   r   return_tensorsr   Fimage)
modalities	input_idsmm_token_type_ids)datatensor_type)
ValueError_merge_kwargsr   r"   init_kwargsr!   
isinstancestrlist	TypeErrorgetr   r	   r*   r+   r,   replacer'   appendpop_check_special_mm_tokensnparray
zeros_liker/   tolistr   )r2   r5   r6   audiovideosr3   output_kwargsimage_inputsprompt_stringsr:   heightwidthnum_image_tokenssampler=   r   text_inputs	array_idsrA   s                      r   __call__zLlavaProcessor.__call__]   s   N >dlVWWW** 
 
"&."<
 
 

 /4/YY-:XYYLLLdC   	a6DDD$'' 	a
47C0H0H 	a_``` N++7'7L*>,q/+J+JKKMFE &$/ 9( 0 1 2i?? A% N . .(8$:JM]:]^^%%f----&}599:JDQQ#0#?#C#CD^`e#f#f $dn^ii}]7Siidhiii%%nkwi%XXX# 	J[!9::I "k+.F G GBCi4+>>?/@/G/G/I/IK+,!@K!@<!@n]]]]r   c                    i }|t           j                            di           }|                    |           |                    dd          p| j        j        }|d         |d         }}|| j        z  || j        z  z  }|| j        z  }| j        dk    r|dz  }|gt          |          z  }dgt          |          z  }	|                    ||	d           t          d	i |S )
a  
        Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

        Args:
            image_sizes (`list[list[int]]`, *optional*):
                The input sizes formatted as (height, width) per each image.

        Returns:
            `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
            input modalities, along with other useful data.
        Nr   	crop_sizerY   rZ   r;   r<   )r[   num_image_patchesr   )r   r   rK   updater!   ra   r*   r+   r,   lenr
   )
r2   image_sizesr3   vision_datar   ra   resized_heightresized_widthr[   rb   s
             r   _get_num_multimodal_tokensz)LlavaProcessor._get_num_multimodal_tokens   s    "0:>>PRSSM  (((%))+t<<^@T@^I,5h,?7ASMN .$/ AmW[WfFfg @@2i?? A%  01C4D4DD!"c+&6&6 64D[lmmnnn,,,,,r   )NNNNNr%   r   )NNNN)N)r   r   r   __doc__
attributesimage_processor_classtokenizer_classr1   r   r   r   r   r   rI   r   r   r   r_   ri   __classcell__)r4   s   @r   r    r    -   s        2 $[1J0%O '+$%R R R R R R( (,^bU^ U^$U^ I0$y/4HYCZZ[U^ -.U^ 
U^ U^ U^ U^n- - - - - - - -r   r    )rj   typingr   r   numpyrP   feature_extraction_utilsr   image_utilsr   r   r	   processing_utilsr
   r   r   r   tokenization_utils_baser   r   utilsr   
get_loggerr   loggerr   r    __all__r   r   r   <module>ry      sU    # " " " " " " "     4 4 4 4 4 4 E E E E E E E E E E            D C C C C C C C       
	H	%	%    +5    d- d- d- d- d-^ d- d- d-N 
r   