Ë
    T^(h2  ã                   ó$  — d dl Z d dlmZ d dl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  e
«       rd dlmZ dd	lmZ  e	«       r
d dlZdd
lmZ  e«       rddlmZ ddlmZ  ej6                  e«      Z e ed¬«      «       G d„ de«      «       Zy)é    N)ÚUserDict)ÚListÚUnioné   )Úadd_end_docstringsÚis_tf_availableÚis_torch_availableÚis_vision_availableÚloggingÚrequires_backendsé   )ÚPipelineÚbuild_pipeline_init_args)ÚImage)Ú
load_image)Ú6MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES)Ú9TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES)Ústable_softmaxT)Úhas_image_processorc                   ór   ‡ — e Zd ZdZˆ fd„Zd
deeee   ded   f   fˆ fd„Zd
d„Z		 	 	 	 dd„Z
d„ Zd	„ Zˆ xZS )Ú#ZeroShotImageClassificationPipelineaL  
    Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you
    provide an image and a set of `candidate_labels`.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
    >>> classifier(
    ...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
    ...     candidate_labels=["animals", "humans", "landscape"],
    ... )
    [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]

    >>> classifier(
    ...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
    ...     candidate_labels=["black and white", "photorealist", "painting"],
    ... )
    [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
    ```

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

    This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"zero-shot-image-classification"`.

    See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).
    c                 óš   •— t        ‰| �  di |¤Ž t        | d«       | j                  | j                  dk(  rt
        «       y t        «       y )NÚvisionÚtf© )ÚsuperÚ__init__r   Úcheck_model_typeÚ	frameworkr   r   )ÚselfÚkwargsÚ	__class__s     €ús/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/zero_shot_image_classification.pyr   z,ZeroShotImageClassificationPipeline.__init__C   sH   ø€ Ü‰ÑÑ"˜6Ò"ä˜$ Ô)Ø×Ñà�~‰~ Ò%ô Fõ	
