
    Ng'                     *   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	Z	d dl
mZ d dlZd dlZddlmZmZmZ ddlmZ d	d
lmZmZmZ d	dlmZ  e            rd dlZdgZdej        deeef         deej        ej        f         fdZ  G d de          Z!dS )    )ListUnionDictAnyTupleN)reduce)Image   )PathManagerLABEL_MAP_CATALOGMODEL_CATALOG   )BaseLayoutModel   )	Rectangle	TextBlockLayout)is_paddle_availablePaddleDetectionLayoutModelimagetarget_sizereturnc                    | j         dd         }|\  }}|t          |d                   z  }|t          |d                   z  }t          j        | dd||d          } t	          j        ||g                              d          }| |fS )z
    Args:
        image (np.ndarray): image (np.ndarray)
    Returns:
        image (np.ndarray): processed image (np.ndarray)
    Nr   r   r
   )fxfyinterpolationfloat32)shapefloatcv2resizenparrayastype)r   r   origin_shaperesize_hresize_w
im_scale_y
im_scale_xscale_factors           k/var/www/html/ai-engine/env/lib/python3.11/site-packages/layoutparser/models/paddledetection/layoutmodel.py_resize_imager,   &   s     ;rr?L$HhE,q/222JE,q/222J JudDZJVWXXXE8Z455<<YGGL,    c                   l    e Zd ZdZdgZdZeZ	 	 	 	 	 	 ddZ	 	 	 ddZd	 Z	d
 Z
d Zded         fdZdS )r   a  Create a PaddleDetection-based Layout Detection Model

    Args:
        config_path (:obj:`str`):
            The path to the configuration file.
        model_path (:obj:`str`, None):
            The path to the saved weights of the model.
            If set, overwrite the weights in the configuration file.
            Defaults to `None`.
        label_map (:obj:`dict`, optional):
            The map from the model prediction (ids) to real
            word labels (strings). If the config is from one of the supported
            datasets, Layout Parser will automatically initialize the label_map.
            Defaults to `None`.
        device(:obj:`str`, optional):
            Whether to use cuda or cpu devices. If not set, LayoutParser will
            automatically determine the device to initialize the models on.
        extra_config (:obj:`dict`, optional):
            Extra configuration passed to the PaddleDetection model configuration.
            Defaults to `{}`.
            Including arguments:
            enable_mkldnn (:obj:`bool`, optional):
                Whether use mkldnn to accelerate the computation.
                Defaults to False.
            thread_num (:obj:`int`, optional):
                The number of threads.
                Defaults to 10.
            threshold (:obj:`float`, optional):
                Threshold to reserve the result for output.
                Defaults to 0.5.
            target_size (:obj:`list`, optional):
                The image shape after resize.
                Defaults to [640,640].

    Examples::
        >>> import layoutparser as lp
        >>> model = lp.models.PaddleDetectionLayoutModel('
                                    lp://PubLayNet/ppyolov2_r50vd_dcn_365e/config')
        >>> model.detect(image)

    paddlepaddledetectionNc           	         |t          j        dt                     |i }|                     ||          \  }}t	          j        |          }|S|                    d          r<|                    d                              d          d         }	t          |	         }ni }|| _
        |                     |||                    dd          |                    dd          	          | _        |                    d
d          | _        |                    dddg          | _        |                    dt!          j        g dgg                    | _        |                    dt!          j        g dgg                    | _        d S )Nz?Setting enforce_cpu is deprecated. Please set `device` instead.zlp:///r
   enable_mkldnnF
thread_num
   )devicer3   r4   	thresholdg      ?r   i  
pixel_mean)g
ףp=
?gv/?gCl?	pixel_std)gZd;O?gy&1?g?)warningswarnDeprecationWarningconfig_parserr   get_local_path
startswithlstripsplitr   	label_mapload_predictorget	predictorr7   r   r"   r#   r8   r9   )
selfconfig_path
model_pathrB   r6   enforce_cpuextra_config_	model_dirdataset_names
             r+   __init__z#PaddleDetectionLayoutModel.__init__m   s    "MQ"  
 L**;
CC:.z::	$$W-- )0099??DDQG-l;			" ,,&**?EBB#''b99	 - 
 
 &))+s;;'++MC:FF&**"(%:%:%:$;#<==
 
 &))$9$9$9#:";<<
 
