§
    ‚Štj&  ã                   ó  — 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
j        e¦  «        Z e ed
¬¦  «        ¦  «         G d„ de¦  «        ¦   «         ZdS )é    )Ú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                 óF  •—  t          ¦   «         j        |i |¤Ž t          | d¦  «         t          j        ¦   «         }|                     t          ¦  «         |                     t          ¦  «         |                     t          ¦  «         |  	                    |¦  «         d S )NÚvision)
ÚsuperÚ__init__r   r   ÚcopyÚupdater   r   r   Úcheck_model_type)ÚselfÚargsÚkwargsÚmappingÚ	__class__s       €úg/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/transformers/pipelines/image_segmentation.pyr   z"ImageSegmentationPipeline.__init__D   s�   ø€ Ø�‰ŒÔ˜$Ð) &Ð)Ð)Ð)å˜$ Ñ)Ô)Ð)Ý<ÔAÑCÔCˆØ�ŠÕDÑEÔEÐEØ�ŠÕDÑEÔEÐEØ�ŠÕEÑFÔFÐ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Ð2Ø@FÐGdÔ@eÐÐ<Ñ=Ø˜ÐÐØ+1°)Ô+<Ð˜iÑ(à  "Ð&8Ð8Ð8r%   ÚinputszImage.Imager!   Úreturnc                 ó   — d S ©Nr,   ©r   r0   r!   s      r$   Ú__call__z"ImageSegmentationPipeline.__call___   s   € ØbeÐber%   c                 ó   — d S r3   r,   r4   s      r$   r5   z"ImageSegmentationPipeline.__call__b   s   € ØnqÐnqr%   c                 óŒ   •— d|v r|                      d¦  «        }|€t          d¦  «        ‚ t          ¦   «         j        |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.
        ÚimagesNzICannot call the image-classification pipeline without an inputs argument!)ÚpopÚ
ValueErrorr   r5   )r   r0   r!   r#   s      €r$   r5   z"ImageSegmentationPipeline.__call__e   sU   ø€ ðX �vÐÐØ—Z’Z Ñ)Ô)ˆFØˆ>ÝÐhÑiÔiÐiØ�u‰wŒwÔ Ð1Ð1¨&Ð1Ð1Ð1r%   c                 óÂ  — t          ||¬¦  «        }|j        |j        fg}| j        j        j        j        dk    rm|€i }nd|gi} | j        d
|gddœ|¤Ž}|                     | j	        ¦  «        }|  
                    |d         d| j        j        j        d¬¦  «        d         |d<   n2|                      |gd¬¦  «        }|                     | 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Ñ2Ô2ˆØœ e¤kÐ2Ð3ˆØŒ:ÔÔ&Ô/Ð3DÒDÐDØˆØ��à'¨'¨Ð3�Ø)�TÔ)ÐX°%°ÈÐXÐXÐQWÐXÐXˆFØ—Y’Y˜tœzÑ*Ô*ˆFØ$(§N¢NØ�}Ô%Ø$Øœ:Ô,Ô9Ø#ð	 %3ñ %ô %ð
 ô%ˆF�=Ñ!Ð!ð ×)Ò)°%°ÈÐ)ÑNÔNˆFØ—Y’Y˜tœzÑ*Ô*ˆFØ +ˆˆ}ÑØˆr%   c                 óT   — |                      d¦  «        } | j        di |¤Ž}||d<   |S )NrC   r,   )r9   rF   )r   Úmodel_inputsrC   Úmodel_outputss       r$   Ú_forwardz"ImageSegmentationPipeline._forward­   s<   € Ø"×&Ò& }Ñ5Ô5ˆØ"˜œ
Ð2Ð2 \Ð2Ð2ˆØ'2ˆ�mÑ$ØÐr%   çÍÌÌÌÌÌì?ç      à?c                 ó6  — d }|dv r"t          | j        d¦  «        r| j        j        }n%|dv r!t          | j        d¦  «        r| j        j        }|�Å ||||||d         ¬¦  «        d         }g }|d         }	|d	         D ]”}
|	|
d
         k    dz  }t	          j        |                     ¦   «                              t          j	        ¦  «        d¬¦  «        }| j
        j        j        |
