§
    ‚ŠtjEB  ã                   ó  — d Z ddlmZ ddlmZ ddl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d
Z G d„ de
d¬¦  «        Z G d„ ded¬¦  «        Zdd„Zd„ Zd„ Zd„ Ze G d„ de	¦  «        ¦   «         ZdgZd	S )z
Processor class for IDEFICS.
é    )Úurlparseé   )ÚBatchFeature)Ú
ImageInput)ÚProcessingKwargsÚProcessorMixinÚ
TextKwargsÚUnpack)ÚPreTokenizedInputÚ	TextInput)Úauto_docstringÚis_torch_availableNú<image>c                   ó4   — e Zd ZU dZedz  ed<   edz  ed<   dS )ÚIdeficsTextKwargsaW  
    add_eos_token (`bool`, *optional*, defaults to `False`):
        Whether to add an end-of-sequence token at the end of the text input. When enabled, an EOS token is
        appended to mark the end of the text sequence, which is useful for generation tasks.
    add_end_of_utterance_token (`bool`, *optional*):
        Whether to add an end-of-utterance token to mark the end of a user's message in conversational contexts.
        This token helps the model distinguish between different utterances in a multi-turn conversation and is
        particularly important for chat-based models.
    NÚadd_eos_tokenÚadd_end_of_utterance_token)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚboolÚ__annotations__© ó    úl/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/transformers/models/idefics/processing_idefics.pyr   r   '   s>   € € € € € € ðð ð ˜$‘;ÐÐÑØ $ t¡Ð+Ð+Ñ+Ð+Ð+r   r   F)Útotalc                   ó0   — e Zd ZU eed<   ddddœddidœZdS )	ÚIdeficsProcessorKwargsÚtext_kwargsFÚlongest)Úadd_special_tokensÚpaddingr   Úreturn_tensorsÚpt)r    Úcommon_kwargsN)r   r   r   r   r   Ú	_defaultsr   r   r   r   r   6   sG   € € € € € € Ø"Ð"Ð"Ñ"ð #(Ø Ø"ð
ð 
ð
 +¨DÐ1ðð €I€I€Ir   r   éÿÿÿÿc                 ó°   — |dk    r|dk    r	d| | |k    <   |dk    r:| dk    }d| |<   t           j        j                             | |¬¦  «        }d||d d …f<   |S )Nr(   r%   r   ©Únum_classes)ÚtorchÚnnÚ
functionalÚone_hot)Úincremental_maskr$   r+   Ú	negativesÚ	attn_masks        r   Ú$incremental_to_binary_attention_maskr3   C   s�   € à�bÒÐØ˜TÒ!Ð!Ø@BÐÐ-°Ò<Ñ=ð ˜ÒÐØ$¨Ò*ˆ	Ø&'Ð˜Ñ#Ý”HÔ'×/Ò/Ð0@ÈkÐ/ÑZÔZˆ	Ø"#ˆ	�)˜Q˜Q˜Q�,ÑàÐr   c                 ó2   — |dk    rt          | |¦  «        S d S )Nr%   )Ú,image_attention_mask_for_packed_input_ids_pt)Ú	input_idsÚ	tokenizerr$   s      r   Ú)image_attention_mask_for_packed_input_idsr8   T   s%   € Ø˜ÒÐÝ;¸IÀyÑQÔQÐQð Ðr   c                 óN  — t          j        | d¬¦  «        }t          j        | d¬¦  «        }|                     t          ¦  «        }|j        }t          |                      d¦  «        ¦  «        D ]Z}d}d}t          | |         ¦  «        D ]>\  }	}
|
|k    r|dz  }|||         |	<   d}n|||         |	<   |rd||         |	<   |
|k    rd}Œ?Œ[t          |                      d¦  «        ¦  «        D ]µ}d}d}t          | |                              d¦  «        dz
  dd¦  «        D ]I}	| |         |	         }
