
    NgO                        d dl mZmZmZmZmZmZmZ d dlZd dlZd dl	Z	d dl
mZ d dlZd dlmZmZmZmZ d dlZddlmZmZmZmZmZ ddlmZ ej                            e	j        ej                 j                   Z!ej        "                    e!dd	          Z#d
Z$dZ%dZ&e#Z'dZ( ej)        e'e(          Z*dZ+dZ,ddgZ-	 	 d@dZ.d Z/dAdZ0d Z1d Z2dede3dee4e4e4e4f         fdZ5d Z6d Z7d Z8e8	 	 dBd d!d"ed#ede3dd!f
d$            Z9e8	 	 	 	 	 	 	 	 	 	 	 dCd ej        d&ed'eeee4         e4f                  d(eeee3         e3f                  d)eeee:         e:f                  d#ee         d*e;d+e;d,ee4         d-ee:         d.ee:         d/ee:         d0ee3         fd1            Z<e8	 	 	 	 	 	 	 	 	 	 	 	 dDd3e:d4ee4         d5ee:         d6ee:         d7ee:         d8ee3         d9e;d:e;d;ee4         d<ee:         d=ee3         d>e;fd?            Z=dS )E    )ListOptionalUnionDictAnyTupler   N)cycle)Image	ImageFont	ImageDraw
ImageColor   )LayoutInterval	Rectangle	TextBlockQuadrilateral)cvt_coordinates_to_pointsmisczNotoSerifCJKjp-Regular.otfg{Gzt?redz'#f6bd60-#f7ede2-#f5cac3-#84a59d-#f28482   blackwhitedraw_box	draw_text   c           	         t                              d          d         |z            fd| D             }t          fd| D                       }t          |          |t	          |           z  z   }t          j        d||f|          }	t          j        d||f|          }
t          j        |	          }t          j        |
          }t          |           D ];\  }}|
                    dt          |d|                   ||z  z   f||           <|	                    |	                                          S )	zHelper function to draw text vertically.
    Ref: https://github.com/Belval/TextRecognitionDataGenerator/blob/7f4c782c33993d2b6f712d01e86a2f342025f2df/trdg/computer_text_generator.py
     r   c                 V    g | ]%}|d k    r                     |          d         n&S )r   r   getsize).0c
image_fontspace_heights     V/var/www/html/ai-engine/env/lib/python3.11/site-packages/layoutparser/visualization.py
<listcomp>z'_draw_vertical_text.<locals>.<listcomp>B   sF       CDAHH
1a  ,      c                 F    g | ]}                     |          d          S )r   r    )r"   r#   r$   s     r&   r'   z'_draw_vertical_text.<locals>.<listcomp>E   s,    ===1j((++A.===r(   RGBAcolorr   fillfont)intr!   maxsumlenr
   newr   Draw	enumeratetextcropgetbbox)r7   r$   
text_colortext_background_colorcharacter_spacingspace_widthchar_heights
text_widthtext_heighttxt_imgtxt_masktxt_img_drawtxt_mask_drawir#   r%   s    `             @r&   _draw_vertical_textrF   4   sv    z))#..q1K?@@L    HL  L =======>>Jl##&7#d))&CCKi[ 9AVWWWGy*k!:BWXXXH>'**LN8,,M$ 
 
1L1%&&->)>>?	 	 	
 	
 	
 	
 <<))***r(   c                 p    t          dt          t          | j                  t          z                      S )Nr   )r1   r0   minsizeDEFAULT_BOX_WIDTH_RATIO)canvass    r&   _calculate_default_box_widthrL   Y   s*    q#c&+&&)@@AABBBr(   c                 ^    | 	|t           S t          j        |pt          | pt                    S )N)DEFAULT_FONT_OBJECTr   truetypeDEFAULT_FONT_PATHDEFAULT_FONT_SIZE)	font_size	font_paths     r&   _create_font_objectrT   ]   s9    Y.""!**I,J9J
 
 	
