Ë
    T^(hŽT  ã            
       óŒ  — d dl 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mZmZmZ ddlmZmZ  e«       rd d	lmZ dd
lmZmZ  e«       rddlmZ ddlmZ  ej:                  e«      ZdZ  G d„ de jB                  «      Z" G d„ d«      Z#de$deee%ee%   ded   f      fd„Z& e ed¬«      «       G d„ de«      «       Z'y)é    N)ÚIterable)ÚDictÚListÚOptionalÚUnioné   )ÚProcessingKwargsÚUnpack)Úadd_end_docstringsÚis_torch_availableÚis_vision_availableÚloggingÚrequires_backendsé   )ÚPipelineÚbuild_pipeline_init_args)ÚImage)Úload_imagesÚvalid_images)Ú*MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES)Ú
KeyDatasetz<image>c                   ó   — e Zd ZdZdZdZy)Ú
ReturnTyper   r   r   N)Ú__name__Ú
__module__Ú__qualname__ÚTENSORSÚNEW_TEXTÚ	FULL_TEXT© ó    úg/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/image_text_to_text.pyr   r   .   s   „ Ø€GØ€HØ�Ir!   r   c            	       ó:   — e Zd ZdZdedeeee   ded   f   fd„Zy)ÚChata   This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
    to this format because the rest of the pipeline code tends to assume that lists of messages are
    actually a batch of samples rather than messages in the same conversation.ÚmessagesÚimagesúImage.Imagec                 ól   — |D ]  }d|v rd|v rŒt        d«      ‚ t        ||«      }|| _        || _        y )NÚroleÚcontentzQWhen passing chat dicts as input, each dict must have a 'role' and 'content' key.)Ú
ValueErrorÚretrieve_images_in_messagesr%   r&   )Úselfr%   r&   Úmessages       r"   Ú__init__zChat.__init__9   sJ   € Øò 	vˆGØ˜gÑ%¨)°wÒ*>Ü Ð!tÓuÐuð	vô -¨X°vÓ>ˆà ˆŒØˆ�r!   N)	r   r   r   Ú__doc__r   r   Ústrr   r/   r    r!   r"   r$   r$   4   s4   „ ñRð ð ¨u°S¸$¸s¹)À]ÐTXÐYfÑTgÐ5gÑ/hô r!   r$   r%   r&   r'   c                 ód  — |€g }nt        |t        «      s|g}d}g }| D ]õ  }|d   D ]ë  }t        |t        «      sŒ|j                  d«      dk(  rTdD ]  }||v sŒ|j	                  ||   «        ŒH |t        |«      k  r|j	                  ||   «       |dz  }Œqt        d«      ‚|j                  d«      dk(  sŒ‘t        |j                  d«      t        «      r2d	|d   v r+|j	                  |d   d	   «       d|d<   |d   d	   |d<   |d= Œât        d
«      ‚ Œ÷ |t        |«      k7  rt        d«      ‚|S )zS
    Retrieve and combine images from the chat and the images passed as input.
    r   r*   ÚtypeÚimage)r4   ÚurlÚpathÚbase64r   zlThe number of images in the chat messages should be the same as the number of images passed to the pipeline.Ú	image_urlr5   zhWrong format for 'image_url' content type. The content should have an 'image_url' dict with a 'url' key.)Ú
