Ë
    T^(h\A  ã                   óV  — d Z ddlZddlmZ ddlmZmZ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 dd	lmZmZmZ dd
lmZ erddlmZ  ej8                  e«      Zdefd„Z d„ Z!d„ Z"d„ Z#d„ Z$ G d„ ded¬«      Z% G d„ ded¬«      Z&e%e&jN                  d<    G d„ de«      Z(dgZ)y)z
Processor class for Idefics3.
é    N)Ú
accumulate)ÚTYPE_CHECKINGÚDictÚListÚOptionalÚUnioné   )ÚBatchFeature)Ú
ImageInputÚis_valid_imageÚ
load_image)ÚImagesKwargsÚProcessingKwargsÚProcessorMixinÚUnpack)Ú
AddedTokenÚBatchEncodingÚ	TextInput)Úlogging)ÚPreTokenizedInputÚreturnc                 óH   — t        | t        «      xr | j                  d«      S )NÚhttp)Ú
isinstanceÚstrÚ
startswith)Úvals    ún/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/idefics3/processing_idefics3.pyÚis_urlr   $   s   € Ü�cœ3ÓÒ: C§N¡N°6Ó$:Ð:ó    c                 ó2   — t        | «      xs t        | «      S ©N)r   r   )Úelems    r   Úis_image_or_image_urlr$   (   s   € Ü�$‹<Ò/œ>¨$Ó/Ð/r    c           	      ó¼   — d}t        |«      D ]4  }t        |«      D ]  }||› d|dz   › d|dz   › d�z   |› | z  z   z  }Œ! |dz  }Œ6 |d|› �|› z   |› | z  z   |› z   z  }|S )zKPrompt with expanded image tokens for when the image is split into patches.Ú z<row_é   Ú_col_ú>ú
)Úrange)	Úimage_seq_lenÚ
image_rowsÚ
image_colsÚfake_token_around_imageÚimage_tokenÚglobal_img_tokenÚtext_split_imagesÚn_hÚn_ws	            r   Ú_prompt_split_imager5   ,   sÁ   € àÐÜ�ZÓ ò "ˆÜ˜Ó$ò 	ˆCØØ*Ð+°°s¸Q±w°i¸uÀSÈ1ÁWÀIÈQÐ/OÑOÐU`ÐTaÐerÑRrÑrñÑð	ð 	˜TÑ!Ñð"ð Ø
Ð$Ð%Ð&ØÐñ	 àˆM˜]Ñ
*ñ	+ð %Ð%ñ	'ñÐð Ðr    c                 ó&   — |› |› z   |› | z  z   |› z   S )z5Prompt with expanded image tokens for a single image.© )r,   r/   r0   r1   s       r   Ú_prompt_single_imager8   ?   s6   € ð #Ð
#ØÐñ	 àˆM˜]Ñ
*ñ	+ð %Ð%ñ	'ðr    c                 óT   — | dk(  r|dk(  rt        ||||¬«      S t        || ||||«      S )Nr   )r/   r0   r1   )r8   r5   )r-   r.   r,   r/   r0   r1   s         r   Úget_image_prompt_stringr:   I   sH   € ð �Q‚˜:¨š?Ü#ØØ$;Ø#Ø-ô	
ð 	
ô Ø�z :Ð/FÈÐUeóð r    c                   ó8   — e Zd ZU ee   ed<   eeeef      ed<   y)ÚIdefics3ImagesKwargsÚreturn_row_col_infoÚmax_image_sizeN)	Ú__name__Ú
__module__Ú__qualname__r   ÚboolÚ__annotations__r   r   Úintr7   r    r   r<   r<   X   s   … Ø! $™Ó'Ø˜T # s (™^Ñ,Ô,r    r<   F)Útotalc                   ó.   — e Zd ZU eed<   ddddœddidœZy)ÚIdefics3ProcessorKwargsÚimages_kwargsTF)Úadd_special_tokensÚpaddingÚis_split_into_wordsr=   )Útext_kwargsrH   N)r?   r@   rA   r<   rC   Ú	_defaultsr7   r    r   rG   rG   ]   s+   … Ø'Ó'ð #'ØØ#(ñ
ð " 4ð
ñ	�Ir    rG   rH   c                   óÜ   ‡ — e Zd ZdZddgZddgZdZdZ	 ddede	e
   fˆ fd„Zd	„ Z	 	 	 	 	 dd
