Ë
    Hêñi&  ã                   óö   — d dl 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
j0                  e«      Z e ed
¬«      «       G d„ de«      «       Zy)é    )ÚAnyÚUnionÚoverloadNé   )Ú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                   ó,  ‡ — 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eeef      fd„«       Ze
dee   ed   z  d	ed
eeeeef         fd„«       Zdeedee   ed   f   d	ed
eeeef      eeeeef         z  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).
    FTNc                 ó  •— t        ‰| �  |i |¤Ž t        | d«       t        j                  «       }|j                  t        «       |j                  t        «       |j                  t        «       | j                  |«       y )NÚvision)
ÚsuperÚ__init__r   r   ÚcopyÚupdater   r   r   Úcheck_model_type)ÚselfÚargsÚkwargsÚmappingÚ	__class__s       €úk/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/transformers/pipelines/image_segmentation.pyr   z"ImageSegmentationPipeline.__init__D   sb   ø€ Ü‰Ñ˜$Ð) &Ò)ä˜$ Ô)Ü<×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_parametersN   s¨   € ØÐØÐØ˜ÑØ,2°9Ñ,=Ð˜yÑ)Ø+1°)Ñ+<Ð˜iÑ(Ø˜&Ñ Ø.4°[Ñ.AÐ˜{Ñ+Ø˜vÑ%Ø39Ð:JÑ3KÐÐ/Ñ0Ø(¨FÑ2Ø@FÐGdÑ@eÐÐ<Ñ=Ø˜ÑØ+1°)Ñ+<Ð˜iÑ(à  "Ð&8Ð8Ð8r%   ÚinputszImage.Imager!   Úreturnc                  ó   — y ©Nr,   ©r   r0   r!   s      r$   Ú__call__z"ImageSegmentationPipeline.__call___   s   € Øber%   c                  ó   — y r3   r,   r4   s      r$   r5   z"ImageSegmentationPipeline.__call__b   s   € Ønqr%   c                 ó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:
            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!)ÚpopÚ
ValueErrorr   r5   )r   r0   r!   r#   s      €r$   r5   z"ImageSegmentationPipeline.__call__e   sB   ø€ ðX �vÑØ—Z‘Z Ó)ˆFØˆ>ÜÐhÓiÐiÜ‰wÑ Ñ1¨&Ñ1Ð1r%   c                 ó  — t        ||¬«      }|j                  |j                  fg}| j                  j                  j
                  j                  dk(  rx|€i }nd|gi} | j                  d
|gddœ|¤Ž}|j                  | j                  «      }| j                  |d   d| j                  j                  j                  d¬«      d   |d<   n/| j                  |gd¬«      }|j                  | j                  «      }||d	<   |S )N)r+   ÚOneFormerConfigÚtask_inputsÚpt)r8   Úreturn_tensorsÚ
max_length)Úpaddingr@   r?   Ú	input_idsÚtarget_sizer,   )r   ÚheightÚwidthÚmodelÚconfigr#   Ú__name__Úimage_processorÚtoÚdtypeÚ	tokenizerÚtask_seq_len)r   Úimager'   r+   rC   r!   r0   s          r$   Ú
preprocessz$ImageSegmentationPipeline.preprocess—   s  € Ü˜5¨'Ô2ˆØŸ™ e§k¡kÐ2Ð3ˆØ�:‰:×Ñ×&Ñ&×/Ñ/Ð3DÒDØˆØ‘à'¨'¨Ð3�Ø)�T×)Ñ)ÐX°%°ÈÑXÐQWÑXˆFØ—Y‘Y˜tŸz™zÓ*ˆFØ$(§N¡NØ�}Ñ%Ø$ØŸ:™:×,Ñ,×9Ñ9Ø#ð	 %3ó %ð
 ñ%ˆF�=Ò!ð ×)Ñ)°%°ÈÐ)ÓNˆFØ—Y‘Y˜tŸz™zÓ*ˆFØ +ˆˆ}ÑØˆr%   c                 óV   — |j                  d«      } | j                  di |¤Ž}||d<   |S )NrC   r,   )r9   rF   )r   Úmodel_inputsrC   Ú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_segmentationrC   )r(   r)   r*   Útarget_sizesr   ÚsegmentationÚsegments_infoÚidéÿ   ÚL)ÚmodeÚlabel_idÚscore)ra   ÚlabelÚmask>   NÚsemanticÚ"post_process_semantic_segmentation)rY   zSubtask z is not supported for model )ÚhasattrrI   rV   rX   r   Ú	fromarrayÚnumpyÚastypeÚnpÚuint8rF   rG   Úid2labelÚappendre   Úuniquer:   Útype)r   rR   r'   r(   r)   r*   ÚfnÚoutputsÚ
annotationrZ   Úsegmentrc   rb   ra   Ú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%   )NN)NgÍÌÌÌÌÌì?ç      à?rv   )rH   Ú
__module__Ú__qualname__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r/   r   r   Ústrr   ÚlistÚdictr5   rO   rS   ru   Ú__classcell__)r#   s   @r$   r   r      s  ø„ ñ!ðF €OØ ÐØ#ÐØ€Oô'ò9ð" Øe˜u S¨-Ð%7Ñ8ÐeÀCÐeÈDÐQUÐVYÐ[^ÐV^ÑQ_ÑL`Òeó ØeàØq˜t C™y¨4°Ñ+>Ñ>ÐqÈ#ÐqÐRVÐW[Ð\`ÐadÐfiÐaiÑ\jÑWkÑRlÒqó Øqð02Ø˜C °°S±	¸4ÀÑ;NÐNÑOð02Ø[^ð02à	ˆd�3˜�8‰nÑ	  T¨$¨s°C¨x©.Ñ%9Ñ :Ñ	:õ02ódò,ð kn÷,r%   r   )Útypingr   r   r   rh   rj   Úutilsr   r   r	   r
   r   Úbaser   r   ÚPILr   Úimage_utilsr   Úmodels.auto.modeling_autor   r   r   r   Ú
get_loggerrH   Úloggerr   r,   r%   r$   ú<module>rŠ      ss   ðß 'Ñ 'ã ç kÕ kß 4ñ ÔÝå(áÔ÷ó ð 
ˆ×	Ñ	˜HÓ	%€ñ Ñ,ÀÔFÓGôD ó Dó HñDr%   