Ë
    îÍ:jÂ!  ã                   óö   — d dl mZ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  e«       rddlmZ  e«       rd dlZddlmZmZ erd d	lmZ  e	j,                  e«      Z e ed
¬«      «       G d„ de«      «       Zy)é    )ÚTYPE_CHECKINGÚAnyÚUnionÚoverloadé   )Úadd_end_docstringsÚis_torch_availableÚis_vision_availableÚloggingÚrequires_backendsé   )ÚPipelineÚbuild_pipeline_init_args)Ú
load_imageN)Ú(MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMESÚ,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)ÚImageT)Úhas_image_processorc                   ó2  ‡ — e Zd ZdZdZdZdZdZˆ fd„Zd„ Z	e
deedf   d	ed
edeeeef      fd„«       Ze
deee   ed   f   d	ed
edeeeeef         fd„«       Zdeeeeef      eeeeef         f   fˆ fd„Zdd„Zd„ Zdd„Zdddeeef   fd„Zˆ xZS )ÚObjectDetectionPipelineaò  
    Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
    and their classes.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> detector = pipeline(model="facebook/detr-resnet-50")
    >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
    [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]

    >>> # x, y  are expressed relative to the top left hand corner.
    ```

    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:
    `"object-detection"`.

    See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).
    FTNc                 ó   •— t        ‰| �  |i |¤Ž | j                  dk(  rt        d| j                  › d�«      ‚t        | d«       t        j                  «       }|j                  t        «       | j                  |«       y )NÚtfzThe z is only available in PyTorch.Úvision)ÚsuperÚ__init__Ú	frameworkÚ
ValueErrorÚ	__class__r   r   ÚcopyÚupdater   Úcheck_model_type)ÚselfÚargsÚkwargsÚmappingr   s       €ú|/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/transformers/pipelines/object_detection.pyr   z ObjectDetectionPipeline.__init__8   sn   ø€ Ü‰Ñ˜$Ð) &Ò)à�>‰>˜TÒ!Ü˜t D§N¡NÐ#3Ð3QÐRÓSÐSä˜$ Ô)Ü:×?Ñ?ÓAˆØ�‰ÔCÔDØ×Ñ˜gÕ&ó    c                 óD   — i }d|v r|d   |d<   i }d|v r|d   |d<   |i |fS )NÚtimeoutÚ	threshold© )r"   r$   Úpreprocess_paramsÚpostprocess_kwargss       r&   Ú_sanitize_parametersz,ObjectDetectionPipeline._sanitize_parametersC   sL   € ØÐØ˜ÑØ+1°)Ñ+<Ð˜iÑ(ØÐØ˜&Ñ Ø.4°[Ñ.AÐ˜{Ñ+Ø  "Ð&8Ð8Ð8r'   ÚimagezImage.Imager#   r$   Úreturnc                  ó   — y ©Nr+   ©r"   r/   r#   r$   s       r&   Ú__call__z ObjectDetectionPipeline.__call__L   s   € Ømpr'   c                  ó   — y r2   r+   r3   s       r&   r4   z ObjectDetectionPipeline.__call__O   s   € ð &)r'   c                 óZ   •— d|v rd|vr|j                  d«      |d<   t        ‰| �  |i |¤ŽS )ai  
        Detect objects (bounding boxes & classes) in the image(s) passed as inputs.

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

                - A string containing an 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. Images in a batch must all be in the
                same format: all as HTTP(S) links, all as local paths, or all as PIL images.
            threshold (`float`, *optional*, defaults to 0.5):
                The probability necessary to make a prediction.
            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 or a list of list of dictionaries containing the result. If the input is a single
            image, will return a list of dictionaries, if the input is a list of several images, will return a list of
            list of dictionaries corresponding to each image.

            The dictionaries contain the following keys:

            - **label** (`str`) -- The class label identified by the model.
            - **score** (`float`) -- The score attributed by the model for that label.
            - **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.
        ÚimagesÚinputs)Úpopr   r4   )r"   r#   r$   r   s      €r&   r4   z ObjectDetectionPipeline.__call__T   s=   ø€ ð@ �vÑ (°&Ñ"8Ø%Ÿz™z¨(Ó3ˆF�8ÑÜ‰wÑ Ð0¨Ñ0Ð0r'   c                 óJ  — t        ||¬«      }t        j                  |j                  |j                  gg«      }| j                  |gd¬«      }| j                  dk(  r|j                  | j                  «      }| j                  �| j                  |d   |d   d¬«      }||d<   |S )N)r)   Úpt)r7   Úreturn_tensorsÚwordsÚboxes)Útextr>   r<   Útarget_size)
r   ÚtorchÚ	IntTensorÚheightÚwidthÚimage_processorr   ÚtoÚdtypeÚ	tokenizer)r"   r/   r)   r@   r8   s        r&   Ú
preprocessz"ObjectDetectionPipeline.preprocessx   s—   € Ü˜5¨'Ô2ˆÜ—o‘o¨¯©°e·k±kÐ'BÐ&CÓDˆØ×%Ñ%¨e¨WÀTÐ%ÓJˆØ�>‰>˜TÒ!Ø—Y‘Y˜tŸz™zÓ*ˆFØ�>‰>Ð%Ø—^‘^¨°©ÀÀwÁÐ`d�^ÓeˆFØ +ˆˆ}ÑØˆr'   c                 óž   — |j                  d«      } | j                  di |¤Ž}|j                  d|i|¥«      }| j                  �|d   |d<   |S )Nr@   Úbboxr+   )r9   Úmodelr   rH   )r"   Úmodel_inputsr@   ÚoutputsÚmodel_outputss        r&   Ú_forwardz ObjectDetectionPipeline._forwardƒ   s^   € Ø"×&Ñ& }Ó5ˆØ�$—*‘*Ñ,˜|Ñ,ˆØ×)Ñ)¨=¸+Ð*QÈÐ*QÓRˆØ�>‰>Ð%Ø$0°Ñ$8ˆM˜&Ñ!ØÐr'   c           	      ó6  ‡ ‡‡— |d   }‰ j                   ��|d   j                  «       \  ŠŠˆˆ ˆfd„}|d   j                  d«      j                  d¬«      j	                  d¬«      \  }}|j                  «       D �cg c]%  }‰ j
                  j                  j                  |   ‘Œ' }}|d   j                  d«      D �	cg c]
  }	 ||	«      ‘Œ }
}	g d¢}t        |j                  «       ||
«      D �cg c]   }|d   |kD  sŒt        t        ||«      «      ‘Œ" }}|S ‰ j                  j                  |||«      }|d   }|d	   }|d
   }|d   }
