Ë
    T^(hÐ1  ã                   ó  — d Z ddlmZ ddl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mZ ddlmZmZ dd	lmZ erdd
lmZ  ej4                  e«      Zdefd„Zd„ Z G d„ ded¬«      Z  G d„ ded¬«      Z! G d„ de«      Z"dgZ#y)z
Processor class for IDEFICS2.
é    )Ú
accumulate)ÚTYPE_CHECKINGÚListÚOptionalÚUnioné   )ÚBatchFeature)Ú
ImageInputÚis_valid_imageÚ
load_image)ÚImagesKwargsÚProcessingKwargsÚProcessorMixinÚUnpackÚ!_validate_images_text_input_order)Ú
AddedTokenÚ	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/idefics2/processing_idefics2.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                   ó   — e Zd ZU ee   ed<   y)ÚIdefics2ImagesKwargsÚimage_seq_lenN)Ú__name__Ú
__module__Ú__qualname__r   ÚintÚ__annotations__© r   r   r%   r%   2   s   … Ø˜C‘=Ô r   r%   F)Útotalc                   ó*   — e Zd ZU eed<   ddddœi dœZy)ÚIdefics2ProcessorKwargsÚimages_kwargsTF)Úadd_special_tokensÚpaddingÚis_split_into_words)Útext_kwargsr0   N)r'   r(   r)   r%   r+   Ú	_defaultsr,   r   r   r/   r/   6   s$   … Ø'Ó'ð #'ØØ#(ñ
ð
 ñ�Ir   r/   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fd„Zd„ Zd„ Zed„ «       Zˆ xZS )ÚIdefics2ProcessoraÌ  
    Constructs a IDEFICS2 processor which wraps a LLama tokenizer and IDEFICS2 image processor into a single processor.

    [`IdeficsProcessor`] offers all the functionalities of [`Idefics2ImageProcessor`] and [`LlamaTokenizerFast`]. See
    the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information.

    Args:
        image_processor (`Idefics2ImageProcessor`):
            An instance of [`Idefics2ImageProcessor`]. 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 64):
            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
            config.perceiver_config.resampler_n_latents value for the model used.
        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ÚIdefics2ImageProcessorÚAutoTokenizerc                 óÎ  •— |€t        d«      ‚|€t        d«      ‚t        |d«      sRt        ddd¬«      | _        t        ddd¬«      | _        d	| j                  | j                  gi}|j                  |«       n"|j                  | _        |j                  | _        t        d
dd¬«      | _        |j                  d	| j                  gi«       || _        t        ‰| �)  |||¬«       y )Nz)You need to specify an `image_processor`.z"You need to specify a `tokenizer`.Úimage_tokenz<fake_token_around_image>FT)Ú
normalizedÚspecialz<image>Úadditional_special_tokensz<end_of_utterance>)r:   )Ú
ValueErrorÚhasattrr   Úfake_image_tokenr>   r1   Úimage_boundary_tokenÚend_of_utterance_tokenr&   ÚsuperÚ__init__)Úselfr8   r9   r&   r:   ÚkwargsÚtokens_to_addÚ	__class__s          €r   rH   zIdefics2Processor.__init__\   së   ø€ ð Ð"ÜÐHÓIÐIØÐÜÐAÓBÐBä�y -Ô0Ü$.Ð/JÐW\ÐfjÔ$kˆDÔ!Ü)¨)ÀÈtÔTˆDÔØ8¸4×;PÑ;PÐRV×RbÑRbÐ:cÐdˆMØ×(Ñ(¨Õ7à$-×$BÑ$BˆDÔ!Ø(×4Ñ4ˆDÔä&0Ð1EÐRWÐaeÔ&fˆÔ#Ø×$Ñ$Ð&AÀD×D_ÑD_ÐC`Ð%aÔbØ*ˆÔä‰Ñ˜¨)À=ÐÕQr   c                 óÒ   — g }|D ]_  }g }|D ]E  }t        |«      r|j                  |«       Œ t        |«      sŒ,|j                  t        |«      «       ŒG |j                  |«       Œa |S r!   )r   Úappendr   r   )rI   ÚpromptsÚprompt_imagesÚpromptÚimagesr"   s         r   Ú_extract_images_from_promptsz.Idefics2Processor._extract_images_from_promptss   sn   € ØˆØò 	)ˆFØˆFØò 4�Ü! $Ô'Ø—M‘M $Õ'Ü˜D•\Ø—M‘M¤*¨TÓ"2Õ3ð	4ð
 × Ñ  Õ(ð	)ð Ðr   rR   Útextr   rJ   r   c                 óˆ  — |€|€t        d«      ‚t        ||«      \  }} | j                  t        fd| j                  j
                  i|¤Ž}|d   j                  dd«      }|�|n| j                  }g }t        «       }	|��t        |t        «      r|g}n.t        |t        «      st        |d   t        «      st        d«      ‚| j                  j                  }