isinstancer   ÚdictÚgetÚappendÚlenr+   )r%   r&   Ú
idx_imagesÚretrieved_imagesr.   r*   Úkeys          r"   r,   r,   C   sy  € ð €~Ø‰Ü˜¤Ô)Ø�ˆØ€JØÐØò ˆØ˜yÑ)ò 	ˆGÜ˜'¤4Õ(Ø—;‘;˜vÓ&¨'Ò1ØAò ˜Ø 'š>Ø,×3Ñ3°G¸C±LÔAÙ!ðð
 &¬¨F«Ò3Ø,×3Ñ3°F¸:Ñ4FÔGØ&¨!™O™Jä",ð !Oó#ð ð —[‘[ Ó(¨KÓ7Ü! '§+¡+¨kÓ":¼DÔAÀeÈwÐWbÑOcÑFcØ(×/Ñ/°¸Ñ0DÀUÑ0KÔLà*1˜ ™Ø+2°;Ñ+?ÀÑ+F˜ Ñ(Ø# KÑ0ä(ð Góð ñ1	ðð< ”S˜“[Ò ÜØzó
ð 	
ð Ðr!   T)Úhas_processorc                   óü   ‡ — e Zd ZdZdZdZdZdZˆ fd„Z	 	 	 	 	 	 	 	 	 dde	e
   fd„Z	 	 ddeeeee   eee      d	ed	   eed	      f      d
eeeee   ee   f      fˆ fd„Zdd„Zdd„Zej*                  dfd„Zˆ xZS )ÚImageTextToTextPipelineac	  
    Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.
    When the underlying model is a conversational model, it can also accept one or more chats,
    in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).
    Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
    >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
    [{'generated_text': 'a photo of two birds'}]
    ```

    ```python
    >>> from transformers import pipeline

    >>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
    >>> messages = [
    >>>     {
    >>>         "role": "user",
    >>>         "content": [
    >>>             {
    >>>                 "type": "image",
    >>>                 "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
    >>>             },
    >>>             {"type": "text", "text": "Describe this image."},
    >>>         ],
    >>>     },
    >>>     {
    >>>         "role": "assistant",
    >>>         "content": [
    >>>             {"type": "text", "text": "There is a dog and"},
    >>>         ],
    >>>     },
    >>> ]
    >>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
    [{'input_text': [{'role': 'user',
        'content': [{'type': 'image',
        'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
        {'type': 'text', 'text': 'Describe this image.'}]},
    {'role': 'assistant',
        'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
    'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)

    This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:
    "image-text-to-text".

    See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text).
    TFc                 óf   •— t        ‰| �  |i |¤Ž t        | d«       | j                  t        «       y )NÚvision)Úsuperr/   r   Úcheck_model_typer   )r-   ÚargsÚkwargsÚ	__class__s      €r"   r/   z ImageTextToTextPipeline.__init__µ   s.   ø€ Ü‰Ñ˜$Ð) &Ò)Ü˜$ Ô)Ø×ÑÔHÕIr!   NrI   c
                 ó  — i }i }i }|j                  |
«       |�||d<   |	�|	|d<   |�||d<   |�#d|vri |d<   d|d   v rt        d«      ‚||d   d<   |�1|€/|�t        d«      ‚|rt        j                  nt        j                  }|�|€t        j
                  }|�||d<   |	�|	|d<   |�||d<   |�R| j                  j                  j                  |d	¬
