o
    0j8                     @   s   d dl mZ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 ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ej G dd deZ!edG dd deZ"dS )    )AnyDictListOptionalTupleUnionN   )logging)pipeline_requires_extra   )ImageBatchSampler)	ReadImage)	HPIConfigPaddlePredictorOption)	DetResult)	benchmark   )(AutoParallelImageSimpleInferencePipeline)BasePipeline)CropByBoxes   )SealRecognitionResultc                !       s  e Zd ZdZddddddddedee dee deeeef  d	ee d
e	dee
eeef ef  ddf fddZdedede	fddZdee	 dee	 dee	 defddZ														d%de
eee ejeej f dee	 dee	 dee	 dee
eee f  dee
eef  dee	 dee
eeeef f  dee dee dee dee d ee d!ee d"ee def d#d$Z  ZS )&_SealRecognitionPipelinezSeal Recognition PipelineNFdeviceengineengine_config	pp_optionuse_hpip
hpi_configconfigr   r   r   r   r   r   returnc             	      s\  t  jd||||||d| |dd| _| jr,|di dddi}	| |	| _|dd| _| jr|d	i d
ddi}
i }|
dd }durR||d< |
dd }dur`||d< |
dd }durn||d< |
dd }dur|||d< | j|
fi || _|di dddi}| || _	t
 | _t|ddd| _tdd| _dS )a  Initializes the seal recognition pipeline.

        Args:
            config (Dict): Configuration dictionary containing various settings.
            device (Optional[str], optional): The device to use for prediction. Defaults to `None`.
            engine (Optional[str], optional): Inference engine. Defaults to `None`.
            engine_config (Optional[Dict[str, Any]], optional): Engine-specific config. Defaults to `None`.
            pp_option (Optional[PaddlePredictorOption], optional): Paddle predictor options.
                Defaults to `None`.
            use_hpip (bool, optional): Whether to use HPIP. Defaults to `False`.
            hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
                HPIP configuration. Defaults to `None`.
        r   use_doc_preprocessorTZSubPipelinesZDocPreprocessorZpipeline_config_errorz+config error for doc_preprocessor_pipeline!use_layout_detectionZ
SubModulesZLayoutDetectionZmodel_config_errorz"config error for layout_det_model!	thresholdN
layout_nmslayout_unclip_ratiolayout_merge_bboxes_modeZSealOCRz#config error for seal_ocr_pipeline!
batch_sizer   )r(   ZBGR)format )super__init__getr"   Zcreate_pipelinedoc_preprocessor_pipeliner#   Zcreate_modellayout_det_modelseal_ocr_pipeliner   _crop_by_boxesr   batch_samplerr   
img_reader)selfr    r   r   r   r   r   r   kwargsZdoc_preprocessor_configZlayout_det_configZlayout_kwargsr$   r%   r&   r'   Zseal_ocr_config	__class__r*   v/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/pipelines/seal_recognition/pipeline.pyr,   $   sn   
z!_SealRecognitionPipeline.__init__model_settingslayout_det_resc                 C   sR   |d r| j std dS |d r'|durtd dS | js'td dS dS )	aw  
        Check if the input parameters are valid based on the initialized models.

        Args:
            model_settings (Dict): A dictionary containing input parameters.
            layout_det_res (DetResult): Layout detection result.

        Returns:
            bool: True if all required models are initialized according to input parameters, False otherwise.
        r"   zRSet use_doc_preprocessor, but the models for doc preprocessor are not initialized.Fr#   Nz^The layout detection model has already been initialized, please set use_layout_detection=FalsezRSet use_layout_detection, but the models for layout detection are not initialized.T)r"   r	   errorr#   )r4   r9   r:   r*   r*   r8   check_model_settings_validx   s"   z3_SealRecognitionPipeline.check_model_settings_validuse_doc_orientation_classifyuse_doc_unwarpingr#   c                 C   sL   |du r|du r| j }n|du s|du rd}nd}|du r | j}t||dS )a  
        Get the model settings based on the provided parameters or default values.

        Args:
            use_doc_orientation_classify (Optional[bool]): Whether to use document orientation classification.
            use_doc_unwarping (Optional[bool]): Whether to use document unwarping.
            use_layout_detection (Optional[bool]): Whether to use layout detection.

        Returns:
            dict: A dictionary containing the model settings.
        NTF)r"   r#   )r"   r#   dict)r4   r=   r>   r#   r"   r*   r*   r8   get_model_settings   s   z+_SealRecognitionPipeline.get_model_settingsinputlayout_thresholdr%   r&   r'   seal_det_limit_side_lenseal_det_limit_typeseal_det_threshseal_det_box_threshseal_det_unclip_ratioseal_rec_score_threshc           &      +   s   |  |||}| ||sddiV  |}|d ur%t|ts!|g}t|}t| |D ]\}}| |j}|d rFt| j	|||d}ndd |D }dd |D }|d s|d u rd	d |D }t| j
||
|||||d
  D ]}d|d< qsdd  D }n|d rt| j|||||	d}ng }|D ]}zt|}W n ty   tdw || qg }dg}t||D ],\}}|d D ]}|d  dv r| ||g}|d }||d  q|t| qt| j
||
|||||d
  fddt|d d |dd  D }|D ]} d}!| D ]}|!|d< |!d7 }!qqt|j|j|||D ]\}"}#}$}} |"|#|$|| |d}%t|%V  q*q,d S )Nr;   z0the input params for model settings are invalid!r"   )r=   r>   c                 S   s   g | ]}d |iqS Z
output_imgr*   ).0Zarrr*   r*   r8   
<listcomp>   s    z4_SealRecognitionPipeline.predict.<locals>.<listcomp>c                 S   s   g | ]}|d  qS rI   r*   rJ   itemr*   r*   r8   rK      s    r#   c                 S   s   g | ]}i qS r*   r*   )rJ   _r*   r*   r8   rK      s    )Ztext_det_limit_side_lenZtext_det_limit_typeZtext_det_threshZtext_det_box_threshZtext_det_unclip_ratioZtext_rec_score_threshr   seal_region_idc                 S   s   g | ]}|gqS r*   r*   rL   r*   r*   r8   rK      s    )r$   r%   r&   r'   zNo more layout det resultsr   Zboxeslabel)ZsealZimgc                    s   g | ]
\}} || qS r*   r*   )rJ   ijZflat_seal_resultsr*   r8   rK   .  s    
)
input_path
page_indexdoc_preprocessor_resr:   Zseal_res_listr9   )r@   r<   
isinstancelistiter	enumerater2   r3   Z	instancesr.   r0   r/   nextStopIteration
ValueErrorappendziplowerr1   lenZinput_pathsZpage_indexesr   )&r4   rA   r=   r>   r#   r:   rB   r%   r&   r'   rC   rD   rE   rF   rG   rH   r5   r9   Zexternal_layout_det_resultsrN   Z
batch_dataZimage_arraysZdoc_preprocessor_resultsZdoc_preprocessor_imagesZlayout_det_resultsZseal_resZseal_resultsZcropped_imgsZchunk_indicesZdoc_preprocessor_imageZbox_infoZcrop_img_infoZseal_results_for_imgrO   rU   rV   rW   Zsingle_img_resr*   rS   r8   predict   s   





	z _SealRecognitionPipeline.predict)NNNNNNNNNNNNNN)__name__
__module____qualname____doc__r   r   strr   r   boolr   r   r,   r   r<   r?   r@   r   npZndarrayfloatr   intr   rc   __classcell__r*   r*   r6   r8   r       s    	T
"
#	
r   Zocrc                   @   s&   e Zd ZdgZedd Zdd ZdS )SealRecognitionPipelineZseal_recognitionc                 C   s   t S )N)r   )r4   r*   r*   r8   _pipeline_clsU  s   z%SealRecognitionPipeline._pipeline_clsc                 C   s   | ddS )Nr(   r   )r-   )r4   r    r*   r*   r8   _get_batch_sizeY  s   z'SealRecognitionPipeline._get_batch_sizeN)rd   re   rf   entitiespropertyro   rp   r*   r*   r*   r8   rn   Q  s
    
rn   )#typingr   r   r   r   r   r   numpyrj   utilsr	   Z
utils.depsr
   Zcommon.batch_samplerr   Zcommon.readerr   modelsr   r   Zmodels.object_detection.resultr   Zutils.benchmarkr   Z	_parallelr   baser   
componentsr   resultr   Ztime_methodsr   rn   r*   r*   r*   r8   <module>   s&      2