Ë
    S^(h>  ã                   óð   — d dl mZmZ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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j2                  e«      Z G d
„ ded¬«      Z G d„ de«      ZdgZy	)é    )ÚClassVarÚListÚOptionalÚUnion)ÚIMAGE_TOKENÚPaliGemmaProcessorÚbuild_string_from_inputé   )ÚBatchFeature)Ú
ImageInputÚis_valid_imageÚmake_flat_list_of_images)ÚProcessingKwargsÚUnpack)ÚPreTokenizedInputÚ	TextInput)Úis_torch_availableÚloggingNc                   ó&   — e Zd ZddidddœddidœZy	)
ÚColPaliProcessorKwargsÚpaddingÚlongestÚchannels_firstT)Údata_formatÚdo_convert_rgbÚreturn_tensorsÚpt)Útext_kwargsÚimages_kwargsÚcommon_kwargsN)Ú__name__Ú
__module__Ú__qualname__Ú	_defaults© ó    úi/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/colpali/modular_colpali.pyr   r   0   s,   „ ð �yð
ð ,Ø"ñ
ð +¨DÐ1ñ	�Ir&   r   F)Útotalc                   ó2  — e Zd ZU dZdZee   ed<   dZee   ed<   e	defd„«       Z
	 	 	 	 dd	ed