«      }t        |«      dkD  rt        j                  d«       |d   |d<   |||fS )NÚtimeoutÚcontinue_final_messageÚgenerate_kwargsÚmax_new_tokenszp'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter, please use only onez>`return_full_text` is mutually exclusive with `return_tensors`Úreturn_typeÚclean_up_tokenization_spacesF)Úadd_special_tokensr   z©Stopping on a multiple token sequence is not yet supported on transformers. The first token of the stop sequence will be used as the stop sequence string in the interim.r   Úeos_token_id)Úupdater+   r   r   r   r   Ú	processorÚ	tokenizerÚencoder=   ÚloggerÚwarning_once)r-   rO   rN   rL   Úreturn_full_textÚreturn_tensorsrP   rQ   Ústop_sequencerM   rI   Úforward_kwargsÚpreprocess_paramsÚpostprocess_paramsÚstop_sequence_idss                  r"   Ú_sanitize_parametersz,ImageTextToTextPipeline._sanitize_parametersº   s‹  € ð ˆØÐØÐØ× Ñ  Ô(àÐØ+2Ð˜iÑ(à!Ð-Ø:PÐÐ6Ñ7àÐ&Ø0?ˆNÐ,Ñ-àÐ%Ø ¨Ñ6Ø46�Ð0Ñ1Ø >Ð2CÑ#DÑDÜ ð+óð ð CQˆNÐ,Ñ-Ð.>Ñ?àÐ'¨KÐ,?ØÐ)Ü Ð!aÓbÐbÙ2Bœ*×.Ò.Ì
×H[ÑH[ˆKØÐ%¨+Ð*=Ü$×,Ñ,ˆKØÐ"Ø0;Ð˜}Ñ-Ø!Ð-Ø;QÐÐ7Ñ8Ø'Ð3ØA]ÐÐ=Ñ>ØÐ$Ø $§¡× 8Ñ 8× ?Ñ ?ÀÐbgÐ ?Ó hÐÜÐ$Ó%¨Ò)Ü×#Ñ#ðbôð /@ÀÑ.BˆO˜NÑ+Ø  .Ð2DÐDÐDr!   r&   r'   Útextc                 óˆ  •— |€|€t        d«      ‚|�|€t        |«      s	 t        ‰| �  |fi |¤ŽS t	        |t
        t        t        f«      r”t	        |d   t
        t        t        f«      rvt	        |d   t        «      rt        ‰| �  t        ||«      fi |¤ŽS |€dgt        |«      z  }t        ||«      D ��cg c]  \  }}t        ||«      ‘Œ }}}t        ‰| �  |fi |¤ŽS t        | j                  dd«      �t        j                  d«       |€t        ‰| �  |fi |¤ŽS |€t        d«      ‚t        ‰| �  ||dœfi |¤ŽS c c}}w )aŒ  
        Generate a text given text and the image(s) passed as inputs.

        Args:
            images (`str`, `List[str]`, `PIL.Image or `List[PIL.Image]`):
                The pipeline handles three types of images:

                - A string containing a HTTP(s) link pointing to an image
                - A string containing a local path to an image
                - An image loaded in PIL directly

                The pipeline accepts either a single image or a batch of images.
            text (str, List[str], `List[Dict[str, Union[str, PIL.Image]]]`):
                The text to be used for generation. If a list of strings is passed, the length of the list should be the
                same as the number of images. Text can also follow the chat format: a list of dictionaries where each
                dictionary represents a message in a conversation. Each dictionary should have two keys: 'role' and
                'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of dictionary
                containing the text of the message and the type of the message. The type of the message can be either
                'text' or 'image'. If the type is 'image', no text is needed.
            return_tensors (`bool`, *optional*, defaults to `False`):
                Returns the tensors of predictions (as token indices) in the outputs. If set to
                `True`, the decoded text is not returned.
            return_text (`bool`, *optional*):
                Returns the decoded texts in the outputs.
            return_full_text (`bool`, *optional*, defaults to `True`):
                If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
                specified at the same time as `return_text`.
            clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
                Whether or not to clean up the potential extra spaces in the text output.
            continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
                last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
                By default this is `True` when the final message in the input chat has the `assistant` role and
                `False` otherwise, but you can manually override that behaviour by setting this flag.

        Return:
            A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot return a combination
            of both `generated_text` and `generated_token_ids`):

            - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
            - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
                ids of the generated text.
            - **input_text** (`str`) -- The input text.
        Nz0You must at least provide either text or images.r   Úchat_templatea
  The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even though this model supports chat. Consider using the chat format for better results. For more information, see https://huggingface.co/docs/transformers/en/chat_templatingz(You must provide text for this pipeline.)r&   rb   )r+   r   rF   Ú__call__r9   ÚlistÚtupler   r:   r$   r=   ÚzipÚgetattrrU   rX   rY   )r-   r&   rb   rI   Úchatr4   ÚchatsrJ   s          €r"   re   z ImageTextToTextPipeline.__call__õ   s_  ø€ ðf ˆ>˜d˜lÜÐOÓPÐPØÐ $ ,´|ÀFÔ7Kðô ‘7Ñ# FÑ5¨fÑ5Ð5ä�dœT¤5¬*Ð5Ô6¼:ÀdÈ1ÁgÔPTÔV[Ô]aÐObÔ;cä˜$˜q™'¤4Ô(Ü‘wÑ'¬¨T°6Ó(:ÑE¸fÑEÐEà�>Ø"˜V¤c¨$£iÑ/�FÜ>AÀ$ÈÓ>O×P©{¨t°Uœ˜d EÕ*ÐP�ÑPÜ‘wÑ'¨Ñ8°Ñ8Ð8ô �4—>‘> ?°DÓ9ÐEÜ×Ñð[ôð ˆ>Ü‘7Ñ# DÑ3¨FÑ3Ð3Øˆ<ÜÐGÓHÐHä‰wÑ¨6¸4Ñ @ÑKÀFÑKÐKùó! Qs   Â7D>c                 óD  — t        |t        t        t        f«      rd }|}|}nˆt        |t        «      r\|€|j
                  d   d   dk(  } | j                  j                  |j
                  f| || j                  dœ|¤Ž}|}|j                  }n|d   }|d   }|d   }t        ||¬«      }t        |t        t        f«      r t        |«      dkD  r|j                  d	d
«        | j                  d||| j                  dœ|¤Žj                  | j                  ¬«      }||d<   |S )Néÿÿÿÿr)   Ú	assistant)Úadd_generation_promptrM   r[   rb   r&   )rL   r   ÚpaddingT)r&   rb   r[   )Údtyper    )r9   rf   rg   r1   r$   r%   rU   Úapply_chat_templateÚ	frameworkr&   r   r=   Ú
setdefaultÚtoÚtorch_dtype)	r-   ÚinputsrL   rM   Úprocessing_kwargsr&   rb   Úinputs_textÚmodel_inputss	            r"   Ú
preprocessz"ImageTextToTextPipeline.preprocessM  s8  € ä�fœt¤U¬CÐ0Ô1ØˆFØˆDØ ‰Kä˜&¤$Ô'ð *Ð1Ø-3¯_©_¸RÑ-@ÀÑ-HÈKÑ-WÐ*Ø9�t—~‘~×9Ñ9Ø—O‘Oðà.DÐ*DØ+AØ#'§>¡>ñ	ð
 (ñ�ð %�ØŸ™‘à˜f‘~�Ø$ V™n�Ø Ñ)�ä  °Ô9ˆFô �dœT¤5˜MÔ*¬s°4«y¸1ª}Ø×(Ñ(¨°DÔ9Ø%�t—~‘~Ðs¨V¸$ÈtÏ~É~ÑsÐarÑs×vÑvØ×"Ñ"ð wó 
ˆð  +ˆ�VÑàÐr!   c                 ó”   — |€i n|}|j                  d«      }d|v r|d   n|d   } | j                  j                  di |¤|¤Ž}|||dœS )Nrb   Ú	input_idsÚdecoder_input_ids)Úgenerated_sequenceÚprompt_textr}   r    )ÚpopÚmodelÚgenerate)r-   rz   rN   r€   r}   r   s         r"   Ú_forwardz ImageTextToTextPipeline._forwardt  si   € Ø /Ð 7™"¸_ˆØ"×&Ñ& vÓ.ˆà)4¸Ñ)DˆL˜Ò%È,ÐWjÑJkð 	ð 1˜TŸZ™Z×0Ñ0ÑS°<ÐSÀ?ÑSÐà&8ÈÐclÑmÐmr!   c                 ó   — |d   }t        |t        t        f«      r|gn|}|d   }|d   }|t        j                  k(  r+t        t        |«      «      D �cg c]  }||   ||   dœ‘Œ c}S  | j                  j                  |fi |¤Ž}	 | j                  j                  |fi |¤Ž}
|t        j                  t        j                  hv rig }t        |	|
«      D ]V  \  }}|j                  |«      }d|cxk  rdk  r$n n!|j                  ||t        |«      z   d  «       ŒF|j                  |«       ŒX |}	|t        j                  k(  �rg }t        ||	«      D ]ñ  \  }}t        |t        «      r||z   }nÅt        |t        «      rµ|€|j                  d   d   d	k(  }|r€t        |j                  d   d
   d   j!                  «       «      }|dxx   |z  cc<   t#        |j                  «      d d |j                  d   d   |j                  d   d
   d d |gz   dœgz   }nt#        |j                  «      d	|dœgz   }|j                  |«       Œó |}	t        ||	«      D ��cg c]&  \  }}t        |t        «      r|j                  n||dœ‘Œ( }}}|S c c}w c c}}w )Nr€   r   r}   )Ú
input_textÚgenerated_token_idsr   r   rm   r)   rn   r*   rb   )r)   r*   )r†   Úgenerated_text)r9   r1   r$   r   r   Úranger=   rU   Úpost_process_image_text_to_textr   r   rh   Úfindr<   r%   r:   Úitemsrf   )r-   Úmodel_outputsrP   rM   Úpostprocess_kwargsÚinput_textsr   r}   ÚiÚgenerated_textsÚdecoded_inputsÚnew_generated_textsÚtext_generatedÚdecoded_inputÚindex_input_textÚ
full_textsr€   rˆ   Únew_textr†   Úrecordss                        r"   Úpostprocessz#ImageTextToTextPipeline.postprocess~  sð  € ð $ MÑ2ˆÜ'1°+ÄÄT¸{Ô'K�{‘mÐQ\ˆØ*Ð+?Ñ@ÐØ! +Ñ.ˆ	Øœ*×,Ñ,Ò,ô œs ;Ó/Ó0öàð  +¨1™~ÐFXÐYZÑF[Ó\òð ð I˜$Ÿ.™.×HÑHÐI[ÑrÐ_qÑrˆØG˜Ÿ™×GÑGÈ	ÑhÐUgÑhˆð œ:×.Ñ.´
×0DÑ0DÐEÑEð #%ÐÜ14°_ÀnÓ1Uò ?Ñ-� à#1×#6Ñ#6°}Ó#EÐ àÐ(Ô-¨AÕ-à'×.Ñ.¨~Ð>NÔQTÐUbÓQcÑ>cÐ>eÐ/fÕgà'×.Ñ.¨~Õ>ð?ð 2ˆOØœ*×.Ñ.Ó.ØˆJÜ/2°;ÀÓ/Pò 2Ñ+�˜^Ü˜k¬3Ô/Ø%0°>Ñ%A‘NÜ ¬TÔ2Ø-Ð5ð 2=×1EÑ1EÀbÑ1IÈ&Ñ1QÐU`Ñ1`Ð.Ù-ä#'¨×(<Ñ(<¸RÑ(@ÀÑ(KÈBÑ(O×(UÑ(UÓ(WÓ#X˜Ø  Ó(¨NÑ:Ó(Ü)-¨k×.BÑ.BÓ)CÀCÀRÐ)Hà(3×(<Ñ(<¸RÑ(@ÀÑ(HØ+6×+?Ñ+?ÀÑ+CÀIÑ+NÈsÐPRÐ+SÐW_ÐV`Ñ+`ñðLñ *™ô *.¨k×.BÑ.BÓ)CØ%0¸^ÑLðGñ *˜ð ×!Ñ! .Õ1ð/2ð0 )ˆOô /2°+¸Ó.O÷
ñ
 +�
˜Nô 6@À
ÌDÔ5Q˜j×1Ò1ÐWaØ"0óð
ˆñ 
ð ˆùòyùóh
s   ÁJÉ+J
)	NNNNNNNNN)NN)NNN)N)r   r   r   r0   Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr/   r
   r	   ra   r   r   r1   r   r:   re   r{   r„   r   r   rš   Ú__classcell__)rJ   s   @r"   rC   rC   u   só   ø„ ñ7ðr €OØ!ÐØ#ÐØ€OôJð ØØØØØØ%)ØØ#ñ9Eð Ð)Ñ*ó9Eð~ Ø<@ñVLàØ�#�t˜C‘y $ t¨C¡y¡/°=À$À}ÑBUÐW[Ð\`ÐanÑ\oÑWpÐpÑqñ
ðVLð
 �u˜S $ s¡)¨T°$©ZÐ7Ñ8Ñ9õVLóp%óNnð *4×)=Ñ)=ÐVZ÷Dr!   rC   )(ÚenumÚcollections.abcr   Útypingr   r   r   r   Úprocessing_utilsr	   r
   Úutilsr   r   r   r   r   Úbaser   r   ÚPILr   Úimage_utilsr   r   Úmodels.auto.modeling_autor   Úpt_utilsr   Ú
get_loggerr   rX   ÚIMAGE_TOKENÚEnumr   r$   r:   r1   r,   rC   r    r!   r"   ú<module>r­      sÎ   ðó  Ý $ß .Ó .ç 7÷õ ÷ 5ñ ÔÝç7ñ ÔÝVÝ$à	ˆ×	Ñ	˜HÓ	%€à€ô�—‘ô ÷ñ ð/Øð/Ø$ U¨3°°S±	¸=È$È}ÑJ]Ð+]Ñ%^Ñ_ó/ñd Ñ,¸4Ô@ÓAôL˜hó Ló BñLr!   