Ë
    ÛÓ^jA  ã                   ó¾   — d dl mZmZ ddlmZ ddl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mZ  e«       rd dlZ G d	„ d
e
d¬«      Ze G d„ de«      «       ZdgZy)é    )ÚOptionalÚUnioné   )ÚBatchFeature)Ú
ImageInputÚis_valid_image)ÚMultiModalDataÚProcessingKwargsÚProcessorMixinÚUnpack)ÚPreTokenizedInputÚ	TextInput)Úauto_docstringÚis_torch_availableNc                   ó&   — e Zd ZddidddœddidœZy	)
ÚColQwen2ProcessorKwargsÚpaddingÚlongestÚchannels_firstT)Údata_formatÚdo_convert_rgbÚreturn_tensorsÚpt)Útext_kwargsÚimages_kwargsÚcommon_kwargsN)Ú__name__Ú
__module__Ú__qualname__Ú	_defaults© ó    ú{/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/colqwen2/processing_colqwen2.pyr   r   "   s,   „ ð �yð
ð ,Ø"ñ
ð +¨DÐ1ñ	�Ir"   r   F)Útotalc                   ób  ‡ — e Zd Z	 	 	 	 	 ddedz  dedz  fˆ fd„Ze	 	 ddedz  deez  e	e   z  e	e   z  de
e   defd	„«       Zdd
„Zed„ «       Zedefd„«       Z	 ddedz  de
e   defd„Zdee	e   z  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ˆ xZS )ÚColQwen2ProcessorNÚvisual_prompt_prefixÚquery_prefixc                 óÒ   •— t         ‰| �  |||¬«       t        |d«      sdn|j                  | _        t        |d«      sdn|j                  | _        |xs d| _        |xs d| _        y)	ar  
        visual_prompt_prefix (`str`, *optional*, defaults to `"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>"`):
            A string that gets tokenized and prepended to the image tokens.
        query_prefix (`str`, *optional*, defaults to `"Query: "`):
            A prefix to be used for the query.
        )Úchat_templateÚimage_tokenz<|image_pad|>Úvideo_tokenz<|video_pad|>zf<|im_start|>user
<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|><|endoftext|>zQuery: N)ÚsuperÚ__init__Úhasattrr+   r,   r'   r(   )ÚselfÚimage_processorÚ	tokenizerr*   r'   r(   ÚkwargsÚ	__class__s          €r#   r.   zColQwen2Processor.__init__1   so   ø€ ô 	‰Ñ˜¨)À=ÐÔQÜ29¸)À]Ô2S™?ÐYb×YnÑYnˆÔÜ29¸)À]Ô2S™?ÐYb×YnÑYnˆÔà$8ò %
Øuð 	Ô!ð )Ò5¨IˆÕr"   ÚimagesÚtextr3   Úreturnc                 óv  —  | j                   t        fd| j                  j                  i|¤Ž}|d   j	                  dd«      }|du}|€|€t        d«      ‚|�|�t        d«      ‚|��7t        |«      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  } | j                  dd	|i|d
   ¤Ž}|d   }	|	�¸| j                  j                  dz  }
d}t        t        |«      «      D ]†  }| j                  ||   v rQ||   j                  | j                  d|	|   j!                  «       |
z  z  d«      ||<   |dz  }| j                  ||   v rŒQ||   j                  d| j                  «      ||<   Œˆ  | j                  |fddi|d   ¤Ž}t#        i |¥|¥¬«      }|d   dd…df   |d   dd…df   z  }t        t%        j&                  |d   |j)                  «       «      «      }t$        j*                  j,                  j.                  j1                  |d¬«      |d<   |r.|d   j3                  |d   dk(  d«      }|j5                  d|i«       |S |�™t        |t6        «      r|g}n.t        |t        «      rt        |d   t6        «      st        d«      ‚|€| j8                  dz  }g }|D ]%  }| j:                  |z   |z   }|j=                  |«       Œ'  | j                  |fddi|d   ¤Ž}|S y)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   ÚsuffixNz&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 imagesr5   r   Úimage_grid_thwé   z<|placeholder|>é   Úreturn_token_type_idsF)ÚdataÚpixel_valuesT)Úbatch_firstÚ	input_idsÚtoken_type_idsiœÿÿÿÚlabelsz*Text must be a string or a list of stringsé
   r!   )Ú_merge_kwargsr   r2   Úinit_kwargsÚpopÚ
