o
    0j                     @   sx   d dl mZmZmZmZmZ d dlZddlm	Z	 ddl
mZ ddlmZmZ dd	lmZ dd
lmZ G dd deZdS )    )AnyListOptionalSequenceTupleN   )logging   )DetRunnerPredictor)	ReadImageToBatch   )InstanceSegPostProcessInstanceSegResultc                       s   e Zd ZdZdddee f fddZdefdd	Zde	fd
dZ
dd Zddee dee fddZdee dee fddZdd Z  ZS )InstanceSegRunnerPredictorzAInstanceSegRunnerPredictor that inherits from DetRunnerPredictor.N)	thresholdr   c                   s`   t  j|i | h d| _| j| jv r+tddt| j d| jd d  d || _	dS )	a  Initializes InstanceSegPredictor.
        Args:
            *args: Arbitrary positional arguments passed to the superclass.
            threshold (Optional[float], optional): The threshold for filtering out low-confidence predictions.
                Defaults to None, in which case will use default from the config file.
            **kwargs: Arbitrary keyword arguments passed to the superclass.
        >   zPP-YOLOE_seg-Sz'Cascade-MaskRCNN-ResNet50-vd-SSLDv2-FPNZSOLOv2zCascade-MaskRCNN-ResNet50-FPNzInstance Segmentation Models: "z, a  " only supports prediction with a batch_size of one, if you set the predictor with a batch_size larger than one, no error will occur, however, it will actually inference with a batch_size of one, which will lead to a slower inference speed. You are now using Global
model_name.N)
super__init__*model_names_only_supports_batchsize_of_oner   r   warningjoinlistconfigr   )selfr   argskwargs	__class__ y/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/models/instance_segmentation/predictor.pyr      s   

z#InstanceSegRunnerPredictor.__init__returnc                 C   s   t S )zvReturns the result class, InstanceSegResult.

        Returns:
            type: The InstanceSegResult class.
        r   r   r"   r"   r#   _get_result_class6   s   z,InstanceSegRunnerPredictor._get_result_classc                 C   s   t ddg}| jd D ]'}|d }| j| }|d |}|r'|| fi |n|| }|r2|| q||   |  }||fS )zBuild the preprocessors and postprocessors based on the configuration.

        Returns:
            tuple: A tuple containing the preprocessors and postprocessors.
        RGB)formatZ
Preprocesstype)r   r   Z	_FUNC_MAPpopappendbuild_to_batchbuild_postprocess)r   pre_opscfgZtf_keyfuncr   oppost_opr"   r"   r#   _build>   s   


z!InstanceSegRunnerPredictor._buildc                 C   s   d}t |dS )N)Zimg_sizeZimgZscale_factors)ordered_required_keys)r   )r   r4   r"   r"   r#   r,   U   s   
z)InstanceSegRunnerPredictor.build_to_batch
batch_datac                    s   |j }| jdd D ]}||}q
| jd |}| j| jv r@g }t|d jd D ]  fdd|D }| |}|| q)n| |}| |}	| 	|	||durT|n| j
}
|j|jdd |D dd |
D dd |
D d	S )
a  
        Process a batch of data through the preprocessing, inference, and postprocessing.

        Args:
            batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).

        Returns:
            dict: A dictionary containing the input path, raw image, box and mask
                for every instance of the batch. Keys include 'input_path', 'input_img', 'boxes' and 'masks'.
        Nr   c                    s   g | ]}|  d  qS ))N.r"   ).0Zbatch_input_ir"   r#   
<listcomp>v   s    z6InstanceSegRunnerPredictor.process.<locals>.<listcomp>c                 S      g | ]}|d  qS )Zori_imgr"   )r7   datar"   r"   r#   r:          c                 S   r;   )boxesr"   r7   resultr"   r"   r#   r:      r=   c                 S   r;   )masksr"   r?   r"   r"   r#   r:      r=   )Z
input_pathZ
page_indexZ	input_imgr>   rA   )Z	instancesr.   r   r   rangeshaperunnerr+   _format_outputr2   r   Zinput_pathsZpage_indexes)r   r5   r   ZdatasZpre_opZbatch_inputsZbatch_predsZbatch_inputs_Zbatch_pred_Z
preds_listZboxes_masksr"   r8   r#   process_   s0   




z"InstanceSegRunnerPredictor.processpredc                    s  d}g t  d tr/t d dkr/dd  D dd  D fddttD S t  d trKt d dkrK fddtt D S g tt d	 D ](} d	 | }|| } d || }|  d
 || }| |}qUfddttD S )a  
        Transform batch outputs into a list of single image output.

        Args:
            pred (Sequence[Any]): The input predictions, which can be either a list of 3 or 4 elements.
                - When len(pred) == 4, it is expected to be in the format [boxes, class_ids, scores, masks],
                  compatible with SOLOv2 output.
                - When len(pred) == 3, it is expected to be in the format [boxes, box_nums, masks],
                  compatible with Instance Segmentation output.

        Returns:
            List[dict]: A list of dictionaries, each containing either 'class_id' and 'masks' (for SOLOv2),
                or 'boxes' and 'masks' (for Instance Segmentation), or just 'boxes' if no masks are provided.
        r   r   c                 S   s   g | ]
}|d  |d gqS )r   r	   r"   r7   Zpred_r"   r"   r#   r:      s    z=InstanceSegRunnerPredictor._format_output.<locals>.<listcomp>c                 S   r;   )   r"   rH   r"   r"   r#   r:      r=   c                    *   g | ]}t  | t | d qS ))Zclass_idrA   nparrayr7   r9   )pred_class_id	pred_maskr"   r#   r:      s    rI   c                    s2   g | ]}t  | d  t  | d dqS )r   r	   r>   rA   rK   rN   )rG   r"   r#   r:      s    $r   r	   c                    rJ   )rQ   rK   rN   )pred_boxrP   r"   r#   r:      s    )
isinstancer   lenrB   r+   )r   rG   Zbox_idx_startidxZnp_boxes_numZbox_idx_endZnp_boxesZnp_masksr"   )rG   rR   rO   rP   r#   rE      s0   





z)InstanceSegRunnerPredictor._format_outputc                 C   s   t | jd | jd dS )NZdraw_thresholdZ
label_list)r   labels)r   r   r%   r"   r"   r#   r-      s   z,InstanceSegRunnerPredictor.build_postprocess)N)__name__
__module____qualname____doc__r   floatr   r)   r&   r   r3   r,   r   r   rF   r   dictrE   r-   __classcell__r"   r"   r    r#   r      s    
/3r   )typingr   r   r   r   r   numpyrL   utilsr   Zobject_detectionr
   Zobject_detection.processorsr   r   Z
processorsr   r@   r   r   r"   r"   r"   r#   <module>   s   