a
    h"'                     @   s   d Z ddl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eZG d
d deddZG dd deZdgZdS )z
Processor class for Llava.
    )UnionN   )BatchFeature)
ImageInputget_image_sizeto_numpy_array)MultiModalDataProcessingKwargsProcessorMixinUnpack)PreTokenizedInput	TextInput)loggingc                   @   s   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 r   r   f/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/llava/processing_llava.pyr   &   s   r   F)totalc                       sj   e Zd ZdZddgZdZdZd fd	d
	Zdee	e
eee
 ee f ee edddZdddZ  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	tokenizerZAutoImageProcessorZAutoTokenizerN<image>r   c           	         sT   || _ || _|| _t|dr"|jn|| _|j| jddd | _t j|||d d S )Nimage_tokenF)Z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__r   r   r(   K   s    zLlavaProcessor.__init__)imagestextr*   returnc                 K   s  |du r|du rt d| jtfd| jji|}|durR| j|fi |d }ni }t|trh|g}n t|tst|d tst	d|}|
ddur|d }	tt|	d \}
}|
| j || j  | j }| jdkr|d	8 }g }|D ]"}|| j| j| }|| q|d
 dd}|d
 dd}| j|fi |d
 ddi}| j||dgd |rt|d }t|d }d	||| jk< | |d< ti |||d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 `kwrags` 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`.Ztokenizer_init_kwargsr   r   zAInvalid input text. Please provide a string, or a list of stringspixel_valuesdefault   r   return_tensorsr   Fimage)Z
modalitiesZ	input_idsmm_token_type_ids)dataZtensor_type)
ValueErrorZ_merge_kwargsr   r   Zinit_kwargsr   
isinstancestrlist	TypeErrorgetr   r   r!   r"   r#   replacer   appendpopZ_check_special_mm_tokensnparrayZ
zeros_liker&   tolistr   )r)   r-   r.   ZaudioZvideosr*   Zoutput_kwargsZimage_inputsZprompt_stringsr0   heightwidthnum_image_tokenssampler3   r   Ztext_inputsZ	array_idsr5   r   r   r   __call__]   sR    '

zLlavaProcessor.__call__c           
      K   s   i }|durt jdi }|| |ddp6| jj}|d |d  }}|| j || j  }|| j7 }| jdkrz|d8 }|gt	| }dgt	| }	|||	d t
f 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_sizerC   rD   r1   r2   )rE   num_image_patches)r   r   r<   updater   rH   r!   r"   r#   lenr   )
r)   Zimage_sizesr*   Zvision_datar   rH   Zresized_heightZresized_widthrE   rI   r   r   r   _get_num_multimodal_tokens   s    


z)LlavaProcessor._get_num_multimodal_tokens)NNNNNr   r   )NNNN)N)r   r   r   __doc__
attributesZimage_processor_classZtokenizer_classr(   r   r   r   r   r:   r   r   r   rG   rL   __classcell__r   r   r+   r   r   -   s.              Wr   )rM   typingr   numpyr@   Zfeature_extraction_utilsr   Zimage_utilsr   r   r   Zprocessing_utilsr   r	   r
   r   Ztokenization_utils_baser   r   utilsr   Z
get_loggerr   loggerr   r   __all__r   r   r   r   <module>   s   
 (