a
    d                     @   s   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 rVddlmZ e rtd dlZddlmZmZ e	eZeeef Zee ZeeG d	d
 d
eZdS )    )AnyDictListUnion   )add_end_docstringsis_torch_availableis_vision_availableloggingrequires_backends   )PIPELINE_INIT_ARGSPipeline)
load_imageN)"MODEL_FOR_OBJECT_DETECTION_MAPPING&MODEL_FOR_TOKEN_CLASSIFICATION_MAPPINGc                       sx   e Zd ZdZ fddZdd Zeeee	 f d fddZ
d	d
 Zdd ZdddZdeeef dddZ  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).
    c                    sV   t  j|i | | jdkr.td| j dt| d | tt	 t
	   d S )NtfzThe z is only available in PyTorch.Zvision)super__init__	framework
ValueError	__class__r   Zcheck_model_typedictr   itemsr   selfargskwargsr    p/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/pipelines/object_detection.pyr   1   s    

z ObjectDetectionPipeline.__init__c                 K   s"   i }d|v r|d |d< i i |fS )N	thresholdr    )r   r   Zpostprocess_kwargsr    r    r!   _sanitize_parameters<   s    z,ObjectDetectionPipeline._sanitize_parameters)returnc                    s   t  j|i |S )a  
        Detect objects (bounding boxes & classes) in 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 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.9):
                The probability necessary to make a prediction.

        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.
        )r   __call__r   r   r    r!   r%   B   s    z ObjectDetectionPipeline.__call__c                 C   sZ   t |}t|j|jgg}| j|gdd}| jd urN| j|d |d dd}||d< |S )Npt)Zimagesreturn_tensorswordsboxes)textr)   r'   target_size)r   torchZ	IntTensorheightwidthimage_processor	tokenizer)r   imager+   inputsr    r    r!   
preprocessa   s    
z"ObjectDetectionPipeline.preprocessc                 C   sF   | d}| jf i |}|d|i|}| jd urB|d |d< |S )Nr+   bbox)popmodelr   r0   )r   Zmodel_inputsr+   outputsmodel_outputsr    r    r!   _forwardj   s    

z ObjectDetectionPipeline._forward?c                    sJ  |d }j d ur|d  \  fdd|d djddjdd\}}fdd	| D }fd
d	|d dD }g dfdd	t| ||D }nj||}	|	d }
|
d }|
d }|
d }| |
d< fdd	|D |
d< fdd	|D |
d< g dfdd	t|
d |
d |
d D }|S )Nr+   r   c              
      sH    t| d  d  | d  d | d  d  | d  d gS )Nr   i  r   r      )_get_bounding_boxr,   ZTensor)r4   )r-   r   r.   r    r!   unnormalizey   s    z8ObjectDetectionPipeline.postprocess.<locals>.unnormalizeZlogits)Zdimc                    s   g | ]} j jj| qS r    )r6   configid2label).0Z
predictionr   r    r!   
<listcomp>       z7ObjectDetectionPipeline.postprocess.<locals>.<listcomp>c                    s   g | ]} |qS r    r    )rA   r4   )r=   r    r!   rC      rD   r4   )Zscorelabelboxc                    s&   g | ]}|d  krt t |qS )r   r   ziprA   vals)keysr"   r    r!   rC      rD   scoreslabelsr)   c                    s   g | ]} j jj|  qS r    )r6   r?   r@   item)rA   rE   rB   r    r!   rC      rD   c                    s   g | ]}  |qS r    )r<   )rA   rF   rB   r    r!   rC      rD   c                    s   g | ]}t t |qS r    rG   rI   )rK   r    r!   rC      s   )r0   tolistZsqueezeZsoftmaxmaxrH   r/   Zpost_process_object_detection)r   r8   r"   r+   rL   classesrM   r)   
annotationZraw_annotationsZraw_annotationr    )r-   rK   r   r"   r=   r.   r!   postprocessr   s,    
""
z#ObjectDetectionPipeline.postprocessztorch.Tensor)rF   r$   c                 C   s8   | j dkrtd|  \}}}}||||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   intrO   )r   rF   rT   rU   rV   rW   r4   r    r    r!   r<      s    

z)ObjectDetectionPipeline._get_bounding_box)r:   )__name__
__module____qualname____doc__r   r#   r   Predictionsr   
Predictionr%   r3   r9   rS   r   strrX   r<   __classcell__r    r    r   r!   r      s   	
-r   )typingr   r   r   r   utilsr   r   r	   r
   r   baser   r   Zimage_utilsr   r,   Zmodels.auto.modeling_autor   r   Z
get_loggerrY   loggerr_   r^   r]   r   r    r    r    r!   <module>   s   