r(   c                 n   |dk    rKt          j        d| j        dz  | j        f|pt                    }|                    | | j        df           nc|dk    rKt          j        d| j        | j        dz  f|pt                    }|                    | d| j        f           nt          d|           |S )Nlrr*   r   r+   r   udzInvalid direction )r
   r4   widthheightDEFAULT_TEXT_BACKGROUNDpaste
ValueError)rK   arrangementr;   
new_canvass       r&   _create_new_canvasr_   g   s    dY\Av}-'B+B
 
 


 	&,!23333			Y\6=1,-'B+B
 
 


 	!V]!34444 ;k;;<<<r(   c           	          d t          | t          t                              d                              D             S )Nc                     i | ]\  }}||	S  rb   )r"   typer,   s      r&   
<dictcomp>z)_create_color_palette.<locals>.<dictcomp>   s.       D% 	e  r(   -)zipr	   DEAFULT_COLOR_PALETTEsplit)typess    r&   _create_color_paletterj      sD     ue,A,G,G,L,L&M&MNN   r(   color_stringalphareturnc                 4   | d         dk    rXt          |           dk    rE|                     d          g t          fddD                       t          d|z            R S 	 t	          j        |           }|t          d|z            fz   S #  | cY S xY w)Nr   #   c              3   N   K   | ]}t          ||d z            d          V   dS )r      N)r0   )r"   rE   	color_hexs     r&   	<genexpr>z!_get_color_rgb.<locals>.<genexpr>   s:      DDQ3yQU+R00DDDDDDr(   )r   r         )r3   lstriptupler0   r   getrgb)rk   rl   rgbrs   s      @r&   _get_color_rgbr{      s    A##l"3"3q"8"8 '',,	
DDDD)DDDDD
e
 
 	

	 #L11C#cEk**,,,	 
  s   ')B Bc                     t          |d          st          |j                  f}n|j        }|                                                                }||d d         z   }|                     |||           d S )Npointsr   )rX   r.   )hasattrr   coordinatesr}   raveltolistline)drawblockr,   rX   r}   verticesdrawing_verticess          r&   _draw_box_outline_on_handlerr      s    5(## +E,=>>@||~~$$&&H(2A2,.II      r(   c                     t          |d          r$d |j                                        D             }nt          |j                  }|                     |t          ||                     d S )Nr}   c                 ,    g | ]}t          |          S rb   )rx   )r"   r   s     r&   r'   z4_draw_transparent_box_on_handler.<locals>.<listcomp>   s    DDDUE%LLDDDr(   )r~   r}   r   r   r   polygonr{   )r   r   r,   rl   r   s        r&    _draw_transparent_box_on_handlerr      sx    uh @DDel.A.A.C.CDDD,U->??LLue$$    r(   c                 F     t          j                    fd            }|S )Nc                    t          | t          j                  r5| j        dk    r|                     d          } |                                 } n.t          | t
          j                  rt          j        |           }  | |g|R i |}|S )NRGB)
