o
    0j.                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlZ	d dl
mZmZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZmZmZ edr`d dl Z edG dd deZ!ed	ddee"e"f de	j#de$de%de	j#f
ddZ&dS )    N)DictTuple)Image	ImageDraw   )logging)class_requires_depsfunction_requires_depsis_dep_available)PINGFANG_FONT   )BaseCVResult	JsonMixin)crop_white_areadraw_box_txt_finedraw_formula_module	env_validgenerate_pdf_filegenerate_tex_filepdf2imgzopencv-contrib-pythonc                   @   sT   e Zd ZdZdeeejf fddZdeeef fddZdeeef fddZ	d	S )
FormulaRecognitionResultzFormula Recognition Resultreturnc           %      C   s0  t | d d dddddddf }i }| d }|d r*|jd$i | d j | d }t|dkr;|jd	 |d< zt  W n tjy^ } zt	d
 ||d< |W  Y d}~S d}~ww t|dkrt
|d}| d d d }t|}|dur|\}}	}
}||	|	| |||
 f }t |}|j\}}ddg|dg||gd|gg}zPt|j||dd}t |}|j\}}|}t|| | }|||ft j}|jt| d }t d||fd}||d |||jd df ||d< |W S  tjy } zt	d ||d< |W  Y d}~S d}~ww |j|j}}
| }t
j||
dft
jdd }td t|}| d  tt| d D ]}| d | }|d  t|d }|d }t |\}}}} zdt!ddt!ddt!ddf}!|||||| || g}t
|"ddg}dd |# D }"|j$|"|!dd |j$||!d t%|
|f||dd}#t
|t
j&"d }"t'(|#|"gd!|!d" t')||#}W qH tjy } zt	d W Y d}~qHd}~ww t *||d#}t dt|
d |fd}$|$|dd|
|f |$t ||
d|
d |f |$|d< |S )%z
        Converts the internal data to a PIL Image with detection and recognition results.

        Returns:
            Dict[str, Image.Image]: An image with detection boxes, texts, and scores blended on it.
        doc_preprocessor_resZ
output_imgNmodel_settingsuse_doc_preprocessorlayout_det_resr   reszPlease refer to 2.3 Formula Recognition Pipeline Visualization in Formula Recognition Pipeline Tutorial to install the LaTeX rendering engine at first.Zformula_res_imgRGBformula_res_listrec_formulaF)is_debug
      r$   r$   )r   r   z3Syntax error detected in formula, rendering failed.r   Zdtyper$   formula_region_iddt_polys   c                 S   s   g | ]\}}||fqS  r)   ).0xyr)   r)   w/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddlex/inference/pipelines/formula_recognition/result.py
<listcomp>   s    z4FormulaRecognitionResult._to_img.<locals>.<listcomp>   )outlinewidth)fill)r      r(   Tr3   g      ?r)   )+r   Z	fromarrayupdateZimglenr   
subprocessCalledProcessErrorr   warningnparrayconvertr   sizer   intresizeZLANCZOSr1   newZpasteheightcopyZonesuint8randomseedr   ZDrawrangestrlistrandintZreshapetolistZpolygondraw_box_formula_fineZint32cv2Z	polylinesZbitwise_andblend)%selfimageZres_img_dictr   r   er    Zxywhr+   r,   whZimage_widthZimage_heightboxZimg_formularender_widthrender_heightresize_heightresize_widthZnew_image_widthZ	new_imageZimg_leftZ	img_rightZ	draw_lefttnoZformula_resformular'   x1y1Zx2y2colorZptsimg_right_textZimg_showr)   r)   r-   _to_img/   s   *













z FormulaRecognitionResult._to_imgc                 O   s   i }| d |d< | d |d< | d |d< | d d r#| d j d |d< t| d dkr4| d j d |d< g |d	< tt| d	 D ]-}| d	 | d
 | d	 | d d}d| d	 | v rf| d	 | d f|d< |d	 | q@tj|g|R i |S )ax  Converts the instance's attributes to a dictionary and then to a string.

        Args:
            *args: Additional positional arguments passed to the base class method.
            **kwargs: Additional keyword arguments passed to the base class method.

        Returns:
            Dict[str, str]: A dictionary with the instance's attributes converted to strings.
        
input_path
page_indexr   r   r   r   r   r   r   r    r&   r    r&   r'   )rF   r5   rE   appendr   _to_strrM   argskwargsdatarW   Zrec_formula_dictr)   r)   r-   rc      s$   
z FormulaRecognitionResult._to_strc                 O   s   i }| d |d< t | d |d< | d |d< | d d r%| d j d |d< t| d dkr6| d j d |d< g |d	< tt| d	 D ]-}| d	 | d
 | d	 | d d}d| d	 | v rh| d	 | d f|d< |d	 | qBtj|g|R i |S )a[  
        Converts the object's data to a JSON dictionary.

        Args:
            *args: Positional arguments passed to the JsonMixin._to_json method.
            **kwargs: Keyword arguments passed to the JsonMixin._to_json method.

        Returns:
            Dict[str, str]: A dictionary containing the object's data in JSON format.
        r_   r`   r   r   r   r   r   r   r   r    r&   ra   r'   )rF   r5   rE   rb   r   _to_jsonrd   r)   r)   r-   rh      s$   z!FormulaRecognitionResult._to_jsonN)
__name__
__module____qualname____doc__r   rF   r   r^   rc   rh   r)   r)   r)   r-   r   +   s
    j r   Fimg_sizerR   rX   r!   r   c              	   C   s  	 t t|d d |d d  d |d d |d d  d  }t t|d d |d d  d |d d |d d  d  }t }tj|d}tj|d}tj|d}	t|| tj	|rnt
||| d}
tj	|r}t||	d	d
}
|
dur|
jdd \}}|}|| | }t|
t |t |f}
|
jdd \}}tddg|dg||gd|gg}tj|tjd}t||}tj|
tjd}
tj|
|| tjtjdd}nt| |dtj}|W  d   S 1 sw   Y  dS )zdraw box formula for pipeliner   r   r(   r3   ztemp.texztemp.pdfztemp.jpgNF)Z
is_paddingr   r%   r#   )flagsZ
borderModeZborderValuezRendering Failed)r=   mathsqrttempfileTemporaryDirectoryospathjoinr   existsr   r   shaperK   r>   r9   Zfloat32r:   ZgetPerspectiveTransformrB   ZwarpPerspectiveZINTER_NEARESTZBORDER_CONSTANTr   r   )rm   rR   rX   r!   Z
box_heightZ	box_widthtdZtex_file_pathZpdf_file_pathZimg_file_pathZformula_imgZ	formula_hZ	formula_wrU   rV   Zpts1Zpts2Mr]   r)   r)   r-   rJ      sX   <<

	
$rJ   )F)'ro   rs   rC   r6   rq   typingr   r   numpyr9   ZPILr   r   utilsr   Z
utils.depsr   r	   r
   Zutils.fontsr   Zcommon.resultr   r   Z!models.formula_recognition.resultr   r   r   r   r   r   r   rK   r   r=   ZndarrayrF   boolrJ   r)   r)   r)   r-   <module>   s>   $
 0