ô Hõ	
ó    Úimager   c                 óh   •— d|v r|j                  d«      }|€t        d«      ‚t        ‰| �  |fi |¤ŽS )aó  
        Assign labels to the image(s) passed as inputs.

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

                - A string containing a http link pointing to an image
                - A string containing a local path to an image
                - An image loaded in PIL directly

            candidate_labels (`List[str]`):
                The candidate labels for this image. They will be formatted using *hypothesis_template*.

            hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`):
                The format used in conjunction with *candidate_labels* to attempt the image classification by
                replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
                already formatted.

            timeout (`float`, *optional*, defaults to None):
                The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
                the call may block forever.

        Return:
            A list of dictionaries containing one entry per proposed label. Each dictionary contains the
            following keys:
            - **label** (`str`) -- One of the suggested *candidate_labels*.
            - **score** (`float`) -- The score attributed by the model to that label. It is a value between
                0 and 1, computed as the `softmax` of `logits_per_image`.
        ÚimageszSCannot call the zero-shot-image-classification pipeline without an images argument!)ÚpopÚ
ValueErrorr   Ú__call__)r    r%   r!   r"   s      €r#   r*   z,ZeroShotImageClassificationPipeline.__call__M   sB   ø€ ð@ �vÑØ—J‘J˜xÓ(ˆEØˆ=ÜÐrÓsÐsÜ‰wÑ Ñ0¨Ñ0Ð0r$   c                 óš   — i }d|v r|d   |d<   d|v r|d   |d<   d|v r|d   |d<   |�t        j                  dt        «       ||d<   |i i fS )NÚcandidate_labelsÚtimeoutÚhypothesis_templatez^The `tokenizer_kwargs` argument is deprecated and will be removed in version 5 of TransformersÚtokenizer_kwargs)ÚwarningsÚwarnÚFutureWarning)r    r/   r!   Úpreprocess_paramss       r#   Ú_sanitize_parametersz8ZeroShotImageClassificationPipeline._sanitize_parameterss   sˆ   € ØÐØ Ñ'Ø4:Ð;MÑ4NÐÐ0Ñ1Ø˜ÑØ+1°)Ñ+<Ð˜iÑ(Ø  FÑ*Ø7=Ð>SÑ7TÐÐ3Ñ4ØÐ'Ü�M‰MØpÜôð 5EÐÐ0Ñ1à  " bÐ(Ð(r$   c                 óè  — |€i }t        ||¬«      }| j                  |g| j                  ¬«      }| j                  dk(  r|j                  | j                  «      }||d<   |D �cg c]  }|j                  |«      ‘Œ }}ddi}	d| j                  j                  j                  v r|	j                  dd	d¬
«       |	j                  |«        | j                  |fd| j                  i|	¤Ž}
|
g|d<   |S c c}w )N)r-   )r'   Úreturn_tensorsÚptr,   ÚpaddingTÚsiglipÚ
max_lengthé@   )r8   r:   Ú
truncationr6   Útext_inputs)r   Úimage_processorr   ÚtoÚtorch_dtypeÚformatÚmodelÚconfigÚ
model_typeÚupdateÚ	tokenizer)r    r%   r,   r.   r-   r/   ÚinputsÚxÚ	sequencesÚtokenizer_default_kwargsr=   s              r#   Ú
preprocessz.ZeroShotImageClassificationPipeline.preprocess„   sÿ   € ð Ð#Ø!ÐÜ˜5¨'Ô2ˆØ×%Ñ%¨e¨WÀTÇ^Á^Ð%ÓTˆØ�>‰>˜TÒ!Ø—Y‘Y˜t×/Ñ/Ó0ˆFØ%5ˆÐ!Ñ"Ø<LÖM°qÐ(×/Ñ/°Õ2ÐMˆ	ÐMØ$-¨tÐ#4Ð Ø�t—z‘z×(Ñ(×3Ñ3Ñ3Ø$×+Ñ+°LÈRÐ\`Ð+ÔaØ ×'Ñ'Ð(8Ô9Ø$�d—n‘n YÑj¸t¿~¹~ÐjÐQiÑjˆØ!, ˆˆ}ÑØˆùò Ns   Á#C/c                 óÒ   — |j                  d«      }|j                  d«      }t        |d   t        «      r|d   }n|d   d   } | j                  di |¤|¤Ž}||j                  dœ}|S )Nr,   r=   r   )r,   Úlogitsr   )r(   Ú
isinstancer   rB   Úlogits_per_image)r    Úmodel_inputsr,   r=   ÚoutputsÚmodel_outputss         r#   Ú_forwardz,ZeroShotImageClassificationPipeline._forwardœ   s€   € Ø'×+Ñ+Ð,>Ó?ÐØ"×&Ñ& }Ó5ˆÜ�k !‘n¤hÔ/Ø% a™.‰Kð & a™.¨Ñ+ˆKà�$—*‘*Ñ;˜{Ð;¨lÑ;ˆð !1Ø×.Ñ.ñ
ˆð Ðr$   c                 óÞ  — |j                  d«      }|d   d   }| j                  dk(  rjd| j                  j                  j                  v rHt        j                  |«      j                  d«      }|j                  «       }t        |t        «      s«|g}n§| j                  dk(  rE|j                  d¬«      j                  d«      }|j                  «       }t        |t        «      sW|g}nS| j                  dk(  r,t        |d¬	«      }|j                  «       j                  «       }nt        d
| j                  › �«      ‚t        t!        ||«      d„ ¬«      D ��cg c]
  \  }}||dœ‘Œ }}}|S c c}}w )Nr,   rM   r   r7   r9   éÿÿÿÿ)Údimr   )ÚaxiszUnsupported framework: c                 ó   — | d    S )Nr   r   )rH   s    r#   ú<lambda>zAZeroShotImageClassificationPipeline.postprocess.<locals>.<lambda>Â   s   € Ð_`ÐabÑ_cÐ^c€ r$   )Úkey)ÚscoreÚlabel)r(   r   rB   rC   rD   ÚtorchÚsigmoidÚsqueezeÚtolistrN   ÚlistÚsoftmaxr   Únumpyr)   ÚsortedÚzip)	r    rR   r,   rM   ÚprobsÚscoresr[   Úcandidate_labelÚresults	            r#   Úpostprocessz/ZeroShotImageClassificationPipeline.postprocess­   sF  € Ø(×,Ñ,Ð-?Ó@ÐØ˜xÑ(¨Ñ+ˆØ�>‰>˜TÒ! h°$·*±*×2CÑ2C×2NÑ2NÑ&NÜ—M‘M &Ó)×1Ñ1°"Ó5ˆEØ—\‘\“^ˆFÜ˜f¤dÔ+Ø ˜‘Ø�^‰^˜tÒ#Ø—N‘N r�NÓ*×2Ñ2°2Ó6ˆEØ—\‘\“^ˆFÜ˜f¤dÔ+Ø ˜‘Ø�^‰^˜tÒ#Ü" 6°Ô3ˆEØ—[‘[“]×)Ñ)Ó+‰FäÐ6°t·~±~Ð6FÐGÓHÐHô +1´°VÐ=MÓ1NÑTcÔ*d÷
á&��ð  oÓ6ð
ˆñ 
ð ˆùó	
s   ÅE))N)NzThis is a photo of {}.NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   Ústrr   r*   r4   rK   rS   rj   Ú__classcell__)r"   s   @r#   r   r   !   sS   ø„ ñô@
ñ$1˜e C¨¨c©°G¸TÀ'¹]Ð$JÑKõ $1óL)ð( Ø4ØØóò0ö"r$   r   )r0   Úcollectionsr   Útypingr   r   Úutilsr   r   r	   r
   r   r   Úbaser   r   ÚPILr   Úimage_utilsr   r]   Úmodels.auto.modeling_autor   Úmodels.auto.modeling_tf_autor   Útf_utilsr   Ú
get_loggerrk   Úloggerr   r   r$   r#   ú<module>r|      s   ðÛ Ý  ß ÷÷ ÷ 5ñ ÔÝå(áÔÛåbáÔÝhÝ)à	ˆ×	Ñ	˜HÓ	%€ñ Ñ,ÀÔFÓGôb¨(ó bó Hñbr$   