o
    h3                     @   s   d dl mZ d dlmZ ddlmZ ddlmZmZm	Z	m
Z
 ddlmZmZ e r3d dlZdd	lmZ e	eZeed
ddG dd deZdS )    )defaultdict)Optional   )
load_image)add_end_docstringsis_torch_availableloggingrequires_backends   )ChunkPipelinebuild_pipeline_init_argsN)'MODEL_FOR_MASK_GENERATION_MAPPING_NAMEST)has_image_processora  
        points_per_batch (*optional*, int, default to 64):
            Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU
            memory.
        output_bboxes_mask (`bool`, *optional*, default to `False`):
            Whether or not to output the bounding box predictions.
        output_rle_masks (`bool`, *optional*, default to `False`):
            Whether or not to output the masks in `RLE` formatc                       s   e Zd ZdZ fddZdd Zddd fdd	
Z	
					ddedede	e de	e de	e f
ddZ
				dddZ			d ddZ  ZS )!MaskGenerationPipelinea0
  
    Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an
    image, given an image. It is a `ChunkPipeline` because you can seperate the points in a mini-batch in order to
    avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the
    same time. Default is `64`.

    The pipeline works in 3 steps:
        1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point
           labels.
            For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes`
            function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of
            `points_per_batch`.

        2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once.
            Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the
            tensors and models are on the same device.

        3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps
            are induced:
                - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks,
                  resizes them according
                to the image size, and transforms there to binary masks.
                - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and
                  `stability_scores`. Also
                applies a variety of filters based on non maximum suppression to remove bad masks.
                - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
    >>> outputs = generator(
    ...     "http://images.cocodataset.org/val2017/000000039769.jpg",
    ... )

    >>> outputs = generator(
    ...     "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
    ... )
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)

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

    See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation).
    c                    sP   t  jdi | t| d t| d | jdkr!td| j d| t d S )NvisiontorchptzThe z is only available in PyTorch. )super__init__r	   	framework
ValueError	__class__check_model_typer   )selfkwargsr   r   z/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/pipelines/mask_generation.pyr   T   s   


zMaskGenerationPipeline.__init__c                 K   s  i }i }i }d|v r|d |d< d|v r|d |d< d|v r$|d |d< d|v r.|d |d< d|v r8|d |d< d|v rB|d |d< d|v rL|d |d< d|v rV|d |d< d	|v r`|d	 |d	< d
|v rj|d
 |d
< d|v rt|d |d< d|v r~|d |d< d|v r|d |d< |||fS )Npoints_per_batchpoints_per_cropcrops_n_layerscrop_overlap_ratiocrop_n_points_downscale_factortimeoutpred_iou_threshstability_score_offsetmask_thresholdstability_score_threshcrops_nms_threshoutput_rle_maskoutput_bboxes_maskr   )r   r   preprocess_kwargspostprocess_kwargsforward_paramsr   r   r   _sanitize_parameters^   s<   
z+MaskGenerationPipeline._sanitize_parametersNnum_workers
batch_sizec                   s    t  j|g|R ||d|S )a	  
        Generates binary segmentation masks

        Args:
            inputs (`np.ndarray` or `bytes` or `str` or `dict`):
                Image or list of images.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                Threshold to use when turning the predicted masks into binary values.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                A filtering threshold in `[0,1]` applied on the model's predicted mask quality.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to
                binarize the model's mask predictions.
            stability_score_offset (`int`, *optional*, defaults to 1):
                The amount to shift the cutoff when calculated the stability score.
            crops_nms_thresh (`float`, *optional*, defaults to 0.7):
                The box IoU cutoff used by non-maximal suppression to filter duplicate masks.
            crops_n_layers (`int`, *optional*, defaults to 0):
                If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of
                layers to run, where each layer has 2**i_layer number of image crops.
            crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`):
                Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
                the image length. Later layers with more crops scale down this overlap.
            crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`):
                The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
            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:
            `Dict`: A dictionary with the following keys:
                - **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.

        r/   )r   __call__)r   imager0   r1   argsr   r   r   r   r2      s    &zMaskGenerationPipeline.__call__@   r   g?    r
   r    r!   r   r"   r#   c              	   c   s   t ||d}| jjd }| j||||||\}	}
}}| j|dd}| jdkr.|| j}|  9 | jdkrd|  }|  | j	|| j
d}| j|d}||d< W d    n1 s_w   Y  W d    n1 snw   Y  |
jd }|d ur~|n|}|d	krtd
td	||D ]0}|
d d ||| d d d d f }|d d ||| f }||| k}|||	|d|V  qd S )N)r#   longest_edger   )imagesreturn_tensors)devicepixel_valuesimage_embeddingsr
   r   zCannot have points_per_batch<=0. Must be >=1 to returned batched outputs. To return all points at once, set points_per_batch to None)input_pointsinput_labelsinput_boxesis_last)r   image_processorsizegenerate_crop_boxesr   totorch_dtypedevice_placementget_inference_context_ensure_tensor_on_devicer;   modelget_image_embeddingspopshaper   range)r   r3   r   r    r!   r   r"   r#   target_size
crop_boxesgrid_pointscropped_imagesr?   model_inputsinference_contextr=   n_pointsibatched_pointslabelsrA   r   r   r   
preprocess   sJ   





$z!MaskGenerationPipeline.preprocess)\(?ffffff?c              
   C   s   | d}| d}| d }| d }	| jdi |}
|
d }| jj|||	|dd}|
d }| j|d	 |d	 |d	 |d	 ||||\}}}||||d
S )Nr@   rA   original_sizesreshaped_input_sizes
pred_masksF)binarize
iou_scoresr   )masksrA   boxesr`   r   )rL   tolistrJ   rB   post_process_masksfilter_masks)r   rS   r$   r'   r&   r%   r@   rA   r\   r]   model_outputslow_resolution_masksra   r`   rb   r   r   r   _forward   s2   



zMaskGenerationPipeline._forwardFffffff?c                 C   s   g }g }g }|D ]}| |d ||d | |d qt|}t|}| j||||\}	}
}}tt}|D ]}|	 D ]\}}||  | qFq@i }|r[||d< |ra||d< |	|
d||S )Nr`   ra   rb   rle_maskbounding_boxes)ra   scores)
appendrL   extendr   catrB    post_process_for_mask_generationr   listitems)r   rf   r)   r*   r(   
all_scores	all_masks	all_boxesmodel_outputoutput_masksr`   rj   rk   extraoutputkvoptionalr   r   r   postprocess   s.   

z"MaskGenerationPipeline.postprocess)r5   r   r6   r7   r
   N)rZ   r[   r   r
   )FFri   )__name__
__module____qualname____doc__r   r.   r2   intfloatr   rY   rh   r}   __classcell__r   r   r   r   r      s>    2
"+
3
)r   )collectionsr   typingr   image_utilsr   utilsr   r   r   r	   baser   r   r   models.auto.modeling_autor   
get_loggerr~   loggerr   r   r   r   r   <module>   s    