| j                  j                  }|
› ||z  › |
› �}| j                  j                   r|dz  }g }|D ]\  }|j#                  |j%                  |«      «       |j'                  ||«      }|j'                  |
› |
› �|
› «      }|j#                  |«       Œ^  | j                  |fi |d	   ¤Ž}|	j)                  |«       |��Œt+        |«      r|gg}nüt        |t        t,        f«      r›t+        |d   «      r�|�‡t/        |«      t1        |«      k7  r*t        d
› dt/        |«      › d|› dt1        |«      › d�	«      ‚dgt        t3        |«      «      z   }t5        t1        |«      «      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]  }t1        |«      ‘Œ }}|�||k(  st        d|› d|› d�«      ‚|D ��cg c]  }|D �cg c]  }t7        |«      ‘Œ c}‘Œ }}} | j                  |fi |d   ¤Ž}|	j)                  |«       |	S 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 Idefics2Processor
        >>> from transformers.image_utils import load_image

        >>> processor = Idefics2Processor.from_pretrained("HuggingFaceM4/idefics2-8b", image_seq_len=2)
        >>> 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)
        ['<s><fake_token_around_image><image><image><fake_token_around_image> In this image, we see', '<s> bla bla bla<fake_token_around_image><image><image><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>` + `<image>` * `image_seq_len` * <fake_token_around_image>`.
            return_tensors (`Union[str, TensorType]`, *optional*):
                If set, will return tensors of a particular framework. See [`PreTrainedTokenizerFast.__call__`] for more
                information.

        Nz+You must provide either `text` or `images`.Útokenizer_init_kwargsr0   r&   r   zAInvalid input text. Please provide a string, or a list of stringsé   r4   z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.é   zdInvalid input images. Please provide a single image or a list of images or a list of list of images.z!The number of images in the text z and images  z should be the same.)rB   r   Ú_merge_kwargsr/   r9   Úinit_kwargsÚpopr&   r	   r   r   ÚlistrD   Úcontentr>   r8   Údo_image_splittingrN   ÚcountÚreplaceÚupdater#   ÚtupleÚsumÚlenr   Úranger   )rI   rR   rT   ÚaudioÚvideosrJ   Úoutput_kwargsr&   Ún_images_in_textÚinputsrD   r>   Ú	image_strÚprompt_stringsÚsampleÚtext_inputsÚcumsum_images_in_textÚiÚn_images_in_imagesÚimÚimage_inputss                        r   Ú__call__zIdefics2Processor.__call__   s¡  € ðl ˆ<˜F˜NÜÐJÓKÐKä8¸ÀÓF‰ˆ�à*˜×*Ñ*Ü#ñ
