§
    Þ˜ºhø&  ã                   ó  — 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         ed         f         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ef                  eeeeef                           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).
    FTNc                 óŒ  •—  t          ¦   «         j        |i |¤Ž | j        dk    rt          d| j        › d�¦  «        ‚t          | d¦  «         t          j        ¦   «         }|                     t          ¦  «         |                     t          ¦  «         |                     t          ¦  «         |                      |¦  «         d S )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       €úq/var/www/html/services/rag-service/venv/lib/python3.11/site-packages/transformers/pipelines/image_segmentation.pyr   z"ImageSegmentationPipeline.__init__D   s¹   ø€ Ø�‰ŒÔ˜$Ð) &Ð)Ð)Ð)àŒ>˜TÒ!Ð!ÝÐR D¤NÐRÐRÐRÑSÔSÐ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_parametersQ   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#   r3   r%   s      r'   Ú__call__z"ImageSegmentationPipeline.__call__b   s   € ØbeÐber(   c                 ó   — d S r6   r/   r7   s      r'   r8   z"ImageSegmentationPipeline.__call__e   s   € ØtwÐtwr(   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!)Úpopr   r   r8   )r#   r3   r%   r   s      €r'   r8   z"ImageSegmentationPipeline.__call__h   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    r}|€i }nd|gi} | j        d
|gddœ|¤Ž}| j        dk    r| 	                    | j
        ¦  «        }|                      |d         d| j        j        j        | j        ¬¦  «        d         |d<   n=|                      |gd¬¦  «        }| j        dk    r| 	                    | j
        ¦  «        }||d	<   |S )N)r.   ÚOneFormerConfigÚtask_inputsÚpt)r;   Úreturn_tensorsÚ
max_length)ÚpaddingrB   rA   Ú	input_idsÚtarget_sizer/   )r   ÚheightÚwidthÚmodelÚconfigr   Ú__name__Úimage_processorr   ÚtoÚdtypeÚ	tokenizerÚtask_seq_len)r#   Úimager*   r.   rE   r%   r3   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ØŒ~ Ò%Ð%ØŸš 4¤:Ñ.Ô.�Ø$(§N¢NØ�}Ô%Ø$Øœ:Ô,Ô9Ø#œ~ð	 %3ñ %ô %ð
 ô%ˆF�=Ñ!Ð!ð ×)Ò)°%°ÈÐ)ÑNÔNˆFØŒ~ Ò%Ð%ØŸš 4¤:Ñ.Ô.�Ø +ˆˆ}ÑØˆr(   c                 óT   — |                      d¦  «        } | j        di |¤Ž}||d<   |S )NrE   r/   )r<   rH   )r#   Úmodel_inputsrE   Ú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_segmentationrE   )r+   r,   r-   Útarget_sizesr   ÚsegmentationÚsegments_infoÚidéÿ   ÚL)ÚmodeÚlabel_idÚscore)re   ÚlabelÚmask>   NÚsemanticÚ"post_process_semantic_segmentation)r]   zSubtask z is not supported for model )ÚhasattrrK   rZ   r\   r   Ú	fromarrayÚnumpyÚastypeÚnpÚuint8rH   rI   Úid2labelÚappendri   Úuniquer   Útype)r#   rT   r*   r+   r,   r-   ÚfnÚoutputsÚ
annotationr^   Úsegmentrg   rf   re   Ú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)NrV   rW   rW   )rJ   Ú
__module__Ú__qualname__Ú__doc__Ú_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   r2   r   r   Ústrr   ÚlistÚdictr8   rQ   rU   ry   Ú__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àØw˜u T¨#¤Y°°]Ô0CÐ%CÔDÐwÐPSÐwÐX\Ð]aÐbfÐgjÐloÐgoÔbpÔ]qÔXrÐwÐwÐwñ „XØwð02Ø˜C °°S´	¸4ÀÔ;NÐNÔOð02Ø[^ð02à	ˆt�D˜˜c˜”NÔ# T¨$¨t°C¸°H¬~Ô*>Ô%?Ð?Ô	@ð02ð 02ð 02ð 02ð 02ð 02ðdð ð ð ð0ð ð ð knð,ð ,ð ,ð ,ð ,ð ,ð ,ð ,r(   r   )Útypingr   r   r   rl   rn   Úutilsr   r   r	   r
   r   Úbaser   r   ÚPILr   Úimage_utilsr   Úmodels.auto.modeling_autor   r   r   r   Ú
get_loggerrJ   Ú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ðIð Ið Ið Ið I ñ Iô Iñ HÔGðIð Ið Ir(   