|
|k    r|dz  }|||         |	<   d}n|||         |	<   |
|k    rd}|rd||         |	<   ŒJ||         dk    }||         |xx         |z  cc<   ||         |xx         dz  cc<   Œ¶||fS )Nr(   )Ú
fill_valuer   Fé   T)r,   Ú	full_likeÚconvert_tokens_to_idsÚIMAGE_TOKENÚeos_token_idÚrangeÚsizeÚ	enumerate)r6   r7   Úimage_attention_maskÚnext_image_attention_maskÚimage_token_idÚeod_token_idÚ	batch_idxÚcountÚseen_eodÚidxÚtoken_idÚnon_negative_indicess               r   r5   r5   Y   s7  € Ý œ?¨9ÀÐDÑDÔDÐÝ %¤°	ÀbÐ IÑ IÔ IÐØ×4Ò4µ[ÑAÔA€NØÔ)€LÝ˜9Ÿ>š>¨!Ñ,Ô,Ñ-Ô-ð  ð  ˆ	ØˆØˆÝ& y°Ô';Ñ<Ô<ð 	 ð 	 ‰MˆC�Ø˜>Ò)Ð)Ø˜‘
�Ø7<Ð$ YÔ/°Ñ4Ø ��à7<Ð$ YÔ/°Ñ4àð :Ø79Ð$ YÔ/°Ñ4à˜<Ò'Ð'Ø�øð	 õ ˜9Ÿ>š>¨!Ñ,Ô,Ñ-Ô-ð Ið Iˆ	ØˆØˆÝ˜ 9Ô-×2Ò2°1Ñ5Ô5¸Ñ9¸2¸rÑBÔBð 	?ð 	?ˆCØ  Ô+¨CÔ0ˆHØ˜>Ò)Ð)Ø˜‘
�Ø<AÐ)¨)Ô4°SÑ9Ø ��à<AÐ)¨)Ô4°SÑ9à˜<Ò'Ð'Ø�àð ?Ø<>Ð)¨)Ô4°SÑ9øà8¸ÔCÀrÒIÐØ! )Ô,Ð-AÐBÐBÔBÀeÑKÐBÐBÑBØ! )Ô,Ð-AÐBÐBÔBÀbÑHÐBÐBÑBÐBàÐ!:Ð:Ð:r   c                 ób   — d| v rdS t          | ¦  «        }t          |j        |j        g¦  «        S )z…Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately
    invalidated the urlú F)r   ÚallÚschemeÚnetloc)ÚstringÚresults     r   Úis_urlrT   ˆ   s6   € ð ˆf€}€}ØˆuÝ�fÑÔ€FÝ�”˜vœ}Ð-Ñ.Ô.Ð.r   c            
       ó  ‡ — e Zd Zd
ˆ fd„	Ze	 	 ddeee         z  ez  ee         z  eee                  z  dee	z  ee         z  ee	         z  eee                  z  eee	                  z  de
e         defd„¦   «         Zed	„ ¦   «         Zˆ xZS )ÚIdeficsProcessorNéà   c                 óV  •— t          ¦   «                              ||¦  «         t          |d¦  «        r|j        n|                     t
          ¦  «        | _        | j        j        | j        j        | j        j        f| _	        d| j
        j                             dg ¦  «        v | _        dS )zÿ
        image_size (int, *optional*, defaults to 224):
            The size of the image to be processed.
        add_end_of_utterance_token (bool, *optional*, defaults to None):
            Whether to add the end of utterance token to the text.
        Úimage_tokenú<end_of_utterance>Úadditional_special_tokensN)ÚsuperÚ__init__ÚhasattrrE   r=   r>   Úimage_processorÚimage_num_channelsÚ