eeee   eee      f   deedee   ed   f   de	e   dee   def
d„Zd„ Zd„ Zed„ «       Zˆ xZS )ÚIdefics3Processoraÿ  
    Constructs a Idefics3 processor which wraps a LLama tokenizer and Idefics3 image processor into a single processor.

    [`Idefics3Processor`] offers all the functionalities of [`Idefics3ImageProcessor`] and [`Idefics3TokenizerFast`]. See
    the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.

    Args:
        image_processor (`Idefics3ImageProcessor`):
            An instance of [`Idefics3ImageProcessor`]. The image processor is a required input.
        tokenizer (`PreTrainedTokenizerBase`, *optional*):
            An instance of [`PreTrainedTokenizerBase`]. This should correspond with the model's text model. The tokenizer is a required input.
        image_seq_len (`int`, *optional*, defaults to 169):
            The length of the image sequence i.e. the number of <image> tokens per image in the input.
            This parameter is used to build the string from the input prompt and image tokens and should match the
            value the model used. It is computed as: image_seq_len = int(((image_size // patch_size) ** 2) / (scale_factor**2))
        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Ú	tokenizerr,   Úchat_templateÚIdefics3ImageProcessorÚAutoTokenizerc                 óŽ  •— |€t        d«      ‚|€t        d«      ‚t        ddd¬«      | _        t        ddd¬«      | _        t        ddd¬«      | _        d	| _        || _        t        j                  d
«      | _	        d| j                  | j                  | j                  gi}|j                  |«       t        ‰| �0  ||fd|i|¤Ž y )Nz)You need to specify an `image_processor`.z"You need to specify a `tokenizer`.z<fake_token_around_image>FT)Ú
normalizedÚspecialú<image>z<end_of_utterance>z<global-img>z*(\n?<global-img>\n?|<row_\d+_col_\d+>\n?)+Úadditional_special_tokensrR   )Ú
ValueErrorr   Úfake_image_tokenr0   Úend_of_utterance_tokenÚglobal_image_tagr,   ÚreÚcompileÚ%_regex_to_remove_extra_special_tokensrI   ÚsuperÚ__init__)ÚselfrP   rQ   r,   rR   ÚkwargsÚtokens_to_addÚ	__class__s          €r   rb   zIdefics3Processor.__init__ˆ   sÜ   ø€ ð Ð"ÜÐHÓIÐIØÐÜÐAÓBÐBä *Ð+FÐSXÐbfÔ gˆÔÜ% i¸EÈ4ÔPˆÔÜ&0Ð1EÐRWÐaeÔ&fˆÔ#Ø .ˆÔØ*ˆÔô 68·Z±ZÐ@mÓ5nˆÔ2ð (Ø×%Ñ%Ø× Ñ Ø×+Ñ+ð*ð
ˆð 	×$Ñ$ ]Ô3ä‰Ñ˜¨)Ñ[À=Ð[ÐTZÓ[r    c                 óÒ   — g }|D ]_  }g }|D ]E  }t        |«      r|j                  |«       Œ t        |«      sŒ,|j                  t        |«      «       ŒG |j                  |«       Œa |S r"   )r   Úappendr   r   )rc   ÚpromptsÚprompt_imagesÚpromptÚimagesr#   s         r   Ú_extract_images_from_promptsz.Idefics3Processor._extract_images_from_prompts¥   sn   € ØˆØò 	)ˆFØˆFØò 4�Ü! $Ô'Ø—M‘M $Õ'Ü˜D•\Ø—M‘M¤*¨TÓ"2Õ3ð	4ð
 × Ñ  Õ(ð	)ð Ðr    rl   Útextr   rd   r   c                 óÔ  — |€|€t        d«      ‚ | j                  t        fd| j                  j                  i|¤Ž}|�|n| j
                  }g }g }	t        «       }