d                  }|
d         }|                     |||dœ¦  «         Œ•�n|dv rÙt          | j        d¦  «        rÄ| j                             ||d         ¬¦  «        d         }g }|                     ¦   «         }	t          j        |	¦  «        }|D ]n}|	|k    dz  }t	          j        |                     t          j	        ¦  «        d¬¦  «        }| j
        j        j        |         }|                     d ||dœ¦  «         Œon't!          d|› dt#          | j
        ¦  «        › �¦  «        ‚|S )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)rc   ÚlabelÚmask>   NÚsemanticÚ"post_process_semantic_segmentation)r[   zSubtask z is not supported for model )ÚhasattrrI   rX   rZ   r   Ú	fromarrayÚnumpyÚastypeÚnpÚuint8rF   rG   Úid2labelÚappendrg   Úuniquer:   Útype)r   rR   r'   r(   r)   r*   ÚfnÚoutputsÚ
annotationr\   Úsegmentre   rd   rc   Úlabelss                  r$   Úpostprocessz%ImageSegmentationPipeline.postprocess³   sh  € ð ˆØÐ(Ð(Ð(­W°TÔ5IÐKoÑ-pÔ-pÐ(ØÔ%ÔHˆBˆBØÐ*Ð*Ð*­w°tÔ7KÐMqÑ/rÔ/rÐ*ØÔ%ÔHˆBàˆ>Ø�bØØ#Ø-Ø,GØ*¨=Ô9ðñ ô ð ôˆGð ˆJØ" >Ô2ˆLà" ?Ô3ð Rð R�Ø$¨°¬Ò5¸Ñ<�Ý” t§z¢z¡|¤|×':Ò':½2¼8Ñ'DÔ'DÈ3ÐOÑOÔO�Øœ
Ô)Ô2°7¸:Ô3FÔG�Ø Ô(�Ø×!Ò!¨E¸EÈ4Ð"PÐ"PÑQÔQÐQÐQñRð Ð*Ð*Ð*­w°tÔ7KÐMqÑ/rÔ/rÐ*ØÔ*×MÒMØ¨M¸-Ô,Hð Nñ ô àôˆGð ˆJØ"Ÿ=š=™?œ?ˆLÝ”Y˜|Ñ,Ô,ˆFàð Qð Q�Ø$¨Ò-°Ñ4�Ý” t§{¢{µ2´8Ñ'<Ô'<À3ÐGÑGÔG�Øœ
Ô)Ô2°5Ô9�Ø×!Ò!¨D¸5È$Ð"OÐ"OÑPÔPÐPÐPð	Qõ Ð_¨Ð_Ð_ÍTÐRVÔR\ÑM]ÔM]Ð_Ð_Ñ`Ô`Ð`ØÐr%   )NN)NrT   rU   rU   )rH   Ú
__module__Ú__qualname__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r/   r   r   Ústrr   ÚlistÚdictr5   rO   rS   rw   Ú__classcell__)r#   s   @r$   r   r      s©  ø€ € € € € ð!ð !ðF €OØ ÐØ#ÐØ€Oð'ð 'ð 'ð 'ð 'ð9ð 9ð 9ð" Øe˜u S¨-Ð%7Ô8ÐeÀCÐeÈDÐQUÐVYÐ[^ÐV^ÔQ_ÔL`ÐeÐeÐeñ „XØeàØq˜t Cœy¨4°Ô+>Ñ>ÐqÈ#ÐqÐRVÐW[Ð\`ÐadÐfiÐaiÔ\jÔWkÔRlÐqÐqÐqñ „XØqð02Ø˜C °°S´	¸4ÀÔ;NÐNÔOð02Ø[^ð02à	ˆd�3˜�8ŒnÔ	  T¨$¨s°C¨x¬.Ô%9Ô :Ñ	:ð02ð 02ð 02ð 02ð 02ð 02ðdð ð ð ð,ð ð ð knð,ð ,ð ,ð ,ð ,ð ,ð ,ð ,r%   r   )Útypingr   r   r   rj   rl   Ú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‹      so  ðØ 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à Ð Ð Ð à kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kÐ kØ 4Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4ð ÐÑÔð )ØÐÐÐÐÐà(Ð(Ð(Ð(Ð(Ð(àÐÑÔð ðð ð ð ð ð ð ð ð ð ð ð ð 
ˆÔ	˜HÑ	%Ô	%€ð ÐÐ,Ð,ÀÐFÑFÔFÑGÔGðDð Dð Dð Dð D ñ Dô Dñ HÔGðDð Dð Dr%   