image_sizeÚdefault_image_dimsr7   Úspecial_tokens_mapÚgetÚ1tokenizer_was_trained_with_end_of_utterance_token)Úselfr_   r7   ra   r   ÚkwargsÚ	__class__s         €r   r]   zIdeficsProcessor.__init__“   sª   ø€ õ 	‰Œ×Ò˜¨)Ñ4Ô4Ð4õ �y -Ñ0Ô0ð>ˆIÔ$Ð$à×0Ò0µÑ=Ô=ð 	Ôð Ô Ô3ØÔ Ô+ØÔ Ô+ð#
ˆÔð ! D¤NÔ$E×$IÒ$IÐJeÐgiÑ$jÔ$jÐjð 	Ô>Ð>Ð>r   ÚimagesÚtextrg   Úreturnc                 ó  ‡'‡(— |€|€t          d¦  «        ‚|€|}�n|��t          |t          t          f¦  «        s|g}t          |t          ¦  «        r|g}t          |t          t          f¦  «        r/t          |¦  «        t          |¦  «        k    rt          d¦  «        ‚t          d„ |D ¦   «         ¦  «        st          d¦  «        ‚t          |d         t          t          f¦  «        rd„ t          ||¦  «        D ¦   «         }nt          t          ||¦  «        ¦  «        } | j        t          fd| j
        j        i|¤Ž}|d	                              d
d¦  «        }|d	                              dd¦  «        }|€| j        }t          d„ |D ¦   «         ¦  «        s|g}dŠ'dŠ(d}ˆ'ˆ(fd„}	g }
g }|D �]R}| j
        j        › }g }d}d}t!          |¦  «        D ]Ê\  }}|dk    rt#          | ¦  «        }t          |t          ¦  «        ru|                     d¦  «        }t'          |¦  «        r@| j                             |¦  «        }| |	|¦  «        z  }|                     |¦  «         d}Œ”|r|r||z  }||z  }d}Œ¥| |	|¦  «        z  }|                     |¦  «         d}ŒË|r|| j
        j        z  }t          |¦  «        dk    r | j        |fi |d         ¤Ž}|
                     |¦  «         |                     |¦  «         �ŒT|d	                              dd¦  «        } | j
        |
fi |d	         ¤Ž}|d         }|d         }t1          d„ |D ¦   «         ¦  «        }t1          d|¦  «        }t3          d„ |D ¦   «         ¦  «        dk    }g }g }g }t          |||¦  «        D �]#\  }}}|} |                      | j        ¦  «        }!t9          |!|¦  «        }"|d|"…         }#t          |#¦  «        dk    rM|dk    rFt;          j        |g|#                     ¦   «         dd…         ¢R Ž }$|#|$d|#                     d¦  «        …<   n|dk    rt;          j        |g| j         ¢R Ž }$|                     |$¦  «         |dk    rN|                     t;          j!        | ¦  «        ¦  «         |                     t;          j!        |¦  «        ¦  «         �Œ%|dk    r<t;          j"        |¦  «        }t;          j"        |¦  «        }t;          j"        |¦  «        }|r,tG          || j
        |¦  «        \  }%}&tI          |%||¬¦  «        }%n>|dk    r8t;          j        |j%        d         |j%        d         dt:          j        ¬¦  «        }%tM          ||||%dœ¬¦  «        S ) aÔ
  
        Returns:
            a dict with entries: `input_ids`, `attention_mask`, `pixel_values`, `image_attention_mask` which can be
            directly passed to `model.generate`

            Detailed explanation:

            Each entry in `text` is either a text to be passed as is or an image that will be processed.

            An image can be either an image object (`PIL.Image`) or a url from which the image can be retrieved.

        When the processor encounters an image it'll inject `<fake_token_around_image><image><fake_token_around_image>`
        entry into the prompt.

        Example:

        ```python
        checkpoint = "HuggingFaceM4/idefics-9b"
        processor = AutoProcessor.from_pretrained(checkpoint)
        url = "https://hips.hearstapps.com/hmg-prod/images/cute-photos-of-cats-in-grass-1593184777.jpg"
        img = processor.image_processor.fetch_images([url])[0]

        prompts = [
            "User:",
            img,
            "Describe this image.\nAssistant: An image of two kittens in grass.\n",
            "User:",
            "https://hips.hearstapps.com/hmg-prod/images/dog-puns-1581708208.jpg",
            "Describe this image.\nAssistant:",
        ]

        inputs = processor(text=prompts, return_tensors="pt")
        generated_ids = model.generate(**inputs, max_length=100)
        generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        ```

        In this example the `prompts` will be converted into:

        ```
        <s>User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
        Assistant: An image of two kittens in grass.
        User:<fake_token_around_image><image><fake_token_around_image>Describe this image.
        Assistant:'
        ```

        and the two images will be massaged using [`IdeficsImageProcessor.__call__`] method and placed inside the
        `pixel_values` dict entry of the return value.

        This example also exemplifies that images can be passed as objects or as text urls. It can be seen that the
        first image is passed as object and the second one as a url.

        To do training do:

        ```python
        image_transform = transforms.Compose(
            [
                transforms.RandomResizedCrop(
                    (w, h), scale=(0.9, 1.0), interpolation=transforms.InterpolationMode.BICUBIC
                ),
                transforms.ToTensor(),
                transforms.Normalize(mean=self.image_mean, std=self.image_std),
            ]
        )
        inputs = processor(text=prompts, transform=image_transform, return_tensors="pt")
        ```

        In order to help debug prompt generation enable `debug=True` which will show you what's happening.

        Nz9You need to specify either `text` or `images` and `text`.a  When providing both images and text arguments, the number of text prompts should be the same as the number of images.If you want to have several images per prompt, images should be nested as such: images=[[img1, img2], [img3, img4], ...] for text=[prompt1, prompt2, ...].c              3   ó@   K  — | ]}t          |t          ¦  «        V — Œd S ©N)Ú