isinstancer
   modeconvertcopynpndarray	fromarray)rK   layoutargskwargsoutfuncs        r&   wrapzimage_loader.<locals>.wrap   s     fek** 	-{e##..[[]]FF
++ 	-_V,,Fd663D333F33
r(   )	functoolswraps)r   r   s   ` r&   image_loaderr      s8    _T	 	 	 	 	 Kr(         ?rK   r
   blocks	color_mapc                     |(t          d |D                       }t          |          }|                                 } t          j        | d          }|D ]}t          ||||j                 |            | S )zyGiven the image, draw a series of transparent boxes based on the blocks,
    coloring using the specified color_map.
    Nc                 <    g | ]}t          |d           |j        S rc   r~   rc   r"   bs     r&   r'   z(draw_transparent_box.<locals>.<listcomp>   s)    FFFA71f3E3EFFFFr(   r*   )setrj   r   r   r5   r   rc   )rK   r   r   rl   	all_typesr   r   s          r&   draw_transparent_boxr      s     FFFFFGG	))44	[[]]F>&&))D T T(ui
6KUSSSSMr(   Fr   	box_width	box_alpha	box_colorshow_element_idshow_element_typeid_font_sizeid_font_pathid_text_colorid_text_background_colorid_text_background_alphac                    d|cxk    rdk    sn J t          d| d                      t          j        | d          }|pt          }|
pt          }
|s|rt          ||	          }|dgt          |          z  }nt          |t          t          f          r|gt          |          z  }t          |          t          |          k    r/t          dt          |           d	t          |                     t          d
 |D                       st          d| d          |#t          |           }|gt          |          z  }n~t          |t          t          f          r|gt          |          z  }t          |          t          |          k    r/t          dt          |           d	t          |                     |9(t          d |D                       }t          |          fd|D             }nwt          |t                    r|gt          |          z  }t          |          t          |          k    r/t          dt          |           d	t          |                     t          |          t          |          cxk    r't          |          cxk    rt          |          k    sn J t          t!          ||||                    D ]#\  }\  }}}}t          |t"                    r|                    |           }|dk    rt'          ||||           t)          ||||           |s|rd}|r|j        p|}|t          |          z  }|r0|st          |j                  n|dz   t          |j                  z   }|j        dd         \  }}|                    |          \  }}t3          ||||z   ||z             }t)          ||||           |                    ||f||
|           %| S )a  Draw the layout region on the input canvas(image).

    Args:
        canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
            The canvas to draw the layout boxes.
        layout (:obj:`Layout` or :obj:`list`):
            The layout of the canvas to show.
        box_width (:obj:`int` or :obj:`List[int]`, optional):
            Set to change the width of the drawn layout box boundary.
            Defaults to None, when the boundary is automatically
            calculated as the the :const:`DEFAULT_BOX_WIDTH_RATIO`
            * the maximum of (height, width) of the canvas.
            If box_with is a list, it will assign different widths to
            the corresponding layout object, and should have the same
            length as the number of blocks in `layout`.
        box_alpha (:obj:`float`  or :obj:`List[float]`, optional):
            A float or list of floats ranging from 0 to 1. Set to change
            the alpha of the drawn layout box.
            Defaults to 0 - the layout box will be fully transparent.
            If box_alpha is a list of floats, it will assign different
            alphas to the corresponding layout object, and should have
            the same length as the number of blocks in `layout`.
        box_color (:obj:`str`  or :obj:`List[str]`, optional):
            A string or a list of strings for box colors, e.g.,
            `['red', 'green', 'blue']` or `'red'`.
            If box_color is a list of strings, it will assign different
            colors to the corresponding layout object, and should have
            the same length as the number of blocks in `layout`.
            Defaults to None. When `box_color` is set, it will override the
            `color_map`.
        color_map (dict, optional):
            A map from `block.type` to the colors, e.g., `{1: 'red'}`.
            You can set it to `{}` to use only the
            :const:`DEFAULT_OUTLINE_COLOR` for the outlines.
            Defaults to None, when a color palette is is automatically
            created based on the input layout.
        show_element_id (bool, optional):
            Whether to display `block.id` on the top-left corner of
            the block.
            Defaults to False.
        show_element_type (bool, optional):
            Whether to display `block.type` on the top-left corner of
            the block.
            Defaults to False.
        id_font_size (int, optional):
            Set to change the font size used for drawing `block.id`.
            Defaults to None, when the size is set to
            :const:`DEFAULT_FONT_SIZE`.
        id_font_path (:obj:`str`, optional):
            Set to change the font used for drawing `block.id`.
            Defaults to None, when the :const:`DEFAULT_FONT_OBJECT` is used.
        id_text_color (:obj:`str`, optional):
            Set to change the text color used for drawing `block.id`.
            Defaults to None, when the color is set to
            :const:`DEFAULT_TEXT_COLOR`.
        id_text_background_color (:obj:`str`, optional):
            Set to change the text region background used for drawing `block.id`.
            Defaults to None, when the color is set to
            :const:`DEFAULT_TEXT_BACKGROUND`.
        id_text_background_alpha (:obj:`float`, optional):
            A float range from 0 to 1. Set to change the alpha of the
            drawn text.
            Defaults to 1 - the text box will be solid.
    Returns:
        :obj:`PIL.Image.Image`:
            A Image object containing the `layout` draw upon the input `canvas`.
    r   r   z#The id_text_background_alpha value  is not within range [0,1].r*   )r   NzThe number of alphas z& is not equal to the number of blocks c              3   6   K   | ]}d |cxk    odk    nc V  dS )r   r   Nrb   )r"   as     r&   rt   zdraw_box.<locals>.<genexpr>J  s6      2211;;;;Q;;;;222222r(   zThe box_alpha value zThe number of widths c                 <    g | ]}t          |d           |j        S r   r   r   s     r&   r'   zdraw_box.<locals>.<listcomp>]  s)    JJJwq&7I7IJQVJJJr(   c                     g | ]>}t          |t                    st          n                    |j        t                    ?S rb   )r   r   DEFAULT_OUTLINE_COLORgetrc   )r"   eler   s     r&   r'   zdraw_box.<locals>.<listcomp>_  sU     
 
 
  c9--@!!sx)>??
 
 
r(   zThe number of colors  z: r   r-   )r\   r   r5   rZ   DEFAULT_TEXT_COLORrT   r3   r   floatr0   allrL   r   rj   strr6   rf   r   put_on_canvasr   r   idrc   r   r!   r   r7   )rK   r   r   r   r   r   r   r   r   r   r   r   r   r   font_objr   idxr   r,   rl   rX   r7   ele_idstart_xstart_ytext_wtext_htext_box_objects        `                      r&   r   r      s   h (----A-----zc.Fccc0 0--- >&v...D7R;R!7%7M C+ C&|\BBC#f++%		i%.. 	2"c&kk1Iy>>S[[((kIkk^abh^i^ikk   22	22222 	MyMMM   088	K#f++-		i%.. 	2"c&kk1Iy>>S[[((kIkk^abh^i^ikk   JJVJJJKKI-i88I
 
 
 
 	
 
 
		 i%% 	2"c&kk1Iy>>S[[((kIkk^abh^i^ikk   v;;#i..LLLLC	NNLLLLc)nnLLLLLL+4FIy)44, , ) )''c5% c8$$ 	,##F++C199(sE5AAA(sE5AAA 	/ 	D $3F#  R,0Qs38}}}dTkCMM6Q"rr2GW%--d33NFF''F"2Gf4D O
 -((	   II'""	     Mr(   rV   r]   rR   rS   r:   r;   text_background_alphavertical_textwith_box_on_texttext_box_widthtext_box_colortext_box_alphawith_layoutc           
         |d}|d}d|cxk    rdk    sn J t          d| d                      d|cxk    rdk    sn J t          d| d                      |	r|
t          |           }
|rt          | |fi |} t          ||          }|pt          }|pt
          }|pt          }t          | |t          ||                    } t          j
        | d          }t          |          D ]\  }}|	r;|                    |