|�tt        |t        «      r|g}n.t        |t        «      st        |d   t        «      st        d«      ‚|D �cg c]'  }|j                  | j                  j                  «      ‘Œ) }}|��t        |«      r|gg}�n$t        |t        t        f«      rÃt        |d   «      rµ|�¯t        |«      t!        |«      k7  rRt        d| j                  j                  › dt        |«      › d| j                  j                  › dt!        |«      › d	�	«      ‚dgt        t#        |«      «      z   }t%        t!        |«      «      D �cg c]  }|||   ||d
z       ‘Œ }}nO|g}nKt        |t        t        f«      s5t        |d   t        t        f«      st        |d   d   «      st        d«      ‚|D �cg c]  }t!        |«      ‘Œ }	}|D ��cg c](  }|D �cg c]  }t'        |«      rt)        |«      n|‘Œ c}‘Œ* }}} | j*                  |fi |d   ¤Ž}|
j-                  |«       |��h|	|k7  rt        d|› d|	› d�«      ‚|
j/                  ddgt!        |«      z  g«      }|
j/                  ddgt!        |«      z  g«      }| j0                  j                  }| j                  j                  }| j2                  }g }t5        |||«      D ]Ÿ  \  }}}g }t5        ||«      D ]'  \  }}t7        ||||||¬«      }|j9                  |«       Œ) |j;                  |«      }t!        |«      dk(  rt        d«      ‚|d   }t=        |«      D ]  \  }}||||d
z      z   z  }Œ |j9                  |«       Œ¡  | j                  dd|i|d   ¤Ž}|
j-                  |«       |
S |�bt?        |«      r/t        dt        |«      › d| j                  j                  › d�«      ‚ | j                  dd|i|d   ¤Ž}|
j-                  |«       |
S c c}w c c}w c c}w c c}w c c}}w )a·  
        Processes the input prompts and returns a BatchEncoding.

        Example:

        ```python
        >>> import requests
        >>> from transformers import Idefics3Processor
        >>> from transformers.image_utils import load_image

        >>> processor = Idefics3Processor.from_pretrained("HuggingFaceM4/Idefics3-8B-Llama3")
        >>> processor.image_processor.do_image_splitting = False  # Force as False to simplify the example

        >>> url1 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
        >>> url2 = "https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg"

        >>> image1, image2 = load_image(url1), load_image(url2)
        >>> images = [[image1], [image2]]

        >>> text = [
        ...     "<image>In this image, we see",
        ...     "bla bla bla<image>",
        ... ]
        >>> outputs = processor(images=images, text=text, return_tensors="pt", padding=True)
        >>> input_ids = outputs.input_ids
        >>> input_tokens = processor.tokenizer.batch_decode(input_ids)
        >>> print(input_tokens)
        ['<|begin_of_text|><fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image> In this image, we see', '<|reserved_special_token_0|><|reserved_special_token_0|><|reserved_special_token_0|><|begin_of_text|>bla bla bla<fake_token_around_image><global-img>((<image>)*169)<fake_token_around_image>']
        ```

        Args:
            images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
                The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
                tensor. If is of type `List[ImageInput]`, it's assumed that this is for a single prompt i.e. of batch size 1.
            text (`Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]`, *optional*):
                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).
                Wherever an image token, `<image>` is encountered it is expanded to
                `<fake_token_around_image>` + `<row_x_col_y>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
            image_seq_len (`int`, *optional*):
                The length of the image sequence. If not provided, the default value of self.image_seq_len is used.
                image_seq_len should be equal to int(((image_size // patch_size) ** 2) / (scale_factor**2))
            return_tensors (`Union[str, TensorType]`, *optional*):
                If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
                information.
        z+You must provide either `text` or `images`.Útokenizer_init_kwargsr   zAInvalid input text. Please provide a string, or a list of stringszThe total number of zP tokens in the prompts should be the same as the number of images passed. Found ú z tokens and z images.r'   zdInvalid input images. Please provide a single image or a list of images or a list of list of images.rH   z!The number of images in the text z and images z should be the same.ÚrowsÚcols)r0   r/   r1   z.The image token should be present in the text.rn   rL   zFound z. tokens in the text but no images were passed.r7   ) rZ   Ú_merge_kwargsrG   rQ   Úinit_kwargsr,   r
   r   r   ÚlistÚcountr0   Úcontentr$   ÚtupleÚsumÚlenr   r+   r   r   rP   ÚupdateÚpopr[   r]   Úzipr:   rh   ÚsplitÚ	enumerateÚany)rc   rl   rn   ÚaudioÚvideosr,   rd   Úoutput_kwargsÚn_images_in_textÚn_images_in_imagesÚinputsÚsampleÚcumsum_images_in_textÚiÚimÚimage_inputsr-   r.   r[   r0   r1   Úprompt_stringsÚsample_rowsÚsample_colsÚimage_prompt_stringsÚn_rowsÚn_colsÚimage_prompt_stringÚsplit_sampleÚtext_inputss                                 r   Ú__call__zIdefics3Processor.__call__±   sí  € ðp ˆ<˜F˜NÜÐJÓKÐKà*˜×*Ñ*Ü#ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð *7Ð)B™È×HZÑHZˆàÐØÐÜ“ˆàÐÜ˜$¤Ô$Ø�v‘Ü ¤dÔ+´J¸tÀA¹wÌÔ4LÜ Ð!dÓeÐeØUYÖZÈ6 §¡¨T×-=Ñ-=×-EÑ-EÕ FÐZÐÐZàÑÜ$ VÔ,Ø!˜(˜’Ü˜F¤T¬5 MÔ2Ô7LÈVÐTUÉYÔ7WØÐ#ÜÐ+Ó,´°F³Ò;Ü(Ø2°4×3CÑ3C×3KÑ3KÐ2Lð M&Ü&)Ð*:Ó&;Ð%<¸A¸d×>NÑ>N×>VÑ>VÐ=WÐWcÔdgÐhnÓdoÐcpÐpxðzóð ð
 ./¨C´$´zÐBRÓ7SÓ2TÑ,TÐ)ô "'¤sÐ+;Ó'<Ó!=öàð Ð4°QÑ7Ð:OÐPQÐTUÑPUÑ:VÒWð�Fñ ð
 %˜X‘Fä˜v¬¬e }Ô5Ü" 6¨!¡9¬t´U¨mÔ<Ü-¨f°Q©i¸©lÔ;ä Øzóð ð =CÖ!C°&¤# f¥+Ð!CÐÐ!Cð ]c×cÐRXÀfÖMÀ¬°¬”z "”~¸Ñ;ÔMÐcˆFÑcà/˜4×/Ñ/°ÑY¸-ÈÑ:XÑYˆLØ�M‰M˜,Ô'àÑØ%Ð)9Ò9Ü$Ø;Ð<LÐ;MÈ\ÐZlÐYmð  nBð  Cóð ð $ŸZ™Z¨°!°´s¸4³y±Ð0AÓB�
Ø#ŸZ™Z¨°!°´s¸4³y±Ð0AÓB�
à#'×#8Ñ#8×#@Ñ#@Ð Ø"×.Ñ.×6Ñ6�Ø#'×#8Ñ#8Ð à!#�Ü8;¸DÀ*ÈjÓ8Yò 2Ñ4�F˜K¨à+-Ð(Ü*-¨k¸;Ó*Gò 	I™˜ Ü.EØ"Ø"Ø)Ø(3Ø4DØ-=ô/Ð+ð -×3Ñ3Ð4GÕHð	Ið $*§<¡<°Ó#<�LÜ˜<Ó(¨AÒ-Ü(Ð)YÓZÐZð *¨!™_�FÜ2;Ð<PÓ2Qò LÑ.˜Ð.ØÐ"5¸ÀQÈÁUÑ8KÑ"KÑK™ðLà"×)Ñ)¨&Õ1ð-2ð0 -˜dŸn™nÑa°.ÐaÀMÐR_ÑD`Ña�Ø—‘˜kÔ*ð ˆð ÐÜÐ#Ô$Ü ØœSÐ!1Ó2Ð3°1°T×5EÑ5E×5MÑ5MÐ4NÐN|Ð}óð ð )˜$Ÿ.™.ÑS¨dÐS°mÀMÑ6RÑSˆKØ�M‰M˜+Ô&àˆùòk  [ùòùò "Dùò NùÓcs*   Â#,QÆ"QÈQÈ&	Q$È/QÉQ$ÑQ$c                 ó˜   —  | j                   j                  |i |¤Ž}|D �cg c]  }| j                  j                  d|«      ‘Œ  c}S c c}w )zÅ
        This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        rX   )rQ   Úbatch_decoder`   Úsub)rc   Úargsrd   Úbatched_decode_outputÚss        r   r˜   zIdefics3Processor.batch_decodeT  sH   € ð
 !< §¡× ;Ñ ;¸TÐ LÀVÑ LÐØVkÖlÐQR�×:Ñ:×>Ñ>¸yÈ!ÕLÒlÐlùÒls   ¡#Ac                 ór   —  | j                   j                  |i |¤Ž}| j                  j                  d|«      S )z¿
        This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        rX   )rQ   Údecoder`   r™   )rc   rš   rd   Údecode_outputs       r   rž   zIdefics3Processor.decode\  s8   € ð
 .˜Ÿ™×-Ñ-¨tÐ>°vÑ>ˆØ×9Ñ9×=Ñ=¸iÈÓWÐWr    c                 óœ   — | j                   j                  }| j                  j                  }t        t        j                  ||z   «      «      S r"   )rQ   Úmodel_input_namesrP   rv   ÚdictÚfromkeys)rc   Útokenizer_input_namesÚimage_processor_input_namess      r   r¡   z#Idefics3Processor.model_input_namesd  s?   € à $§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#Ü”D—M‘MÐ"=Ð@UÑ"UÓVÓWÐWr    )Né©   N)NNNNN)r?   r@   rA   Ú__doc__Ú
