o
    ei=2                     @   s   d dl mZmZ d dlmZmZmZ ddlmZ ddl	m
Z
mZ ddlmZmZ ddlmZmZ ddlmZmZ e r?d d	lZeeZG d
d deddZG dd deZdgZd	S )    )OptionalUnion)IMAGE_TOKENPaliGemmaProcessorbuild_string_from_input   )BatchFeature)
ImageInputmake_flat_list_of_images)ProcessingKwargsUnpack)PreTokenizedInput	TextInput)is_torch_availableloggingNc                   @   s&   e Zd ZddidddddidZd	S )
ColPaliProcessorKwargspaddinglongestchannels_firstT)data_formatdo_convert_rgbreturn_tensorspt)text_kwargsimages_kwargscommon_kwargsN)__name__
__module____qualname__	_defaults r    r    i/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/colpali/modular_colpali.pyr   !   s    
r   F)totalc                       s  e Zd Z					d dedef fddZedefd	d
Z		d!dedB dee	B e
e B e
e	 B dee defddZ	d"dedB dee defddZdee
e B dee defddZ			d#dede
d f dede
d f deded dedef ddfddZ  ZS )$ColPaliProcessorNDescribe the image.
Question: visual_prompt_prefixquery_prefixc                    s"   || _ || _t j|||d dS )a!  
        visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
            A string that gets tokenized and prepended to the image tokens.
        query_prefix (`str`, *optional*, defaults to `"Question: "`):
            A prefix to be used for the query.
        )image_processor	tokenizerchat_templateN)r&   r'   super__init__)selfr(   r)   r*   r&   r'   	__class__r    r!   r,   /   s   zColPaliProcessor.__init__returnc                 C   s   | j jS )z
        Return the query augmentation token.

        Query augmentation buffers are used as reasoning buffers during inference.
        )r)   	pad_tokenr-   r    r    r!   query_augmentation_tokenA   s   z)ColPaliProcessor.query_augmentation_tokenimagestextkwargsc                    s   j tfd jji|}|d dd}d}|du r#|du r#td|dur/|dur/td|dur j|}t|} j	gt
| }dd	 |D } fd
d	t||D } j|fi |d d }	|d dddurz|d d   j7  <  j|fd|i|d }
i |
d|	i}|r|
d |
d dkd}|d|i t|dS |durt|tr|g}nt|trt|d tstd|du rЈ jd }g }|D ]} jj j | | d }|| q|d dd|d d<  j|fd|i|d }|S dS )a  
        Returns:
            [`BatchFeature`]: A [`BatchFeature`] with the following fields:

            - **input_ids** -- List of token ids to be fed to a model.
            - **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`.
        tokenizer_init_kwargsr   suffixNTz&Either text or images must be providedz5Only one of text or images can be processed at a timec                 S   s   g | ]}| d qS )RGB)convert).0imager    r    r!   
<listcomp>l   s    z-ColPaliProcessor.__call__.<locals>.<listcomp>c              
      s:   g | ]\}}t | jj jtt|trt|nd dqS )   )prompt	bos_tokenimage_seq_lenimage_token
num_images)r   r)   r@   image_seq_lengthr   
isinstancelistlen)r;   r?   
image_listr2   r    r!   r=   n   s    r   pixel_values
max_lengthreturn_token_type_ids	input_idstoken_type_idsr   ilabels)dataz*Text must be a string or a list of strings
   
2   )_merge_kwargsr   r)   init_kwargspop
ValueErrorr(   fetch_imagesr
   r&   rG   zipgetrD   masked_fillupdater   rE   strrF   r3   r@   r'   append)r-   r4   r5   r6   output_kwargsr8   rK   	texts_docinput_stringsrI   inputsreturn_datarN   texts_queryquerybatch_queryr    r2   r!   __call__J   sr   





zColPaliProcessor.__call__c                 K      | j dd|i|S )a  
        Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
        [`ColPaliProcessor.__call__`].

        This method forwards the `images` and `kwargs` arguments to the image processor.

        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. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
                number of channels, H and W are image height and width.
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors of a particular framework. Acceptable values are:

                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.

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

            - **input_ids** -- List of token ids to be fed to a model.
            - **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`.
        r4   Nr    rf   )r-   r4   r6   r    r    r!   process_images   s   zColPaliProcessor.process_imagesc                 K   rg   )ag  
        Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
        [`ColPaliProcessor.__call__`].

        This method forwards the `text` and `kwargs` arguments to the tokenizer.

        Args:
            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:

                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return NumPy `np.ndarray` objects.

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

            - **input_ids** -- List of token ids to be fed to a model.
            - **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`).
        r5   Nr    rh   )r-   r5   r6   r    r    r!   process_queries   s   z ColPaliProcessor.process_queries   cpuquery_embeddingsztorch.Tensorpassage_embeddings
batch_sizeoutput_dtypeztorch.dtypeoutput_deviceztorch.devicec              	   C   s@  t |dkr
tdt |dkrtd|d j|d jkr"td|d j|d jkr0td|du r9|d j}g }tdt ||D ]U}g }tjjjj	||||  ddd}	tdt ||D ]'}
tjjjj	||
|
|  ddd}|
td	|	|jd
dd jdd q`|
tj|dd|| qCtj|ddS )aZ  
        Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
        query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
        image of a document page.

        Because the embedding tensors are multi-vector and can thus have different shapes, they
        should be fed as:
        (1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
        (2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
            obtained by padding the list of tensors.

        Args:
            query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
            passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
            batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
            output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
                If `None`, the dtype of the input embeddings is used.
            output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.

        Returns:
            `torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
            tensor is saved on the "cpu" device.
        r   zNo queries providedzNo passages providedz/Queries and passages must be on the same devicez-Queries and passages must have the same dtypeNT)batch_firstpadding_valuezbnd,csd->bcnsr   )dim   r>   )rG   rV   devicedtyperangetorchnnutilsrnnpad_sequencer]   einsummaxsumcatto)r-   rm   rn   ro   rp   rq   scoresibatch_scoresbatch_queriesjbatch_passagesr    r    r!   score_retrieval   s2    


 "z ColPaliProcessor.score_retrieval)NNNr$   r%   )NN)N)rk   Nrl   )r   r   r   r\   r,   propertyr3   r	   r   r   rF   r   r   r   rf   ri   rj   r   intr   r   __classcell__r    r    r.   r!   r#   .   sn    

\
!

$
r#   )typingr   r   2transformers.models.paligemma.processing_paligemmar   r   r   feature_extraction_utilsr   image_utilsr	   r
   processing_utilsr   r   tokenization_utils_baser   r   r{   r   r   ry   
get_loggerr   loggerr   r#   __all__r    r    r    r!   <module>   s   
 z