eeeee   ee   f   dee   defd„Z	 dd	edee   defd„Zd
eeee   f   dee   def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„Zy)ÚColPaliProcessora×  
    Constructs a ColPali processor which wraps a PaliGemmaProcessor and special methods to process images and queries, as
    well as to compute the late-interaction retrieval score.

    [`ColPaliProcessor`] offers all the functionalities of [`PaliGemmaProcessor`]. See the [`~PaliGemmaProcessor.__call__`]
    for more information.

    Args:
        image_processor ([`SiglipImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`LlamaTokenizerFast`], *optional*):
            The tokenizer is a required input.
        chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
            in a chat into a tokenizable string.
    zDescribe the image.Úvisual_prompt_prefixz
Question: Úquery_prefixÚreturnc                 ó.   — | j                   j                  S )zŠ
        Return the query augmentation token.

        Query augmentation buffers are used as reasoning buffers during inference.
        )Ú	tokenizerÚ	pad_token)Úselfs    r'   Úquery_augmentation_tokenz)ColPaliProcessor.query_augmentation_tokenQ   s   € ð �~‰~×'Ñ'Ð'r&   NÚimagesÚtextÚkwargsc                 ó  —  | j                   t        fd| j                  j                  i|¤Ž}|d   j	                  dd«      }|�dnd}|€|€t        d«      ‚|�|�t        d«      ‚|��¼t        |«      r|g}n^t        |t        «      rt        |d	   «      rn?t        |t        «      r$t        |d	   t        «      rt        |d	   d	   «      st        d
«      ‚| j                  gt        |«      z  }	|D �
cg c]  }
|
j                  d«      ‘Œ }}
t        |	|«      D ��cg c]R  \  }}t        || j                  j                  | j                  t         t        |t        «      rt        |«      nd¬«      ‘ŒT }}}t#        |«      } | j$                  |fi |d   ¤Žd   }|d   j'                  dd«      �|d   dxx   | j                  z  cc<    | j                  |fddi|d   ¤Ž}i |¥d|i¥}|r.|d   j)                  |d   d	k(  d«      }|j+                  d|i«       t-        |¬«      S |�Òt        |t.        «      r|g}n.t        |t        «      rt        |d	   t.        «      st        d«      ‚|€| j0                  dz  }g }|D ]C  }| j                  j                  | j2                  z   |z   }||z  }|dz  }|j5                  |«       ŒE |d   j'                  dd«      |d   d<    | j                  |fddi|d   ¤Ž}|S yc c}
w c c}}w )aç	  
        Main method to prepare for the model either (1) one or several texts, either (2) one or several image(s). This method is custom
        wrapper around the PaliGemmaProcessor's [`~PaliGemmaProcessor.__call__`] method adapted for the ColPali model. It cannot process
        both text and images at the same time.

        When preparing the text(s), this method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's
        [`~LlamaTokenizerFast.__call__`].
        When preparing the image(s), this method forwards the `images` and `kwargs` arguments to SiglipImageProcessor's
        [`~SiglipImageProcessor.__call__`].
        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. 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.
            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.
            - **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   ÚsuffixNTFz&Either text or images must be providedz5Only one of text or images can be processed at a timer   zAimages must be an image, list of images or list of list of imagesÚRGBé   )ÚpromptÚ	bos_tokenÚimage_seq_lenÚimage_tokenÚ
num_imagesr   Úpixel_valuesÚ
max_lengthÚreturn_token_type_idsÚ	input_idsÚtoken_type_idsiœÿÿÿÚlabels)Údataz*Text must be a string or a list of stringsé
   ú
é2   )Ú_merge_kwargsr   r/   Úinit_kwargsÚpopÚ
ValueErrorr   Ú
isinstanceÚlistr+   ÚlenÚconvertÚzipr	   r<   Úimage_seq_lengthr   r   Úimage_processorÚgetÚmasked_fillÚupdater   Ústrr2   r,   Úappend)r1   r3   r4   ÚaudioÚvideosr5   Úoutput_kwargsr8   rB   Ú	texts_docÚimager;   Ú
image_listÚinput_stringsr@   ÚinputsÚreturn_datarE   Útexts_queryÚqueryÚbatch_querys                        r'   Ú__call__zColPaliProcessor.__call__Z   sq  € ðZ +˜×*Ñ*Ü"ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð
 ˜}Ñ-×1Ñ1°(¸DÓAˆà(.Ð(:¡ÀÐàˆ<˜F˜NÜÐEÓFÐFØÐ Ð 2ÜÐTÓUÐUàÑÜ˜fÔ%Ø ˜‘Ü˜F¤DÔ)¬n¸VÀA¹YÔ.GØÜ  ¬Ô.´:¸fÀQ¹iÌÔ3NÔSaÐbhÐijÑbkÐlmÑbnÔSoÜ Ð!dÓeÐeà×2Ñ2Ð3´c¸&³kÑAˆIØ8>Ö?¨u�e—m‘m EÕ*Ð?ˆFÐ?ô +.¨i¸Ó*@÷	ñ '�F˜Jô (Ø!Ø"Ÿn™n×6Ñ6Ø"&×"7Ñ"7Ü +Ü2<¸ZÌÔ2Nœs :œÐTUöð	ˆMñ 	ô .¨fÓ5ˆFØ/˜4×/Ñ/°ÑY¸-ÈÑ:XÑYÐZhÑiˆLð ˜]Ñ+×/Ñ/°¸dÓCÐOØ˜mÑ,¨\Ó:¸d×>SÑ>SÑSÓ:à#�T—^‘^Øñà&+ðð   Ñ.ñˆFð C˜VÐB ^°\ÑBˆKá$Ø Ñ,×8Ñ8¸Ð@PÑ9QÐUVÑ9VÐX\Ó]�Ø×"Ñ" H¨fÐ#5Ô6ä [Ô1Ð1àÐÜ˜$¤Ô$Ø�v‘Ü  ¤tÔ,´¸DÀ¹GÄSÔ1IÜ Ð!MÓNÐNàˆ~Ø×6Ñ6¸Ñ;�Ø%'ˆKàò *�ØŸ™×0Ñ0°4×3DÑ3DÑDÀuÑL�Ø˜‘�Ø˜‘�Ø×"Ñ" 5Õ)ð	*ð :GÀ}Ñ9U×9YÑ9YÐZfÐhjÓ9kˆM˜-Ñ(¨Ñ6à(˜$Ÿ.™.Øñà&+ðð   Ñ.ñˆKð Ðð1 ùòC @ùó	s   Ã4K;ÄAL c                 ó*   —  | 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 SiglipImageProcessor's [`~SiglipImageProcessor.__call__`].

        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:

                - `'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.
            - **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`.
        r3   r%   ©rf   )r1   r3   r5   s      r'   Úprocess_imageszColPaliProcessor.process_imagesÙ   s   € ðB ˆt�}‰}Ñ5 FÐ5¨fÑ5Ð5r&   c                 ó*   —  | j                   dd|i|¤ŽS )a  
        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 LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`].

        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:

                - `'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.
            - **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`).
        r4   r%   rh   )r1   r4   r5   s      r'   Úprocess_queriesz ColPaliProcessor.process_queriesü   s   € ð@ ˆt�}‰}Ñ1 $Ð1¨&Ñ1Ð1r&   Úquery_embeddingsztorch.TensorÚpassage_embeddingsÚ