r-   Fr5   c                    t           j                            t          j                            |d          t          j                            |d                    }|dk    r,|                    dd           |                    d           n|                                 |	                    |           |re|
                                 	 |                    d           |
                                 n&# t          $ r}t          d           Y d	}~nd	}~ww xY w|                                 |                                 |                    d
           t           j                            |          }|S )aQ  set AnalysisConfig, generate AnalysisPredictor
        Args:
            model_dir (str): root path of __model__ and __params__
            device (str): cuda or cpu
        Returns:
            predictor (PaddlePredictor): AnalysisPredictor
        Raises:
            ValueError: predict by TensorRT need enforce_cpu == False.
        zinference.pdmodelzinference.pdiparamscudai  r   Tr5   zEThe current environment does not support `mkldnn`, so disable mkldnn.NF)r/   	inferenceConfigospathjoinenable_use_gpuswitch_ir_optimdisable_gpu set_cpu_math_library_num_threadsr3   set_mkldnn_cache_capacity	Exceptionprintdisable_glog_infoenable_memory_optimswitch_use_feed_fetch_opscreate_predictor)rF   rL   r6   r3   r4   configerE   s           r+   rC   z)PaddleDetectionLayoutModel.load_predictor   s   " !((GLL.  GLL$9::	
 
 V !!$***""4((((   33J??? 	$$&&&44R888((****    _        	  """""$$$((///$55f==	s   )C9 9
DDDc                    t          || j                  \  }}t          j        |j        dd                                       d          }|dz  | j        z
  | j        z  }|                    d          	                                }i }t          j        |          t          j
        ddf                             d          |d<   t          j        |          t          j
        ddf                             d          |d<   t          j        |          t          j
        ddf                             d          |d<   |S )	zpreprocess image

        Args:
            image (np.ndarray): image (np.ndarray)
        Returns:
            inputs (dict): input of model
        Nr   r   g     o@)r   r   r
   r   im_shaper*   )r,   r   r"   r#   r   r$   r8   r9   	transposecopynewaxis)rF   r   r*   input_shapeinputss        r+   
preprocessz%PaddleDetectionLayoutModel.preprocess   s    ,E43CDD|hu{2A2//66yAA0DNB	**//11(5//"*aaa-8??	JJwXk222:qqq=AHHSSz!#,!7!7
AAA!F!M!Mi!X!X~r-   c           	      .   t                      }g }t          d |j                  dk     r&t          d           dt	          j        g           i}ni }||d<   |d         }|dddf         | j        k    |dddf         dk    z  }||ddf         }|D ]}t          |d                   |d	d         |d         }}}|\  }	}
}}t          t          |	|
||          | j
                            ||          |
          }|                    |           |S )zprocess outputc                     | |z  S )N )xys     r+   <lambda>z:PaddleDetectionLayoutModel.gather_output.<locals>.<lambda>   s
    q1u r-      z[WARNING] No object detected.boxesNr
   r   r   )typescore)r   r   r   r\   r"   r#   r7   intr   r   rB   rD   append)rF   np_boxeslayoutresultsexpect_boxesnp_boxclsidbboxru   x_1y_1x_2y_2	cur_blocks                 r+   gather_outputz(PaddleDetectionLayoutModel.gather_output   s@   $$hn55991222-GGG'GG7# A7HQQQTNR<OPL!!!O, 		% 		%F!$VAYVAY4E!%Cc3!#sC--^''u55  I
 MM)$$$$r-   c                    |                      |          }|                     |          }| j                                        }|D ]7}| j                            |          }|                    ||                    8| j                                         | j                                        }| j                            |d                   }|	                                }| 
                    |          }	|	S )zDetect the layout of a given image.

        Args:
            image (:obj:`np.ndarray` or `PIL.Image`): The input image to detect.

        Returns:
            :obj:`~layoutparser.Layout`: The detected layout of the input image
        r   )image_loaderrj   rE   get_input_namesget_input_handlecopy_from_cpurunget_output_namesget_output_handlecopy_to_cpur   )
rF   r   ri   input_names
input_nameinput_tensoroutput_namesboxes_tensorrx   ry   s
             r+   detectz!PaddleDetectionLayoutModel.detect  s     !!%((''n4466% 	; 	;J>:::FFL&&vj'9::::~6688~77QHH++--##H--r-   r   )z
np.ndarrayzImage.Imagec                     t          |t          j                  r4|j        dk    r|                    d          }t	          j        |          }|S )NRGB)
isinstancer	   modeconvertr"   r#   )rF   r   s     r+   r   z'PaddleDetectionLayoutModel.image_loader"  sF    eU[)) 	$zU""e,,HUOOEr-   )NNNNNN)NFr5   )__name__
__module____qualname____doc__DEPENDENCIESDETECTOR_NAMEr   rN   rC   rj   r   r   r   r   rm   r-   r+   r   r   >   s        ( (T :L%M!M .
 .
 .
 .
f 3 3 3 3j  .  8  :%(C"D      r-   )"typingr   r   r   r   r   rS   	functoolsr   r:   PILr	   r    numpyr"   catalogr   r   r   base_layoutmodelr   elementsr   r   r   
file_utilsr   paddle.inferencer/   __all__ndarrayrv   r,   r   rm   r-   r+   <module>r      s    1 0 0 0 0 0 0 0 0 0 0 0 0 0 				              



     B B B B B B B B B B . . . . . . 4 4 4 4 4 4 4 4 4 4 - - - - - -  (
(:$)#s(O
2:rz!"   0k k k k k k k k k kr-   