isinstanceÚstr©Ú.0Úis     r   ú	<genexpr>z,IdeficsProcessor.__call__.<locals>.<genexpr>  s,   è è € Ð8Ð8¨a•z !¥SÑ)Ô)Ð8Ð8Ð8Ð8Ð8Ð8r   zQWhen using the image-text-to-text behavior, the prompts should only contain text.r   c                 ó   — g | ]
\  }}|g|¢‘ŒS r   r   )rr   Ú
image_listÚsamples      r   ú
<listcomp>z-IdeficsProcessor.__call__.<locals>.<listcomp>  s%   € Ð]Ð]Ð]Ñ5G°ZÀ˜FÐ0 ZÐ0Ð]Ð]Ð]r   Útokenizer_init_kwargsr    r   Fr   c              3   óN   K  — | ] }t          |t          t          f¦  «        V — Œ!d S rn   )ro   ÚlistÚtuplerq   s     r   rt   z,IdeficsProcessor.__call__.<locals>.<genexpr>%  s0   è è € ÐAÐA°A•:˜a¥$­ Ñ/Ô/ÐAÐAÐAÐAÐAÐAr   z<fake_token_around_image>r   rZ   c                 ó"   •— | r‰‰z   S ‰‰z   ‰z   S rn   r   )Úlast_was_imageÚ
fake_tokenrY   s    €€r   Úimage_tokensz/IdeficsProcessor.__call__.<locals>.image_tokens,  s&   ø€ Øð =Ø" ZÑ/Ð/à! KÑ/°*Ñ<Ð<r   rN   TÚimages_kwargsr$   r%   r6   Úattention_maskc              3   ó4   K  — | ]}t          |¦  «        V — Œd S rn   ©Úlen©rr   Úxs     r   rt   z,IdeficsProcessor.__call__.<locals>.<genexpr>c  s(   è è € Ð8Ð8¨�S ™VœVÐ8Ð8Ð8Ð8Ð8Ð8r   r;   c              3   ó4   K  — | ]}t          |¦  «        V — Œd S rn   r„   r†   s     r   rt   z,IdeficsProcessor.__call__.<locals>.<genexpr>f  s(   è è € Ð <Ð <¨A¥ Q¡¤Ð <Ð <Ð <Ð <Ð <Ð <r   r*   )Údtype)r6   r‚   Úpixel_valuesrC   )Údata)'Ú
ValueErrorro   r{   r|   rp   r…   rO   ÚzipÚ_merge_kwargsr   r7   Úinit_kwargsÚpopre   ÚanyÚ	bos_tokenrB   r   ÚstriprT   r_   Úfetch_imagesÚappendÚ	eos_tokenÚmaxÚsumrH   rE   Úminr,   ÚzerosrA   rb   ÚtensorÚstackr8   r3   Úshaper   ))rf   ri   rj   rg   ÚpromptsÚoutput_kwargsr   r   Úend_of_utterance_tokenr€   Úall_promptsÚ
all_imagesrw   Ú	full_textÚimage_objectsr~   Úlast_was_textrs   ÚitemÚimager$   Útext_encodingÚ	all_textsÚall_attention_masksÚmax_num_imagesÚat_least_one_imageÚoutput_input_idsÚoutput_imagesÚoutput_attention_masksÚtext_singler‚   Úextracted_imagesÚpadded_input_idsÚimage_countÚlocal_max_num_imagesÚcurrent_imagesÚpadded_image_tensorrC   Ú_r   rY   s)                                          @@r   Ú__call__zIdeficsProcessor.__call__«   s²  øø€ ðb ˆ>˜d˜lÝÐXÑYÔYÐYàˆ>àˆG‰GØÑõ ˜f¥t­U mÑ4Ô4ð "Ø ˜�Ý˜$¥Ñ$Ô$ð Ø�v�å˜$¥¥u Ñ.Ô.ð µ3°t±9´9ÅÀFÁÄÒ3KÐ3KÝ ðqñô ð õ
 Ð8Ð8°4Ð8Ñ8Ô8Ñ8Ô8ð vÝ Ð!tÑuÔuÐuÝ˜& œ)¥d­E ]Ñ3Ô3ð 2à]Ð]Í3ÈvÐW[ÑK\ÔK\Ð]Ñ]Ô]��å�s 6¨4Ñ0Ô0Ñ1Ô1�à*˜Ô*Ý"ð