batch_sizeÚoutput_dtypeztorch.dtypeÚoutput_deviceztorch.devicec           	      óà  — t        |«      dk(  rt        d«      ‚t        |«      dk(  rt        d«      ‚|d   j                  |d   j                  k7  rt        d«      ‚|d   j                  |d   j                  k7  rt        d«      ‚|€|d   j                  }g }t	        dt        |«      |«      D �]%  }g }t
        j                  j                  j                  j                  ||||z    dd¬«      }	t	        dt        |«      |«      D ]‡  }
t
        j                  j                  j                  j                  ||
|
|z    dd¬«      }|j                  t        j                  d|	|«      j                  d	¬
«      d   j                  d¬
«      «       Œ‰ |j                  t        j                  |d¬
«      j                  |«      j                  |«      «       �Œ( t        j                  |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 dtypeT)Úbatch_firstÚpadding_valuezbnd,csd->bcnsr
   )Údimé   r:   )rP   rM   ÚdeviceÚdtypeÚrangeÚtorchÚnnÚutilsÚrnnÚpad_sequencerY   ÚeinsumÚmaxÚsumÚcatÚto)r1   rl   rm   rn   ro   rp   ÚscoresÚiÚbatch_scoresÚbatch_queriesÚjÚbatch_passagess               r'   Úscore_retrievalz ColPaliProcessor.score_retrieval  sâ  € ô@ ÐÓ  AÒ%ÜÐ2Ó3Ð3ÜÐ!Ó" aÒ'ÜÐ3Ó4Ð4à˜AÑ×%Ñ%Ð);¸AÑ)>×)EÑ)EÒEÜÐNÓOÐOà˜AÑ×$Ñ$Ð(:¸1Ñ(=×(CÑ(CÒCÜÐLÓMÐMàÐØ+¨AÑ.×4Ñ4ˆLà%'ˆä�qœ#Ð.Ó/°Ó<ó 	]ˆAØ/1ˆLÜ!ŸH™HŸN™N×.Ñ.×;Ñ;Ø   Q¨¡^Ð4À$ÐVWð <ó ˆMô ˜1œcÐ"4Ó5°zÓBò �Ü!&§¡§¡×!3Ñ!3×!@Ñ!@Ø& q¨1¨z©>Ð:ÈÐ\]ð "Aó "�ð ×#Ñ#Ü—L‘L °-ÀÓP×TÑTÐYZÐTÓ[Ð\]Ñ^×bÑbÐghÐbÓiõð	ð �M‰Mœ%Ÿ)™) L°aÔ8×;Ñ;¸LÓI×LÑLÈ]Ó[Ö\ð	]ô �y‰y˜ QÔ'Ð'r&   )NNNN)N)é€   NÚcpu)r!   r"   r#   Ú__doc__r+   r   rX   Ú__annotations__r,   Úpropertyr2   r   r   r   r   r   r   r   r   rf   ri   rk   Úintr   r‰   r%   r&   r'   r*   r*   =   sx  … ñð  +@Ð˜( 3™-Ó?Ø".€L�(˜3‘-Ó.àð(¨#ò (ó ð(ð "Ø^bØØñ}àð}ð �IÐ0°$°y±/À4ÐHYÑCZÐZÑ[ð}ð Ð/Ñ0ð}ð 
ó}ðB "ñ!6àð!6ð Ð/Ñ0ð!6ð 
ó	!6ðF 2à�I˜t I™Ð.Ñ/ð 2ð Ð/Ñ0ð 2ð 
ó	 2ðL Ø04Ø49ñ>(à °°^Ñ0DÐ DÑEð>(ð " .°$°~Ñ2FÐ"FÑGð>(ð ð	>(ð
 ˜}Ñ-ð>(ð ˜^¨SÐ0Ñ1ð>(ð 
ô>(r&   r*   )Útypingr   r   r   r   Ú2transformers.models.paligemma.processing_paligemmar   r   r	   Úfeature_extraction_utilsr   Úimage_utilsr   r   r   Úprocessing_utilsr   r   Útokenization_utils_baser   r   r{   r   r   ry   Ú
get_loggerr!   Úloggerr   r*   Ú__all__r%   r&   r'   ú<module>r™      s{   ð÷" 3Ó 2÷ñ õ 5ß OÑ O÷÷÷ñ ÔÛð 
ˆ×	Ñ	˜HÓ	%€ô
Ð-°Uõ 
ô_(Ð)ô _(ðF	 ð�r&   