ó
    ‰Ž¡j™(  ã                   ó  • S SK JrJrJr  SSKJrJrJrJrJ	r	  SSK
JrJr  \" 5       (       a  S SKJr  SSKJrJr  \" 5       (       a  S SKrS S	KJr  SS
KJr  \R.                  " \5      r\" \" SS95       " S S\5      5       rg)é    )ÚAnyÚUnionÚoverloadé   )Úadd_end_docstringsÚis_torch_availableÚis_vision_availableÚloggingÚrequires_backendsé   )ÚChunkPipelineÚbuild_pipeline_init_args)ÚImage)Ú
load_imageÚvalid_imagesN)ÚBaseModelOutput)Ú2MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMEST)Úhas_image_processorc                   óˆ  ^ • \ rS rSrSrSrSrSrSrU 4S jr	\
S\\S4   S\\\   -  S	\S
\\\\4      4S j5       r\
S\\\\4      S	\S
\\\\\4         4S j5       r SS\\S\\\\4      4   S\\\   -  S-  S	\S
\\\\4      \\\\\4         -  4U 4S jjjrS rSS jrS rSS jrSSS
\\\4   4S jrSrU =r$ )ÚZeroShotObjectDetectionPipelineé   aN  
Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of
objects when you provide an image and a set of `candidate_labels`.

Example:

```python
>>> from transformers import pipeline

>>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
>>> detector(
...     "http://images.cocodataset.org/val2017/000000039769.jpg",
...     candidate_labels=["cat", "couch"],
... )
[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]

>>> detector(
...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
...     candidate_labels=["head", "bird"],
... )
[{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]
```

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

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

See the list of available models on
[huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection).
FTc                 óh   >• [         TU ]  " S0 UD6  [        U S5        U R                  [        5        g )NÚvision© )ÚsuperÚ__init__r   Úcheck_model_typer   )ÚselfÚkwargsÚ	__class__s     €Ú¿C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\transformers/pipelines/zero_shot_object_detection.pyr   Ú(ZeroShotObjectDetectionPipeline.__init__=   s,   ø€ Ü‰ÒÑ"˜6Ò"ä˜$ Ô)Ø×ÑÔPÕQó    ÚimagezImage.ImageÚcandidate_labelsr   Úreturnc                 ó   • g ©Nr   )r   r$   r%   r   s       r!   Ú__call__Ú(ZeroShotObjectDetectionPipeline.__call__C   s   € ð  #r#   c                 ó   • g r(   r   )r   r$   r   s      r!   r)   r*   H   s   € Øber#   Nc           	      ó\  >• SU;   a  UR                  S5      n[        U[        [        R                  45      (       a  XS.nOX[        U[        [
        45      (       a:  [        U5      (       a*  [	        [        TU ]   " S [        X5       5       40 UD65      $  Un[        TU ]   " U40 UD6nU$ )a$  
Detect objects (bounding boxes & classes) in the image(s) passed as inputs.

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

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

        You can use this parameter to send directly a list of images, or a dataset or a generator like so:

        ```python
        >>> from transformers import pipeline

        >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
        >>> detector(
        ...     [
        ...         {
        ...             "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
        ...             "candidate_labels": ["cat", "couch"],
        ...         },
        ...         {
        ...             "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
        ...             "candidate_labels": ["cat", "couch"],
        ...         },
        ...     ]
        ... )
        [[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]]
        ```


    candidate_labels (`str` or `list[str]` or `list[list[str]]`):
        What the model should recognize in the image.

    threshold (`float`, *optional*, defaults to 0.1):
        The probability necessary to make a prediction.

    top_k (`int`, *optional*, defaults to None):
        The number of top predictions that will be returned by the pipeline. If the provided number is `None`
        or higher than the number of predictions available, it will default to the number of predictions.

    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 lists containing prediction results, one list per input image. Each list contains dictionaries
    with the following keys:

    - **label** (`str`) -- Text query corresponding to the found object.
    - **score** (`float`) -- Score corresponding to the object (between 0 and 1).
    - **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a
      dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.
Útext_queries©r$   r%   c              3   ó.   #   • U  H  u  pXS .v •  M     g7f)r.   Nr   )Ú.0ÚimgÚlabelss      r!   Ú	<genexpr>Ú;ZeroShotObjectDetectionPipeline.__call__.<locals>.<genexpr>’   s   é € ÐpÒSoÁKÀC˜sÖ?ÒSoùs   ‚)
ÚpopÚ
isinstanceÚstrr   ÚlistÚtupler   r   r)   Úzip)r   r$   r%   r   ÚinputsÚresultsr    s         €r!   r)   r*   K   s¬   ø€ ð~ ˜VÓ#Ø%Ÿz™z¨.Ó9Ðä�eœc¤5§;¡;Ð/×0Ñ0Ø$ÑK‰FÜ˜¤¤e˜}×-Ñ-´,¸u×2EÑ2EÜÜ‘Ò ÙpÔSVÐW\ÔSoÓpñàñóð ðð ˆFä‘'Ò" 6Ñ4¨VÑ4ˆØˆr#   c                 óh   • 0 nSU;   a  US   US'   0 nSU;   a  US   US'   SU;   a  US   US'   U0 U4$ )NÚtimeoutÚ	thresholdÚtop_kr   )r   r   Úpreprocess_paramsÚpostprocess_paramss       r!   Ú_sanitize_parametersÚ4ZeroShotObjectDetectionPipeline._sanitize_parameters£   sc   € ØÐØ˜ÓØ+1°)Ñ+<Ð˜iÑ(ØÐØ˜&Ó Ø.4°[Ñ.AÐ˜{Ñ+Ø�fÓØ*0°©/Ð˜wÑ'Ø  "Ð&8Ð8Ð8r#   c              #   óÄ  #   • [        US   US9nUS   n[        U[        5      (       a  UR                  S5      n[        R
                  " UR                  UR                  //[        R                  S9n[        U5       H[  u  pgU R                  USS9nU R                  USS9n	U	R                  U R                  5      n	U[        U5      S-
  :H  UUS	.UEU	Ev •  M]     g 7f)
