Ë
    T^(hG<  ã                   ó¦  — d 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mZmZmZmZ ddlmZmZmZ ddlmZ  ej0                  e«      Zd	Z ed
«      D � cg c]	  } d| d›d�‘Œ c}  ed«      D � cg c]	  } d| d›d�‘Œ c} z   Z G d„ de«      Z G d„ de«      Z G d„ ded¬«      Z de!fd„Z"d„ Z#d„ Z$d„ Z% G d„ de«      Z&dgZ'y c c} w c c} w )!z 
Processor class for PaliGemma.
é    )ÚListÚOptionalÚUnioné   )ÚBatchFeature)Ú
ImageInputÚis_valid_imageÚmake_flat_list_of_images)ÚImagesKwargsÚProcessingKwargsÚProcessorMixinÚ
TextKwargsÚUnpackÚ!_validate_images_text_input_order)Ú
AddedTokenÚPreTokenizedInputÚ	TextInput)Úloggingz<image>i   z<locz0>4ú>é€   z<segz0>3c                   ó8   — e Zd ZU eeeeee   ee   f      ed<   y)ÚPaliGemmaTextKwargsÚsuffixN)	Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   Ú__annotations__© ó    úp/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/paligemma/processing_paligemma.pyr   r   -   s&   … Ø�U˜9Ð&7¸¸i¹È$ÐO`ÑJaÐaÑbÑcÔcr   r   c                   ó   — e Zd ZU ee   ed<   y)ÚPaliGemmaImagesKwargsÚdo_convert_rgbN)r   r   r   r   Úboolr   r   r   r    r"   r"   1   s   … Ø˜T‘NÔ"r   r"   c                   ó4   — e Zd ZU eed<   eed<   ddiddidœZy)	ÚPaliGemmaProcessorKwargsÚtext_kwargsÚimages_kwargsÚpaddingFÚdata_formatÚchannels_first)r'   r(   N)r   r   r   r   r   r"   Ú	_defaultsr   r   r    r&   r&   5   s.   … Ø$Ó$Ø(Ó(ð �uð
ð Ð+ð
ñ	�Ir   r&   F)ÚtotalÚreturnc                 óH   — t        | t        «      xr | j                  d«      S )NÚhttp)Ú
isinstanceÚstrÚ
startswith)Úvals    r    Úis_urlr5   C   s   € Ü�cœ3ÓÒ: C§N¡N°6Ó$:Ð:r   c                 ó2   — t        | «      xs t        | «      S ©N)r5   r	   ©Úelems    r    Úis_image_or_image_urlr:   H   s   € Ü�$‹<Ò/œ>¨$Ó/Ð/r   c                 ó<   — t        | t        «      xs t        | «      S r7   )r1   r2   r:   r8   s    r    Ú_is_str_or_imager<   L   s   € Ü�dœSÓ"ÒAÔ&;¸DÓ&AÐAr   c                 ó    — ||z  |z  › |› | › d�S )aZ  
    Builds a string from the input prompt and image tokens.
    For example, for the call:
    build_string_from_input(
        prompt="Prefix str"
        bos_token="<s>",
        image_seq_len=3,
        image_token="<im>",
    )
    The output will be:
    "<im><im><im><s>Initial str"
    Args:
        prompt (`List[Union[str, ImageInput]]`): The input prompt.
        bos_token (`str`): The beginning of sentence token.
        image_seq_len (`int`): The length of the image sequence.
        image_token (`str`): The image token.
        num_images (`int`): Number of images in the prompt.
    ú
r   ©ÚpromptÚ	bos_tokenÚimage_seq_lenÚimage_tokenÚ
num_imagess        r    Úbuild_string_from_inputrE   P   s$   € ð& ˜MÑ)¨JÑ6Ð7¸	°{À6À(È"ÐMÐMr   c            
       óž   ‡ — e Zd ZdZddgZdgZdZdZ	 	 	 dˆ fd„	Z	 	 	 	 dde	d	e
eeee   ee   f   d
ee   defd„Zd„ Zd„ Zed„ «       Zˆ xZS )ÚPaliGemmaProcessoraâ  
    Constructs a PaliGemma processor which wraps a PaliGemma image processor and a PaliGemma tokenizer into a single processor.

    [`PaliGemmaProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GemmaTokenizerFast`]. See the
    [`~PaliGemmaProcessor.__call__`] and [`~PaliGemmaProcessor.decode`] for more information.

    Args:
        image_processor ([`SiglipImageProcessor`], *optional*):
            The image processor is a required input.
        tokenizer ([`GemmaTokenizerFast`], *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.
    Úimage_processorÚ	tokenizerÚchat_template)ÚSiglipImageProcessorÚSiglipImageProcessorFast)ÚGemmaTokenizerÚGemmaTokenizerFastc                 ó´  •— |€t        d«      ‚|€t        d«      ‚t        |d«      st        d«      ‚|j                  | _        t        |d«      sCt        t        dd¬«      }d	|gi}|j                  |«       |j                  t        «      | _        n|j                  | _        |j                  t        «       d|_
        d|_        t        ‰| �5  |||¬
«       y )Nz)You need to specify an `image_processor`.z"You need to specify a `tokenizer`.Úimage_seq_lengthz;Image processor is missing an `image_seq_length` attribute.rC   FT)Ú
normalizedÚspecialÚadditional_special_tokens)rJ   )Ú
ValueErrorÚhasattrrP   r   ÚIMAGE_TOKENÚadd_special_tokensÚconvert_tokens_to_idsÚimage_token_idÚ
add_tokensÚEXTRA_TOKENSÚadd_bos_tokenÚadd_eos_tokenÚsuperÚ__init__)ÚselfrH   rI   rJ   ÚkwargsrC   Útokens_to_addÚ	__class__s          €r    r_   zPaliGemmaProcessor.__init__{   sÓ   ø€ ð Ð"ÜÐHÓIÐIØÐÜÐAÓBÐBÜ�Ð(:Ô;ÜÐZÓ[Ð[à /× @Ñ @ˆÔä�y -Ô0Ü$¤[¸UÈDÔQˆKØ8¸;¸-ÐHˆMØ×(Ñ(¨Ô7Ø"+×"AÑ"AÄ+Ó"NˆDÕà"+×":Ñ":ˆDÔà×Ñœ\Ô*Ø"'ˆ	ÔØ"'ˆ	Ôä‰Ñ˜¨)À=ÐÕQr   ÚimagesÚtextra   r.   c                 óž  — t        ||«      \  }} | j                  t        fd| j                  j                  i|¤Ž}|d   j                  dd«      }|�dnd}|€t        d«      ‚|€t        j                  d«       d	}t        |«      r|g}nt        |t        «      rt        |d
   «      r	 |��.|��+t        d„ |D «       «      �sut        j                  d«       t        |t        «      rKt        |t        «      r;t        |«      t        |«      k7  r$t        dt        |«      › dt        |«      › d�«      ‚t!        |«      r|gg}n€t        |t        t"        f«      rt!        |d
   «      r|D �	cg c]  }	|	g‘Œ }}	nKt        |t        t"        f«      r*t        |d
   t        t"        f«      rt!        |d
   d
   «      st        d«      ‚t%        ||«      D �
�cg c]R  \  }
}t'        |
| j                  j(                  | j*                  t,        t        |t        «      rt        |«      nd¬«      ‘ŒT }}
}t/        |«      }n£g }|D ]Š  }|j1                  t,        t,        | j*                  z  «      }|j3                  t,        «      }|dk7  r|t        t,        «      z   nd
}|d| | j                  j(                  z   ||d z   }|j5                  |«       ŒŒ |D �cg c]  }|› d�‘Œ	 }}|�t        |«      r|g}|�&|D �cg c]  }|| j                  j6                  z   ‘Œ }} | j8                  |fi |d   ¤Žd   }|d   j;                  dd«      �|d   dxx   | j*                  z  cc<    | j                  f||dœ|d   ¤Ž}i |¥d|i¥}|r.|d   j=                  |d   d
k(  d«      }|j?                  d|i«       tA        |¬«      S c c}	w c c}}
w c c}w c c}w )ah  
        Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
        and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode
        the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
        SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
        of the above two methods for more information.

        The usage for PaliGemma fine-tuning preparation is slightly different than usual. suffix passed are suffixes to
        the prompt in `text`, and will be placed after the prompt. This is because attention is handled differently for
        the prefix and the suffix. For instance,
        ```python
        image = PIL_cow_image
        prompt = "answer en Where is the cow standing?"
        suffix = "on the beach"
        inputs = processor(text=prompt, images=image, suffix=suffix)
        ```
        Here `inputs` will contain the `input_ids` and `token_type_ids` that follow
        ```python
        inputs["input_ids"][:, 256:]
        # tensor([[     2,   6006,    603,    573,  13910,   9980, 235336,    108,    477,   573,   8318]])
        inputs["token_type_ids"][:, 256:]
        tensor([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
        ```
        Meaning the last three tokens are of "label" ("suffix") type while the other ones are of "prefix" type.


        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.
            suffix (`str`, `List[str]`, `List[List[str]]`):
                The suffixes or batch of suffixes to be encoded. Only necessary for finetuning. See https://github.com/google-research/big_vision/blob/main/big_vision/configs/proj/paligemma/README.md
                for more information. If your prompt is "<image> What is on the image", the suffix corresponds to the expected prediction "a cow sitting on a bench".

        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`. If `suffix`
              is provided, the `input_ids` will also contain the suffix input ids.
            - **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`.
            - **labels** -- Labels compatible with training if `suffix` is not None
        Útokenizer_init_kwargsr'   r   NTFzF`images` are expected as arguments to a `PaliGemmaProcessor` instance.z]You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.Ú r   c              3   ó,   K  — | ]  }t         |v –— Œ y ­wr7   )rV   )Ú.0Úsamples     r    ú	<genexpr>z.PaliGemmaProcessor.__call__.<locals>.<genexpr>ô   s   è ø€ Ò@°”{ fÔ,Ñ@ùs   ‚aL  You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens.z	Received z images for zK prompts. Each prompt should be associated with an image or list of images.zAimages must be an image, list of images or list of list of imagesé   r?   éÿÿÿÿr>   r(   Úpixel_valuesÚ
max_length)Ú	text_pairÚreturn_token_type_idsÚ	input_idsÚtoken_type_idsiœÿÿÿÚlabels)Údata)!r   Ú_merge_kwargsr&   rI   Úinit_kwargsÚpoprT   ÚloggerÚwarning_oncer<   r1   ÚlistÚanyÚwarningr   Úlenr	   ÚtupleÚziprE   rA   rP   rV   r
   ÚreplaceÚrfindÚappendÚ	eos_tokenrH   ÚgetÚmasked_fillÚupdater   )r`   rd   re   ÚaudioÚvideosra   Úoutput_kwargsr   rr   Úimager@   Ú
image_listÚinput_stringsÚexpanded_samplesrk   Úexpanded_sampleÚbos_rfind_indexÚ	bos_indexÚsfxro   ÚinputsÚreturn_dataru   s                          r    Ú__call__zPaliGemmaProcessor.__call__™   s  € ôD 9¸ÀÓF‰ˆ�à*˜×*Ñ*Ü$ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð
 ˜}Ñ-×1Ñ1°(¸DÓAˆà(.Ð(:¡ÀÐàˆ>ÜÐeÓfÐfØˆ<Ü×ÑØoôð ˆDä˜DÔ!Ø�6‰DÜ˜œdÔ#Ô(8¸¸a¹Ô(AØàÑ Ñ 2ÜÑ@¸4Ô@Õ@Ü—‘ð<ôô ˜d¤DÔ)¬j¸ÄÔ.FÜ˜6“{¤c¨$£iÒ/Ü(Ø'¬¨F« }°LÄÀTÃÀð  LWð  Xóð ô
 " &Ô)Ø%˜h˜Z‘FÜ ¬¬u¨Ô6¼>È&ÐQRÉ)Ô;TØ39Ö:¨%˜ušgÐ:�FÑ:ä˜v¬¬e }Ô5Ü" 6¨!¡9¬t´U¨mÔ<Ü& v¨a¡y°¡|Ô4ä$Ð%hÓiÐiô /2°$¸Ó.?÷	!ñ +˜ 
ô ,Ø%Ø"&§.¡.×":Ñ":Ø&*×&;Ñ&;Ü$/Ü6@ÀÌTÔ6R¤3 z¤?ÐXYöð	!�ñ 	!ô 2°&Ó9‘à#%Ð Ø"ò =�FØ&,§n¡n´[Ä+ÐPT×PeÑPeÑBeÓ&f�OØ&5×&;Ñ&;¼KÓ&H�OØFUÐY[ÒF[ ´#´kÓ2BÒ BÐab�Ià'¨
¨Ð3°d·n±n×6NÑ6NÑNÐQ`ÐajÐakÐQlÑlð $ð %×+Ñ+¨OÕ<ð=ð >NÖ N°6 F 8¨2¢Ð N�Ð NàÐÔ"2°6Ô":Ø�XˆFØÐØ@FÖG¸�c˜DŸN™N×4Ñ4Ó4ÐGˆFÐGØ+�t×+Ñ+¨FÑU°mÀOÑ6TÑUÐVdÑeˆð ˜Ñ'×+Ñ+¨L¸$Ó?ÐKØ˜-Ñ(¨Ó6¸$×:OÑ:OÑOÓ6à�—‘Øð
àØ"7ñ
ð ˜MÑ*ñ	
ˆð ?˜Ð> °Ñ>ˆá Ø˜KÑ(×4Ñ4°VÐ<LÑ5MÐQRÑ5RÐTXÓYˆFØ×Ñ ¨&Ð1Ô2Ü Ô-Ð-ùòk ;ùó	!ùò* !Oùò
 Hs   Å-
N:ÇAN?ËOË3 O
c                 ó:   —  | j                   j                  |i |¤ŽS )zÂ
        This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )rI   Úbatch_decode©r`   Úargsra   s      r    r˜   zPaliGemmaProcessor.batch_decode>  s    € ð
 +ˆt�~‰~×*Ñ*¨DÐ;°FÑ;Ð;r   c                 ó:   —  | j                   j                  |i |¤ŽS )z¼
        This method forwards all its arguments to GemmaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )rI   Údecoder™   s      r    rœ   zPaliGemmaProcessor.decodeF  s    € ð
 %ˆt�~‰~×$Ñ$ dÐ5¨fÑ5Ð5r   c                 óœ   — | j                   j                  }| j                  j                  }t        t        j                  ||z   «      «      S r7   )rI   Úmodel_input_namesrH   r|   ÚdictÚfromkeys)r`   Útokenizer_input_namesÚimage_processor_input_namess      r    rž   z$PaliGemmaProcessor.model_input_namesM  sA   € ð !%§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#Ü”D—M‘MÐ"7Ð:UÑ"UÓVÓWÐWr   )NNN)NNNN)r   r   r   Ú__doc__Ú
attributesÚvalid_kwargsÚimage_processor_classÚtokenizer_classr_   r   r   r   r   r   r   r&   r   r–   r˜   rœ   Úpropertyrž   Ú__classcell__)rc   s   @r    rG   rG   f   s·   ø„ ñð $ [Ð1€JØ#Ð$€LØPÐØ>€Oð ØØõ	Rð@ "Ø^bØØñb.àðb.ð �IÐ0°$°y±/À4ÐHYÑCZÐZÑ[ðb.ð Ð1Ñ2ðb.ð 
ób.òJ<ò6ð ñXó ôXr   rG   N)(r£   Útypingr   r   r   Úfeature_extraction_utilsr   Úimage_utilsr   r	   r
   Úprocessing_utilsr   r   r   r   r   r   Útokenization_utils_baser   r   r   Úutilsr   Ú
get_loggerr   rz   rV   Úranger[   r   r"   r&   r$   r5   r:   r<   rE   rG   Ú__all__)Úis   0r    ú<module>r´      sö   ðñ÷ )Ñ (å 4ß OÑ O÷÷ ÷ñ õ
 ð 
ˆ×	Ñ	˜HÓ	%€à€Ù).¨t«Ö5 A�$�q˜�g˜Q’Ò5ÑRWÐX[ÓR\Ö8]ÈQ¸4ÀÀ#¸wÀaºÒ8]Ñ]€ôd˜*ô dô#˜Lô #ô
Ð/°uõ 
ð;�4ó ;ò
0òBòNô,lX˜ô lXð^  Ð
 �ùòW	 6ùÒ8]s   ÁC	Á5C