
    kh'                     .   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!y)    )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      j                  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/teggl/fontify/venv/lib/python3.12/site-packages/layoutparser/models/paddledetection/layoutmodel.py_resize_imager,   &   s     ;;r?L$HhE,q/22JE,q/22J JJudDZJVWXE88Z45<<YGL,    c                   d    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y)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 }| j                  ||      \  }}t	        j
                  |      }|@|j                  d      r-|j                  d      j                  d      d   }	t        |	   }ni }|| _
        | j                  |||j                  dd      |j                  dd      	      | _        |j                  d
d      | _        |j                  dddg      | _        |j                  dt!        j"                  g dgg            | _        |j                  dt!        j"                  g dgg            | _        y )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   sW    "MMQ"
 L**;
C:..z:	$$W-)009??DQG-l;		" ,,&**?EB#''b9	 - 
 &))+s;'++MC:F&**"((%:$;#<=
 &))$9#:";<
r-   c                    t         j                  j                  t        j                  j                  |d      t        j                  j                  |d            }|dk(  r$|j                  dd       |j                  d       nU|j                          |j                  |       |r2|j                          	 |j                  d       |j                          |j                          |j                          |j!                  d
       t         j                  j#                  |      }|S # t        $ r}t        d       Y d	}~kd	}~ww xY w)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   " !!((GGLL. GGLL$9:	
 V !!$*""4( 33J?$$&44R8((* 	  """$((/$$55f=	 ! _ s   :!D- -	E6EEc                    t        || j                        \  }}t        j                  |j                  dd       j                  d      }|dz  | j                  z
  | j                  z  }|j                  d      j                         }i }t        j                  |      t        j                  ddf   j                  d      |d<   t        j                  |      t        j                  ddf   j                  d      |d<   t        j                  |      t        j                  ddf   j                  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     ,E43C3CD|hhu{{2A/66yA0DNNB	*//1((5/"**a-8??	JwXXk22::q=AHHSz!#,!7

A!F!M!Mi!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                  kD  |dddf   dkD  z  }||ddf   }|D ]f  }t        |d         |d	d |d   }}}|\  }	}
}}t        t        |	|
||      | j                  j                  ||      |
      }|j                  |       h |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   $hnn5912-GG'GG7# A7HQTNR<OPL!O, 		%F!$VAYVAY4E!%Cc3!#sC-^^''u5I
 MM)$		% r-   c                    | j                  |      }| j                  |      }| j                  j                         }|D ]1  }| j                  j	                  |      }|j                  ||          3 | j                  j                          | j                  j                         }| j                  j                  |d         }|j                         }| j                  |      }	|	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     !!%('nn446% 	;J>>:::FL&&vj'9:	; 	~~668~~77QH++-##H-r-   r   )z
np.ndarrayzImage.Imagec                     t        |t        j                        r5|j                  dk7  r|j                  d      }t	        j
                  |      }|S )NRGB)
isinstancer	   modeconvertr"   r#   )rF   r   s     r+   r   z'PaddleDetectionLayoutModel.image_loader"  s<    eU[[)zzU"e,HHUOEr-   )NNNNNN)NFr5   )__name__
__module____qualname____doc__DEPENDENCIESDETECTOR_NAMEr   rN   rC   rj   r   r   r   r   rm   r-   r+   r   r   >   sg    (T :L%M!M .
f 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 	    
  B B . 4 4 - (
(::$)#s(O
2::rzz!"0k kr-   