attributesÚvalid_kwargsÚimage_processor_classÚtokenizer_classrD   r   r   rb   rm   r   r   r   r   r   rG   r   r–   r˜   rž   Úpropertyr¡   Ú__classcell__)rf   s   @r   rO   rO   o   s  ø„ ñð& $ [Ð1€JØ# _Ð5€LØ4ÐØ%€Oð imñ\Ø>Að\ØX`ÐadÑXeõ\ò:
ð OSØbfØØØ'+ñaà�j $ zÑ"2°D¸¸jÑ9IÑ4JÐJÑKðað �IÐ2°D¸±OÀTÐJ]ÑE^Ð^Ñ_ðað   ‘}ðað Ð0Ñ1ðað 
óaòFmòXð ñXó ôXr    rO   )*r§   r^   Ú	itertoolsr   Útypingr   r   r   r   r   Úfeature_extraction_utilsr
   Úimage_utilsr   r   r   Úprocessing_utilsr   r   r   r   Útokenization_utils_baser   r   r   Úutilsr   r   Ú
get_loggerr?   ÚloggerrB   r   r$   r5   r8   r:   r<   rG   rC   rO   Ú__all__r7   r    r   ú<module>r¸      s¶   ðñó 
Ý  ß =Õ =å 4ß AÑ Aß VÓ Vß KÑ KÝ ñ Ý<à	ˆ×	Ñ	˜HÓ	%€ð;�4ó ;ò0òò&òô-˜<¨uõ -ô
Ð.°eõ ð <PÐ × 'Ñ '¨Ñ 8ôyX˜ô yXðx Ð
�r    