Nr$   )r>   r%   Ú,)ÚdtypeÚpt)Úreturn_tensorsr   )Úis_lastÚtarget_sizeÚcandidate_label)r   r6   r7   ÚsplitÚtorchÚtensorÚheightÚwidthÚint32Ú	enumerateÚ	tokenizerÚimage_processorÚtorG   Úlen)
r   r;   r>   r$   r%   rK   ÚirL   Útext_inputsÚimage_featuress
             r!   Ú
preprocessÚ*ZeroShotObjectDetectionPipeline.preprocess®   sé   é € Ü˜6 '™?°GÑ<ˆØ!Ð"4Ñ5ÐÜÐ&¬×,Ñ,Ø/×5Ñ5°cÓ:Ðä—l’l U§\¡\°5·;±;Ð$?Ð#@ÌÏÉÑTˆÜ"+Ð,<Ö"=ÑˆAØŸ.™.¨È˜.ÐNˆKØ!×1Ñ1°%ÈÐ1ÐMˆNØ+×.Ñ.¨t¯z©zÓ:ˆNà¤Ð$4Ó 5¸Ñ 9Ñ9Ø*Ø#2ñð ð	ð
 !ðô ò	 #>ùs   ‚CC c                 óž   • UR                  S5      nUR                  S5      nUR                  S5      nU R                  " S0 UD6nX#US.UEnU$ )NrK   rL   rJ   )rK   rL   rJ   r   )r5   Úmodel)r   Úmodel_inputsrK   rL   rJ   ÚoutputsÚmodel_outputss          r!   Ú_forwardÚ(ZeroShotObjectDetectionPipeline._forwardÁ   s[   € Ø"×&Ñ& }Ó5ˆØ&×*Ñ*Ð+<Ó=ˆØ×"Ñ" 9Ó-ˆà—*’*Ñ,˜|Ñ,ˆà(3ÐdkÑwÐovÐwˆØÐr#   c                 ól  • / nU H“  nUS   n[        U5      nU R                  R                  XRUS   S9S   nUS   R                  5        HI  nUS   U   R	                  5       n	U R                  US   U   S   5      n
