Ë
    T^(hŽ%  ã                   ó  — d dl mZmZmZmZ d dl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  e	«       rdd	lmZmZmZmZ  ej2                  e«      Zeeef   Zee   Z e ed
¬«      «       G d„ de«      «       Zy)é    )ÚAnyÚDictÚListÚUnionNé   )Úadd_end_docstringsÚis_torch_availableÚis_vision_availableÚloggingÚrequires_backendsé   )ÚPipelineÚbuild_pipeline_init_args)ÚImage)Ú
load_image)Ú*MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMESÚ-MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMESÚ-MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMESÚ.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMEST)Úhas_image_processorc                   ób   ‡ — e Zd ZdZˆ fd„Zd„ Zd	deeee	   f   fˆ fd„Z
d
d„Zd„ Z	 dd„Zˆ xZS )ÚImageSegmentationPipelineaÐ  
    Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and
    their classes.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
    >>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
    >>> len(segments)
    2

    >>> segments[0]["label"]
    'bird'

    >>> segments[1]["label"]
    'bird'

    >>> type(segments[0]["mask"])  # This is a black and white mask showing where is the bird on the original image.
    <class 'PIL.Image.Image'>

    >>> segments[0]["mask"].size
    (768, 512)
    ```


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

    See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).
    c                 óT  •— t        ‰| �  |i |¤Ž | j                  dk(  rt        d| j                  › d�«      ‚t        | d«       t        j                  «       }|j                  t        «       |j                  t        «       |j                  t        «       | j                  |«       y )NÚtfzThe z is only available in PyTorch.Úvision)ÚsuperÚ__init__Ú	frameworkÚ
ValueErrorÚ	__class__r   r   ÚcopyÚupdater   r   r   Úcheck_model_type)ÚselfÚargsÚkwargsÚmappingr    s       €úg/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/pipelines/image_segmentation.pyr   z"ImageSegmentationPipeline.__init__C   sˆ   ø€ Ü‰Ñ˜$Ð) &Ò)à�>‰>˜TÒ!Ü˜t D§N¡NÐ#3Ð3QÐRÓSÐSä˜$ Ô)Ü<×AÑAÓCˆØ�‰ÔDÔEØ�‰ÔDÔEØ�‰ÔEÔFØ×Ñ˜gÕ&ó    c                 óœ   — i }i }d|v r|d   |d<   |d   |d<   d|v r|d   |d<   d|v r|d   |d<   d|v r|d   |d<   d|v r|d   |d<   |i |fS )NÚsubtaskÚ	thresholdÚmask_thresholdÚoverlap_mask_area_thresholdÚtimeout© )r$   r&   Úpreprocess_kwargsÚpostprocess_kwargss       r(   Ú_sanitize_parametersz.ImageSegmentationPipeline._sanitize_parametersP   s¨   € ØÐØÐØ˜ÑØ,2°9Ñ,=Ð˜yÑ)Ø+1°)Ñ+<Ð˜iÑ(Ø˜&Ñ Ø.4°[Ñ.AÐ˜{Ñ+Ø˜vÑ%Ø39Ð:JÑ3KÐÐ/Ñ0Ø(¨FÑ2Ø@FÐGdÑ@eÐÐ<Ñ=Ø˜ÑØ+1°)Ñ+<Ð˜iÑ(à  "Ð&8Ð8Ð8r)   Úreturnc                 óh   •— d|v r|j                  d«      }|€t        d«      ‚t        ‰| �  |fi |¤ŽS )aó	  
        Perform segmentation (detect masks & 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.
            subtask (`str`, *optional*):
                Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model
                capabilities. If not set, the pipeline will attempt tp resolve in the following order:
                  `panoptic`, `instance`, `semantic`.
            threshold (`float`, *optional*, defaults to 0.9):
                Probability threshold to filter out predicted masks.
            mask_threshold (`float`, *optional*, defaults to 0.5):
                Threshold to use when turning the predicted masks into binary values.
            overlap_mask_area_threshold (`float`, *optional*, defaults to 0.5):
                Mask overlap threshold to eliminate small, disconnected segments.
            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 dictionary or a 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 mask, label and score (where applicable) of each detected object and contains
            the following keys:

            - **label** (`str`) -- The class label identified by the model.
            - **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of
              the original image. Returns a mask filled with zeros if no object is found.
            - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the
              "object" described by the label and the mask.
        ÚimageszICannot call the image-classification pipeline without an inputs argument!)Úpopr   r   Ú__call__)r$   Úinputsr&   r    s      €r(   r8   z"ImageSegmentationPipeline.__call__a   sB   ø€ ðV �vÑØ—Z‘Z Ó)ˆFØˆ>ÜÐhÓiÐiÜ‰wÑ Ñ1¨&Ñ1Ð1r)   c                 óT  — t        ||¬«      }|j                  |j                  fg}| j                  j                  j
                  j                  dk(  r‘|€i }nd|gi} | j                  d
|gddœ|¤Ž}| j                  dk(  r|j                  | j                  «      }| j                  |d   d| j                  j                  j                  | j                  ¬«      d   |d<   n>| j                  |gd¬«      }| j                  dk(  r|j                  | j                  «      }||d	<   |S )N)r/   ÚOneFormerConfigÚtask_inputsÚpt)r6   Úreturn_tensorsÚ
max_length)Úpaddingr?   r>   Ú	input_idsÚtarget_sizer0   )r   ÚheightÚwidthÚmodelÚconfigr    Ú__name__Úimage_processorr   ÚtoÚtorch_dtypeÚ	tokenizerÚtask_seq_len)r$   Úimager+   r/   rB   r&   r9   s          r(   Ú
preprocessz$ImageSegmentationPipeline.preprocess’   s&  € Ü˜5¨'Ô2ˆØŸ™ e§k¡kÐ2Ð3ˆØ�:‰:×Ñ×&Ñ&×/Ñ/Ð3DÒDØˆØ‘à'¨'¨Ð3�Ø)�T×)Ñ)ÐX°%°ÈÑXÐQWÑXˆFØ�~‰~ Ò%ØŸ™ 4×#3Ñ#3Ó4�Ø$(§N¡NØ�}Ñ%Ø$ØŸ:™:×,Ñ,×9Ñ9Ø#Ÿ~™~ð	 %3ó %ð
 ñ%ˆF�=Ò!ð ×)Ñ)°%°ÈÐ)ÓNˆFØ�~‰~ Ò%ØŸ™ 4×#3Ñ#3Ó4�Ø +ˆˆ}ÑØˆr)   c                 óV   — |j                  d«      } | j                  di |¤Ž}||d<   |S )NrB   r0   )r7   rE   )r$   Úmodel_inputsrB   Úmodel_outputss       r(   Ú_forwardz"ImageSegmentationPipeline._forwardª   s5   € Ø"×&Ñ& }Ó5ˆØ"˜Ÿ
™
Ñ2 \Ñ2ˆØ'2ˆ�mÑ$ØÐr)   c                 ó<  — d }|dv r-t        | j                  d«      r| j                  j                  }n0|dv r,t        | j                  d«      r| j                  j                  }|�³ ||||||d   ¬«      d   }g }|d   }	|d	   D ]�  }
|	|
d
   k(  dz  }t	        j
                  |j                  «       j                  t        j                  «      d¬«      }| j                  j                  j                  |
d      }|
d   }|j                  |||dœ«       Œ‘ |S |dv rÝt        | j                  d«      rÇ| j                  j                  ||d   ¬«      d   }g }|j                  «       }	t        j                  |	«      }|D ]v  }|	|k(  dz  }t	        j
                  |j                  t        j                  «      d¬«      }| j                  j                  j                  |   }|j                  d ||dœ«       Œx |S t!        d|› dt#        | j                  «      › �«      ‚)N>   NÚpanopticÚ"post_process_panoptic_segmentation>   NÚinstanceÚ"post_process_instance_segmentationrB   )r,   r-   r.   Útarget_sizesr   ÚsegmentationÚsegments_infoÚidéÿ   ÚL)ÚmodeÚlabel_idÚscore)r`   ÚlabelÚmask>   NÚsemanticÚ"post_process_semantic_segmentation)rX   zSubtask z is not supported for model )ÚhasattrrH   rU   rW   r   Ú	fromarrayÚnumpyÚastypeÚnpÚuint8rE   rF   Úid2labelÚappendrd   Úuniquer   Útype)r$   rQ   r+   r,   r-   r.   ÚfnÚoutputsÚ