ValueErrorr   Ú
isinstanceÚlistr'   Úlenr1   Ú
merge_sizeÚranger+   ÚreplaceÚprodr   ÚtorchÚsplitÚtolistÚnnÚutilsÚrnnÚpad_sequenceÚmasked_fillÚupdateÚstrÚquery_augmentation_tokenr(   Úappend)r0   r5   r6   r3   Úoutput_kwargsr:   r>   Ú	texts_docÚimage_inputsr;   Úmerge_lengthÚindexÚiÚtext_inputsÚreturn_dataÚoffsetsr@   rD   Útexts_queryÚqueryÚaugmented_queryÚbatch_querys                         r#   Ú__call__zColQwen2Processor.__call__I   sÂ  € ð" +˜×*Ñ*Ü#ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð
 ˜}Ñ-×1Ñ1°(¸DÓAˆà &¨dÐ 2Ðàˆ<˜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à/˜4×/Ñ/Ñ`°vÐ`ÀÈÑA_Ñ`ˆLØ)Ð*:Ñ;ˆNàÐ)Ø#×3Ñ3×>Ñ>ÀÑA�Ø�Üœs 9›~Ó.ò ]�AØ×*Ñ*¨i¸©lÑ:Ø'0°¡|×';Ñ';Ø ×,Ñ,Ð.?À>ÐRWÑCX×C]ÑC]ÓC_ÐcoÑCoÑ.pÐrsó(˜	 !™ð  ™
˜ð	 ×*Ñ*¨i¸©lÒ:ð
 $-¨Q¡<×#7Ñ#7Ð8IÈ4×K[ÑK[Ó#\�I˜a’Lð]ð )˜$Ÿ.™.Øñà&+ðð   Ñ.ñˆKô 'Ð,K¨{Ð,K¸lÐ,KÔLˆKð "Ð"2Ñ3²A°q°DÑ9¸KÐHXÑ<YÒZ[Ð]^ÐZ^Ñ<_Ñ_ˆGô  Ü—‘˜K¨Ñ7¸¿¹Ó9IÓJóˆLô
 +0¯(©(¯.©.×*<Ñ*<×*IÑ*IØ¨$ð +Jó +ˆK˜Ñ'ñ %Ø$ [Ñ1×=Ñ=¸kÐJZÑ>[Ð_`Ñ>`ÐbfÓg�Ø×"Ñ" H¨fÐ#5Ô6àÐàÐÜ˜$¤Ô$Ø�v‘Ü  ¤tÔ,´¸DÀ¹GÄSÔ1IÜ Ð!MÓNÐNàˆ~Ø×6Ñ6¸Ñ;�à%'ˆKàò 4�Ø"&×"3Ñ"3°eÑ";¸fÑ"D�Ø×"Ñ" ?Õ3ð4ð )˜$Ÿ.™.Øñà&+ðð   Ñ.ñˆKð Ðð+ r"   c                 ó’  — i }|�¯t         j                  j                  di «      }|j                  |«       |j                  dd«      xs | j                  j
                  }|D �cg c]   } | j                  j                  g |¢|‘­Ž ‘Œ" }}|D �cg c]
  }||dz  z  ‘Œ }	}|j                  |	|dœ«       t        di |¤ŽS c c}w c c}w )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   rM   r<   )Únum_image_tokensÚnum_image_patchesr!   )r   r    ÚgetrY   r1   rM   Úget_number_of_image_patchesr	   )
r0   Úimage_sizesr3   Úvision_datar   rM   Ú
image_sizerm   Únum_patchesrl   s
             r#   Ú_get_num_multimodal_tokensz,ColQwen2Processor._get_num_multimodal_tokens²   sä   € ð ˆØÐ"Ü3×=Ñ=×AÑAÀ/ÐSUÓVˆMØ× Ñ  Ô(Ø&×*Ñ*¨<¸Ó>ÒaÀ$×BVÑBV×BaÑBaˆJð #.ö!àð A�×$Ñ$×@Ñ@Ð\À*Ð\ÈmÔ\ð!Ðð !ð SdÖdÀ; °
¸A±Ó!=ÐdÐÐdØ×ÑÐ4DÐ[lÑmÔnäÑ, Ñ,Ð,ùò!ùò  es   Á$%B?ÂCc                 ó–   — | j                   j                  }| j                  j                  }|D �cg c]	  }|dvsŒ|‘Œ }}||z   S c c}w )N)Úpixel_values_videosÚvideo_grid_thw)r2   Úmodel_input_namesr1   )r0   Útokenizer_input_namesÚimage_processor_input_namesÚnames       r#   rx   z#ColQwen2Processor.model_input_namesÌ   s\   € à $§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#ð
 9ö'
Ø¸DÐHqÒ<qŠDð'
Ð#ð '
ð %Ð'BÑBÐBùò'
s
   ±	A»Ac                 ó.   — | j                   j                  S )zŠ
        Return the query augmentation token.

        Query augmentation buffers are used as reasoning buffers during inference.
        )r2   Ú	pad_token)r0   s    r#   r[   z*ColQwen2Processor.query_augmentation_tokenØ   s   € ð �~‰~×'Ñ'Ð'r"   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 ColQwen2Processor's
        [`ColQwen2Processor.__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`.
        r5   r!   ©rj   )r0   r5   r3   s      r#   Úprocess_imagesz ColQwen2Processor.process_imagesá   s   € ð> ˆt�}‰}Ñ5 FÐ5¨fÑ5Ð5r"   c                 ó*   —  | j                   dd|i|¤ŽS )ai  
        Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColQwen2Processor's
        [`ColQwen2Processor.__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`).
        r6   r!   r   )r0   r6   r3   s      r#   Úprocess_queriesz!ColQwen2Processor.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 )a[  
        Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
        query embeddings (`qs`) and passage embeddings (`ps`). For ColQwen2, 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)rA   Úpadding_valuezbnd,csd->bcnsr   )Údimr<   r=   )rL   rI   ÚdeviceÚdtyperN   rQ   rT   rU   rV   rW   r\   ÚeinsumÚmaxÚsumÚcatÚto)r0   rƒ   r„   r…   r†   r‡   Úscoresrb   Úbatch_scoresÚbatch_queriesÚjÚbatch_passagess               r#   Úscore_retrievalz!ColQwen2Processor.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"   )NNNNN)NN)N)é€   NÚcpu)r   r   r   rZ   r.   r   r   r   r   rK   r   r   r   rj   rt   Úpropertyrx   r[   r€   r‚   r   Úintr   r—   Ú__classcell__)r4   s   @r#   r&   r&   /   s³  ø„ ð ØØØ+/Ø#'ñ6ð
 " D™jð6ð ˜D‘jõ6ð0 ð %)ØZ^ñfà˜TÑ!ðfð Ð+Ñ+¨d°9©oÑ=ÀÐEVÑ@WÑWðfð Ð0Ñ1ð	fð
 
òfó ðfóP-ð4 ñ	Có ð	Cð ð(¨#ò (ó ð(ð %)ñ6à˜TÑ!ð6ð Ð0Ñ1ð6ð 
ó	6ðB2à˜$˜y™/Ñ)ð2ð Ð0Ñ1ð2ð 
ó	2ðH Ø04Ø49ñ>(à °°^Ñ0DÐ DÑEð>(ð " .°$°~Ñ2FÐ"FÑGð>(ð ð	>(ð
 ˜}Ñ-ð>(ð ˜^¨SÐ0Ñ1ð>(ð 
÷>(r"   r&   )Útypingr   r   Úfeature_extraction_utilsr   Úimage_utilsr   r   Úprocessing_utilsr	   r
   r   r   Útokenization_utils_baser   r   rU   r   r   rQ   r   r&   Ú__all__r!   r"   r#   ú<module>r£      s_   ð÷* #å 4ß 5ß XÓ Xß Cß 7ñ ÔÛô
Ð.°eõ 
ð ôp(˜ó p(ó ðp(ðf	 Ð
�r"   