|j                  «       |d	<   |D �cg c]3  }‰ j
                  j                  j                  |j                  «          ‘Œ5 c}|d
<   |
D �cg c]  }‰ j                  |«      ‘Œ c}|d<   g d¢}t        |d	   |d
   |d   «      D �cg c]  }t        t        ||«      «      ‘Œ }}|S c c}w c c}	w c c}w c c}w c c}w c c}w )Nr@   r   c           
      óœ   •— ‰j                  t        j                  ‰| d   z  dz  ‰| d   z  dz  ‰| d   z  dz  ‰| d   z  dz  g«      «      S )Nr   iè  r   r   é   )Ú_get_bounding_boxrA   ÚTensor)rK   rC   r"   rD   s    €€€r&   Úunnormalizez8ObjectDetectionPipeline.postprocess.<locals>.unnormalize’   si   ø€ Ø×-Ñ-Ü—L‘Là" T¨!¡W™_¨tÑ3Ø# d¨1¡gÑ-°Ñ4Ø" T¨!¡W™_¨tÑ3Ø# d¨1¡gÑ-°Ñ4ð	óó	ð 	r'   Úlogitséÿÿÿÿ)ÚdimrK   )ÚscoreÚlabelÚboxÚscoresÚlabelsr>   )rH   ÚtolistÚsqueezeÚsoftmaxÚmaxrL   ÚconfigÚid2labelÚzipÚdictrE   Úpost_process_object_detectionÚitemrT   )r"   rO   r*   r@   rV   r]   ÚclassesÚ