X–U
S.nUR                  U5        MK     M•     [        US S	S
9nU(       a  US U nU$ )NrL   rK   )r`   r?   Útarget_sizesr   ÚscoresÚboxes)ÚscoreÚlabelÚboxc                 ó   • U S   $ )Nrh   r   )Úxs    r!   Ú<lambda>Ú=ZeroShotObjectDetectionPipeline.postprocess.<locals>.<lambda>Û   s   € °°'²
r#   T)ÚkeyÚreverse)r   rU   Úpost_process_object_detectionÚnonzeroÚitemÚ_get_bounding_boxÚappendÚsorted)r   ra   r?   r@   r<   Úmodel_outputri   r`   Úindexrh   rj   Úresults               r!   ÚpostprocessÚ+ZeroShotObjectDetectionPipeline.postprocessË   sà   € ØˆÛ)ˆLØ Ð!2Ñ3ˆEÜ*¨<Ó8ˆLØ×*Ñ*×HÑHØ$ÈÐUbÑHcð Ið àñˆGð ! Ñ*×2Ñ2Ö4�Ø Ñ)¨%Ñ0×5Ñ5Ó7�Ø×,Ñ,¨W°WÑ-=¸eÑ-DÀQÑ-GÓH�à#(ÀÑE�Ø—‘˜vÖ&ó 5ñ *ô ˜Ñ&:ÀDÑIˆÞØ˜f˜u�oˆGàˆr#   rj   ztorch.Tensorc                 óV   • UR                  5       R                  5       u  p#pEUUUUS.nU$ )zõ
Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }

Args:
    box (`torch.Tensor`): Tensor containing the coordinates in corners format.

Returns:
    bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
)ÚxminÚyminÚxmaxÚymax)ÚintÚtolist)r   rj   r}   r~   r   r€   Úbboxs          r!   rt   Ú1ZeroShotObjectDetectionPipeline._get_bounding_boxá   s7   € ð "%§¡£×!1Ñ!1Ó!3Ñˆ�DàØØØñ	
ˆð ˆr#   r   r(   )gš™™™™™¹?N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r   r   r7   r8   r   Údictr)   rC   r[   rb   rz   r�   rt   Ú__static_attributes__Ú__classcell__)r    s   @r!   r   r      sw  ø† ñð@ €OØ ÐØ#ÐØ€OõRð ð#Ø˜3 Ð-Ñ.ð#ØBEÈÈSÉ	Á/ð#Ø]`ð#à	ˆd�3˜�8‰nÑ	ó#ó ð#ð Øe˜d 4¨¨S¨¡>Ñ2Ðe¸cÐeÀdÈ4ÐPTÐUXÐZ]ÐU]ÑP^ÑK_ÑF`Óeó Øeð
 48ñVà�S˜-¨¨d°3¸°8©nÑ)=Ð=Ñ>ðVð   S¡	™/¨DÑ0ðVð ð	Vð
 
ˆd�3˜�8‰nÑ	  T¨$¨s°C¨x©.Ñ%9Ñ :Ñ	:÷Vð Vòp	9ôò&ôð, ^ð ¸¸SÀ#¸X¹÷ ò r#   r   )Útypingr   r   r   Úutilsr   r   r	   r
   r   Úbaser   r   ÚPILr   Úimage_utilsr   r   rN   Útransformers.modeling_outputsr   Úmodels.auto.modeling_autor   Ú
get_loggerr…   Úloggerr   r   r#   r!   Ú<module>rš      sq   ðß 'Ñ 'ç kÕ kß 9ñ ×ÑÝç6á×ÑÛå=å^à	×	Ò	˜HÓ	%€ñ Ñ,ÀÑFÓGô[ mó [ó Hñ[r#   