ð 
à"&¤.Ô"<ð
ð ð
ð 
ˆð & mÔ4×8Ò8¸È%ÑPÔPˆØ%2°=Ô%A×%EÒ%EÐFbÐdhÑ%iÔ%iÐ"ð &Ð-Ø)-Ô)_Ð&åÐAÐA¸ÐAÑAÔAÑAÔAð 	 Ø�iˆGà0ˆ
ØˆØ!5Ðð	=ð 	=ð 	=ð 	=ð 	=ð 	=ð ˆØˆ
Øð &	-ñ &	-ˆFàœ>Ô3Ð5ˆIð ˆMØ"ˆNØ!ˆMÝ$ VÑ,Ô,ð *ð *‘��4Ø�q’5�5Ý$(¨^Ð);Ñ$<Ô$<�Må˜d¥CÑ(Ô(ð *ØŸ:š: c™?œ?�DÝ˜d‘|”|ð 
/Ø $Ô 4× AÒ AÀ$Ñ GÔ G˜Ø! \ \°.Ñ%AÔ%AÑA˜	Ø%×,Ò,¨UÑ3Ô3Ð3Ø)-˜˜ð 6ð @¸-ð @Ø%Ð)?Ñ?˜IØ! TÑ)˜	Ø).˜˜ð   ¨nÑ!=Ô!=Ñ=�IØ!×(Ò(¨Ñ.Ô.Ð.Ø%)�N�Nàð 6Ø˜Tœ^Ô5Ñ5�	å�=Ñ!Ô! AÒ%Ð%Ø 4 Ô 4°]Ð eÐ eÀmÐTcÔFdÐ eÐ e�à×Ò˜yÑ)Ô)Ð)Ø×Ò˜mÑ,Ô,Ð,Ñ,ð ' }Ô5×9Ò9Ð:JÈDÑQÔQˆØ&˜œ {ÐSÐS°mÀMÔ6RÐSÐSˆØ! +Ô.ˆ	Ø+Ð,<Ô=Ðõ Ð8Ð8¨ZÐ8Ñ8Ô8Ñ8Ô8ˆÝ˜Q Ñ/Ô/ˆå Ð <Ð <°Ð <Ñ <Ô <Ñ<Ô<¸qÒ@ÐØÐØˆØ!#Ðå=@ÀÐL_ÐakÑ=lÔ=lð 	Lñ 	LÑ9ˆK˜Ð)9Ø*ÐØ*×0Ò0°Ô1DÑEÔEˆKÝ#& {°NÑ#CÔ#CÐ Ø-Ð.CÐ/CÐ.CÔDˆNå�>Ñ"Ô" QÒ&Ð&Ø! TÒ)Ð)Ý*/¬+°nÐ*aÀ~×GZÒGZÑG\ÔG\Ð]^Ð]_Ð]_ÔG`Ð*aÐ*aÐ*aÐ'ØDRÐ'Ð(@¨.×*=Ò*=¸aÑ*@Ô*@Ð(@ÑAøà! TÒ)Ð)Ý*/¬+°nÐ*_ÀtÔG^Ð*_Ð*_Ð*_Ð'à× Ò Ð!4Ñ5Ô5Ð5Ø Ò%Ð%Ø ×'Ò'­¬Ð5EÑ(FÔ(FÑGÔGÐGØ&×-Ò-­e¬l¸>Ñ.JÔ.JÑKÔKÐKùà˜TÒ!Ð!Ý$œ{Ð+;Ñ<Ô<ÐÝ!œK¨Ñ6Ô6ˆMÝ%*¤[Ð1GÑ%HÔ%HÐ"àð 	Ý&OØ  $¤.°.ñ'ô 'Ñ#Ð  !õ $HØ$ nÀ.ð$ñ $ô $Ð Ð ð
  Ò%Ð%Ý',¤{Ø$Ô*¨1Ô-Ð/?Ô/EÀaÔ/HÈ!ÕSXÔS]ð(ñ (ô (Ð$õ à-Ø"8Ø -Ø(<ð	ð ð
ñ 
ô 
ð 	
r   c                 ó^   — | j         j        }| j        j        }t          ||z   dgz   ¦  «        S )NrC   )r7   Úmodel_input_namesr_   r{   )rf   Útokenizer_input_namesÚimage_processor_input_namess      r   rº   z"IdeficsProcessor.model_input_names™  s7   € à $¤Ô @ÐØ&*Ô&:Ô&LÐ#ÝÐ)Ð,GÑGÐKaÐJbÑbÑcÔcÐcr   )NrW   N)NN)r   r   r   r]   r   r   r{   rp   r   r   r
   r   r   r¸   Úpropertyrº   Ú__classcell__)rh   s   @r   rV   rV   ‘   s7  ø€ € € € € ð