à"&§.¡.×"<Ñ"<ð
ð ñ
ˆð
 & oÑ6×:Ñ:¸?ÈDÓQˆØ)6Ð)B™È×HZÑHZˆàÐÜ“ˆàÑÜ˜$¤Ô$Ø�v‘Ü ¤dÔ+´J¸tÀA¹wÌÔ4LÜ Ð!dÓeÐeð  $×4Ñ4×<Ñ<ÐØ×*Ñ*×2Ñ2ˆKØ+Ð,¨[¸=Ñ-HÐ,IÐJZÐI[Ð\ˆIà×#Ñ#×6Ò6à%¨™M�	àˆNØò .�Ø ×'Ñ'¨¯©°[Ó(AÔBØŸ™¨°YÓ?�àŸ™Ð+;Ð*<Ð=MÐ<NÐ(OÐTdÐSeÓg�Ø×%Ñ% fÕ-ð.ð )˜$Ÿ.™.¨ÑX¸=ÈÑ;WÑXˆKØ�M‰M˜+Ô&àÑÜ$ VÔ,Ø!˜(˜‘Ü˜F¤T¬5 MÔ2Ô7LÈVÐTUÉYÔ7WØÐ#ÜÐ+Ó,´°F³Ò;Ü(Ø2°;°-ð @&Ü&)Ð*:Ó&;Ð%<¸A¸k¸]È,ÔWZÐ[aÓWbÐVcÐckðmóð ð
 ./¨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ØÐÐ(:Ð>NÒ(NÜ Ø7Ð8HÐ7IÈÐWiÐVjÐj~Ðóð ð
 GM×M¸F°Ö7¨"”z "•~Ô7ÐMˆFÑMØ/˜4×/Ñ/°ÑY¸-ÈÑ:XÑYˆLØ�M‰M˜,Ô'àˆùò7ùò  "Dùò 8ùÓMs$   ÉL/Ê1L4Ë#	L>Ë,L9Ë>L>Ì9L>c                 ó:   —  | j                   j                  |i |¤ŽS )zÂ
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
        refer to the docstring of this method for more information.
        )r9   Úbatch_decode©rI   ÚargsrJ   s      r   rw   zIdefics2Processor.batch_decode  s    € ð
 +ˆt�~‰~×*Ñ*¨DÐ;°FÑ;Ð;r   c                 ó:   —  | j                   j                  |i |¤ŽS )z¼
        This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
        the docstring of this method for more information.
        )r9   Údecoderx   s      r   r{   zIdefics2Processor.decode  s    € ð
 %ˆt�~‰~×$Ñ$ dÐ5¨fÑ5Ð5r   c                 óœ   — | j                   j                  }| j                  j                  }t        t        j                  ||z   «      «      S r!   )r9   Úmodel_input_namesr8   r]   ÚdictÚfromkeys)rI   Útokenizer_input_namesÚimage_processor_input_namess      r   r}   z#Idefics2Processor.model_input_names  s?   € à $§¡× @Ñ @ÐØ&*×&:Ñ&:×&LÑ&LÐ#Ü”D—M‘MÐ"7Ð:UÑ"UÓVÓWÐWr   )Né@   N)NNNN)r'   r(   r)   Ú__doc__Ú
attributesÚvalid_kwargsÚimage_processor_classÚtokenizer_classr*   r   r   rH   rS   r   r
   r   r   r   r/   r	   ru   rw   r{   Úpropertyr}   Ú__classcell__)rL   s   @r   r7   r7   C   sî   ø„ ñð& $ [Ð1€JØ# _Ð5€LØ4ÐØ%€Oð hlñRØ>AðRØW_Ð`cÑWdõRò.
ð OSØbfØØñGà�j $ zÑ"2°D¸¸jÑ9IÑ4JÐJÑKðGð �IÐ2°D¸±OÀTÐJ]ÑE^Ð^Ñ_ðGð Ð0Ñ1ðGð 
óGòR<ò6ð ñXó ôXr   r7   N)$rƒ   Ú	itertoolsr   Útypingr   r   r   r   Úfeature_extraction_utilsr	   Úimage_utilsr
   r   r   Úprocessing_utilsr   r   r   r   r   Útokenization_utils_baser   r   Úutilsr   r   Ú
get_loggerr'   ÚloggerÚboolr   r#   r%   r/   r7   Ú__all__r,   r   r   ú<module>r•      s•   ðñõ !ß 7Ó 7å 4ß AÑ A÷õ ÷ =Ý ñ Ý<ð 
ˆ×	Ñ	˜HÓ	%€ð;�4ó ;ò0ô!˜<¨uõ !ô
Ð.°eõ 
ôWX˜ô WXðt Ð
�r   