annotationrY   Úsegmentrb   ra   r`   Úlabelss                  r(   Úpostprocessz%ImageSegmentationPipeline.postprocess°   s4  € ð ˆØÐ(Ñ(¬W°T×5IÑ5IÐKoÔ-pØ×%Ñ%×HÑH‰BØÐ*Ñ*¬w°t×7KÑ7KÐMqÔ/rØ×%Ñ%×HÑHˆBàˆ>ÙØØ#Ø-Ø,GØ*¨=Ñ9ôð ñˆGð ˆJØ" >Ñ2ˆLà" ?Ñ3ò R�Ø$¨°©Ñ5¸Ñ<�Ü—‘ t§z¡z£|×':Ñ':¼2¿8¹8Ó'DÈ3ÔO�ØŸ
™
×)Ñ)×2Ñ2°7¸:Ñ3FÑG�Ø Ñ(�Ø×!Ñ!¨E¸EÈ4Ñ"PÕQðRð. Ðð! Ð*Ñ*¬w°t×7KÑ7KÐMqÔ/rØ×*Ñ*×MÑMØ¨M¸-Ñ,Hð Nó àñˆGð ˆJØ"Ÿ=™=›?ˆLÜ—Y‘Y˜|Ó,ˆFàò Q�Ø$¨Ñ-°Ñ4�Ü—‘ t§{¡{´2·8±8Ó'<À3ÔG�ØŸ
™
×)Ñ)×2Ñ2°5Ñ9�Ø×!Ñ!¨D¸5È$Ñ"OÕPð	Qð Ðô ˜x¨ yÐ0LÌTÐRV×R\ÑR\ÓM]ÐL^Ð_Ó`Ð`r)   )N)NN)NgÍÌÌÌÌÌì?ç      à?ru   )rG   Ú
__module__Ú__qualname__Ú__doc__r   r3   r   ÚPredictionsr   Ú
Predictionr8   rN   rR   rt   Ú__classcell__)r    s   @r(   r   r      sE   ø„ ñ!ôF'ò9ñ"/2°°{ÀDÈÑDTÐ7TÑ1Uõ /2óbò0ð kn÷,r)   r   ) Útypingr   r   r   r   rg   ri   Úutilsr   r	   r
   r   r   Úbaser   r   ÚPILr   Úimage_utilsr   Úmodels.auto.modeling_autor   r   r   r   Ú
get_loggerrG   ÚloggerÚstrrz   ry   r   r0   r)   r(   ú<module>r…      sŒ   ðß )Ó )ã ç kÕ kß 4ñ ÔÝå(áÔ÷ó ð 
ˆ×	Ñ	˜HÓ	%€ð �#�s�(‰^€
Ø�:Ñ€ñ Ñ,ÀÔFÓGô} ó }ó Hñ}r)   