predictionr^   rK   r>   ÚkeysÚvalsÚ
annotationÚraw_annotationsÚraw_annotationr[   r\   rC   rD   s   `                 @@r&   Úpostprocessz#ObjectDetectionPipeline.postprocess‹   s$  ú€ Ø# MÑ2ˆØ�>‰>Ñ%ð (¨™N×1Ñ1Ó3‰MˆF�Eö
ð ,¨HÑ5×=Ñ=¸aÓ@×HÑHÈRÐHÓP×TÑTÐY[ÐTÓ\‰OˆF�GØOVÏ~É~ÓO_Ö`À�d—j‘j×'Ñ'×0Ñ0°Ó<Ð`ˆFÐ`Ø3@ÀÑ3H×3PÑ3PÐQRÓ3SÖT¨4‘[ Õ&ÐTˆEÐTÚ,ˆDÜ<?ÀÇÁÃÐQWÐY^Ó<_Öw°DÐcgÐhiÑcjÐmvÓcvœ$œs 4¨›Õ/ÐwˆJÐwð( Ðð# #×2Ñ2×PÑPÐQ^Ð`iÐkvÓwˆOØ,¨QÑ/ˆNØ# HÑ-ˆFØ# HÑ-ˆFØ" 7Ñ+ˆEà'-§}¡}£ˆN˜8Ñ$Ø^dÖ'eÐUZ¨¯
©
×(9Ñ(9×(BÑ(BÀ5Ç:Á:Ã<Ó(PÒ'eˆN˜8Ñ$ØNSÖ&TÀs t×'=Ñ'=¸cÕ'BÒ&TˆN˜7Ñ#ò -ˆDô   ¨xÑ 8¸.ÈÑ:RÐTbÐcjÑTkÓlöàô ”S˜˜t“_Õ%ðˆJð ð
 Ðùò/ aùÚTùâwùò (fùÚ&Tùòs*   Á<*G=Â>HÃ0HÃ>HÅ!8HÆ#HÇHr\   ztorch.Tensorc                 óŽ   — | j                   dk7  rt        d«      ‚|j                  «       j                  «       \  }}}}||||dœ}|S )a%  
        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.
        r;   z9The ObjectDetectionPipeline is only available in PyTorch.)ÚxminÚyminÚxmaxÚymax)r   r   Úintr_   )r"   r\   rr   rs   rt   ru   rK   s          r&   rT   z)ObjectDetectionPipeline._get_bounding_box¸   sS   € ð �>‰>˜TÒ!ÜÐXÓYÐYØ!$§¡£×!1Ñ!1Ó!3Ñˆˆd�D˜$àØØØñ	
ˆð ˆr'   r2   )g      à?)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r.   r   r   Ústrr   Úlistrf   r4   rI   rP   rp   rv   rT   Ú__classcell__)r   s   @r&   r   r      s(  ø„ ñð0 €OØ ÐØ#ÐØ€Oô	'ò9ð Øp˜e C¨Ð$6Ñ7ÐpÀÐpÈsÐpÐW[Ð\`ÐadÐfiÐaiÑ\jÑWkÒpó Øpàð)Ø˜4 ™9 d¨=Ñ&9Ð9Ñ:ð)ØCFð)ØRUð)à	ˆd�4˜˜S˜‘>Ñ"Ñ	#ò)ó ð)ð"1¨5°°d¸3À¸8±nÑ1EÀtÈDÐQUÐVYÐ[^ÐV^ÑQ_ÑL`ÑGaÐ1aÑ+bõ "1óH	òó+ðZ ^ð ¸¸SÀ#¸X¹÷ r'   r   )Útypingr   r   r   r   Úutilsr   r	   r
   r   r   Úbaser   r   Úimage_utilsr   rA   Úmodels.auto.modeling_autor   r   ÚPILr   Ú
get_loggerrw   Úloggerr   r+   r'   r&   ú<module>rŠ      ss   ðß 6Ó 6ç kÕ kß 4ñ ÔÝ(ñ ÔÛ÷ñ
 Ýà	ˆ×	Ñ	˜HÓ	%€ñ Ñ,ÀÔFÓGôq˜hó qó Hñqr'   