|
          }t          ||||
           t          ||||           t          |d	          r|j        d
k    r^|j        dd         \  }}|s!|                    ||f|j        ||           t%          |j        ||t          ||                    }|	r|                     |||
z   ||
z   f           |                     |||f           | S )a<  Draw the (detected) text in the `layout` according to
    their coordinates next to the input `canvas` (image) for better comparison.

    Args:
        canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
            The canvas to draw the layout boxes.
        layout (:obj:`Layout` or :obj:`list`):
            The layout of the canvas to show.
        arrangement (`{'lr', 'ud'}`, optional):
            The arrangement of the drawn text canvas and the original
            image canvas:
            * `lr` - left and right
            * `ud` - up and down
            Defaults to 'lr'.
        font_size (:obj:`str`, optional):
            Set to change the size of the font used for
            drawing `block.text`.
            Defaults to None, when the size is set to
            :const:`DEFAULT_FONT_SIZE`.
        font_path (:obj:`str`, optional):
            Set to change the font used for drawing `block.text`.
            Defaults to None, when the :const:`DEFAULT_FONT_OBJECT` is used.
        text_color ([type], optional):
            Set to change the text color used for drawing `block.text`.
            Defaults to None, when the color is set to
            :const:`DEFAULT_TEXT_COLOR`.
        text_background_color ([type], optional):
            Set to change the text region background used for drawing
            `block.text`.
            Defaults to None, when the color is set to
            :const:`DEFAULT_TEXT_BACKGROUND`.
        text_background_alpha (:obj:`float`, optional):
            A float range from 0 to 1. Set to change the alpha of the
            background of the canvas.
            Defaults to 1 - the text box will be solid.
        vertical_text (bool, optional):
            Whether the text in a block should be drawn vertically.
            Defaults to False.
        with_box_on_text (bool, optional):
            Whether to draw the layout box boundary of a text region
            on the text canvas.
            Defaults to False.
        text_box_width (:obj:`int`, optional):
            Set to change the width of the drawn layout box boundary.
            Defaults to None, when the boundary is automatically
            calculated as the the :const:`DEFAULT_BOX_WIDTH_RATIO`
            * the maximum of (height, width) of the canvas.
        text_box_alpha (:obj:`float`, optional):
            A float range from 0 to 1. Set to change the alpha of the
            drawn text box.
            Defaults to 0 - the text box will be fully transparent.
        text_box_color (:obj:`int`, optional):
            Set to change the color of the drawn layout box boundary.
            Defaults to None, when the color is set to
            :const:`DEFAULT_OUTLINE_COLOR`.
        with_layout (bool, optional):
            Whether to draw the layout boxes on the input (image) canvas.
            Defaults to False.
            When set to true, you can pass in the arguments in
            :obj:`draw_box` to change the style of the drawn layout boxes.

    Returns:
        :obj:`PIL.Image.Image`:
            A Image object containing the drawn text from `layout`.
    Nr   r   z The text_background_color value r   zThe text_box_alpha value r*   )rightbottomr7   r   r   )r/   r.   )r\   rL   r   rT   r   r   rZ   r_   r{   r   r5   r6   padr   r   r~   r7   r   rF   r[   )rK   r   r]   rR   rS   r:   r;   r   r   r   r   r   r   r   r   r   r   r   r   modified_boxr   r   text_segments                          r&   r   r     s   h $ !%*********J]+@]]]- -*** ####!#####ZONOOO& &###  B!9&AAN 4&&33F33"9i88H#<'<N11J1L5L,.CDD F
 >&&))Df%% %? %?S 	777OOL(lNN   -lNN   sF## 	sx2~~ _RaR0' 	?II'"	      /46KLL	 L   ? 7^#;W~=U"V    \GW+=>>>>Mr(   )r   r   )NN)Nr   )NNNNFFNNNNr   )rV   NNNNNFFNNNF)>typingr   r   r   r   r   r   r   ossys	itertoolsr	   numpyr   PILr
   r   r   r   layoutparserelementsr   r   r   r   r   elements.utilsr   pathdirnamemodules__package____file__	_lib_pathjoin
_font_pathrJ   r   rg   rP   rQ   rO   rN   r   rZ   __all__rF   rL   rT   r_   rj   r   r0   r{   r   r   r   r   r   boolr   r   rb   r(   r&   <module>r      s   A @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @     				 



           7 7 7 7 7 7 7 7 7 7 7 7                  6 5 5 5 5 5 GOOCK(@AJKK	W\\)V-IJJ
  A    (i():<MNN  ! {
# "+ "+ "+ "+JC C C
 
 
 
  0     U  uS#sC=O7P        (  "
 
 
     	   	
    .  265915 $!#"&"&#'.201} }K}} d3in-.} d5k5012	}
 d3in-.} ~} } } 3-} 3-} C=} 'sm} 'uo} } } }@  ## $+/-1"$($(&*Y Y Y }	Y
 }Y Y $C=Y $E?Y Y Y SMY SMY UOY Y Y Y Y Y Yr(   