ð 
ð 
ð 
ð 
ð 
ð0 ð UYð +/ðk
ð k
à˜T *Ô-Ñ-°Ñ3°d¸3´iÑ?À$ÀtÈCÄyÄ/ÑQðk
ð Ø
ñà
ˆyŒ/ñð Ð Ô
!ñ"ð ˆt�IŒÔ
ñ	 ð
 ˆtÐ%Ô&Ô
'ñ(ðk
ð Ð/Ô0ðk
ð 
ðk
ð k
ð k
ñ „^ðk
ðZ ðdð dñ „Xðdð dð dð dð dr   rV   )r(   )r   Úurllib.parser   Úfeature_extraction_utilsr   Úimage_utilsr   Úprocessing_utilsr   r   r	   r
   Útokenization_utils_baser   r   Úutilsr   r   r,   r>   r   r   r3   r8   r5   rT   rV   Ú__all__r   r   r   ú<module>rÆ      sÖ  ððð ð "Ð !Ð !Ð !Ð !Ð !à 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø %Ð %Ð %Ð %Ð %Ð %ðð ð ð ð ð ð ð ð ð ð ð ð DÐ CÐ CÐ CÐ CÐ CÐ CÐ CØ 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7ð ÐÑÔð Ø€L€L€Lð €ð,ð ,ð ,ð ,ð ,˜
¨%ð ,ñ ,ô ,ð ,ð	ð 	ð 	ð 	ð 	Ð-°Uð 	ñ 	ô 	ð 	ðð ð ð ð"Rð Rð Rð
,;ð ,;ð ,;ð^/ð /ð /ð ðKdð Kdð Kdð Kdð Kd�~ñ Kdô Kdñ „ðKdð\ Ð
€€€r   