
    khO                        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j8                  j;                  e	j<                  ej>                     j@                        Z!ej8                  jE                  e!dd	      Z#d
Z$dZ%dZ&e#Z'dZ( ejR                  e'e(      Z*dZ+dZ,ddgZ-	 	 d<dZ.d Z/d=dZ0d Z1d Z2dede3dee4e4e4e4f   fdZ5d Z6d Z7d Z8e8	 	 d>ddd ed!ede3ddf
d"       Z9e8	 	 	 	 	 	 	 	 	 	 	 d?d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:   d-ee3   fd.       Z<e8	 	 	 	 	 	 	 	 	 	 	 	 d@d/e:d0ee4   d1ee:   d2ee:   d3ee:   d4ee3   d5e;d6e;d7ee4   d8ee:   d9ee3   d:e;fd;       Z=y)A    )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_textc           	         t        |j                  d      d   |z        }| D cg c]  }|dk7  r|j                  |      d   n| }}t        | D cg c]  }|j                  |      d    c}      }	t        |      |t	        |       z  z   }
t        j                  d|	|
f|      }t        j                  d|	|
f|      }t        j                  |      }t        j                  |      }t        |       D ].  \  }}|j                  dt        |d|       ||z  z   f|||       0 |j                  |j                               S c c}w c c}w )zHelper function to draw text vertically.
    Ref: https://github.com/Belval/TextRecognitionDataGenerator/blob/7f4c782c33993d2b6f712d01e86a2f342025f2df/trdg/computer_text_generator.py
     r   r   RGBAcolorfillfont)intgetsizemaxsumlenr
   newr   Draw	enumeratetextcropgetbbox)r,   
image_font
text_colortext_background_colorcharacter_spacingspace_widthspace_heightcchar_heights
text_widthtext_heighttxt_imgtxt_masktxt_img_drawtxt_mask_drawis                   V/var/www/teggl/fontify/venv/lib/python3.12/site-packages/layoutparser/visualization.py_draw_vertical_textr?   4   s\    z))#.q1K?@L IMCDAH
1a ,>L  =1j((+A.=>Jl#&7#d)&CCKii[ 9AVWGyy*k!:BWXH>>'*LNN8,M$ 
1L1%&->)>>?	 	 	

 <<)**) >s   "EEc                 `    t        dt        t        | j                        t        z              S )Nr   )r&   r$   minsizeDEFAULT_BOX_WIDTH_RATIO)canvass    r>   _calculate_default_box_widthrE   Y   s#    q#c&++&)@@ABB    c                 b    | |t         S t        j                  |xs t        | xs t              S )N)DEFAULT_FONT_OBJECTr   truetypeDEFAULT_FONT_PATHDEFAULT_FONT_SIZE)	font_size	font_paths     r>   _create_font_objectrN   ]   s7    Y.""!!**I,J9J
 	
rF   c                    |dk(  rYt        j                  d| j                  dz  | j                  f|xs t              }|j                  | | j                  df       |S |dk(  rYt        j                  d| j                  | j                  dz  f|xs t              }|j                  | d| j                  f       |S t        d|       )Nlrr      r   r   udzInvalid direction )r
   r)   widthheightDEFAULT_TEXT_BACKGROUNDpaste
ValueError)rD   arrangementr1   
new_canvass       r>   _create_new_canvasrZ   g   s    dYY\\Av}}-'B+B


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


 	!V]]!34
  -k];<<rF   c                     t        | t        t        j                  d                  D ci c]  \  }}||
 c}}S c c}}w )N-)zipr	   DEAFULT_COLOR_PALETTEsplit)typestyper    s      r>   _create_color_paletterb      sD     ue,A,G,G,L&MND% 	e  s   =color_stringalphareturnc                     | d   dk(  rDt        |       dk(  r6| j                  d      g t        fddD              t        d|z        S 	 t	        j
                  |       }|t        d|z        fz   S #  | cY S xY w)Nr   #   c              3   B   K   | ]  }t        ||d z    d        yw)rQ      N)r$   ).0r=   	color_hexs     r>   	<genexpr>z!_get_color_rgb.<locals>.<genexpr>   s#     DQ3yQU+R0Ds   )r   rQ         )r(   lstriptupler$   r   getrgb)rc   rd   rgbrl   s      @r>   _get_color_rgbrt      s    A##l"3q"8 '',	
D)DD
e
 	

	 ##L1C#cEk*,,,	 
  s   &A6 6A<c                     t        |d      st        |j                        f}n|j                  }|j	                         j                         }||d d z   }| j                  |||       y )NpointsrQ   )rS   r"   )hasattrr   coordinatesrv   raveltolistline)drawblockr    rS   rv   verticesdrawing_verticess          r>   _draw_box_outline_on_handlerr      sg    5(#+E,=,=>@||~$$&H(2A,.II  rF   c                     t        |d      r1|j                  j                         D cg c]  }t        |       }}nt	        |j
                        }| j                  |t        ||             y c c}w )Nrv   )rw   rv   rz   rq   r   rx   polygonrt   )r|   r}   r    rd   r~   s        r>    _draw_transparent_box_on_handlerr      s_    uh.3ll.A.A.CDUE%LDD,U->->?LLue$	 Es   A0c                 B     t        j                          fd       }|S )Nc                    t        | t        j                        r1| j                  dk7  r| j                  d      } | j	                         } n/t        | t
        j                        rt        j                  |       }  | |g|i |}|S )NRGB)
isinstancer
   modeconvertcopynpndarray	fromarray)rD   layoutargskwargsoutfuncs        r>   wrapzimage_loader.<locals>.wrap   so     fekk*{{e#.[[]F

+__V,F663D3F3
rF   )	functoolswraps)r   r   s   ` r>   image_loaderr      s%    __T	 	 KrF   rD   r
   blocks	color_mapc           	         |;t        |D cg c]  }t        |d      s|j                   c}      }t        |      }| j	                         } t        j                  | d      }|D ]  }t        ||||j                     |        | S c c}w )zyGiven the image, draw a series of transparent boxes based on the blocks,
    coloring using the specified color_map.
    ra   r   )setrw   ra   rb   r   r   r*   r   )rD   r   r   rd   b	all_typesr|   r}   s           r>   draw_transparent_boxr      s     FA71f3EFG	))4	[[]F>>&&)D T(ui

6KUST M Gs
   BBr   	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      }|xs t        }|
xs t        }
|s|rt        ||	      }|dgt        |      z  }nt        |t        t        f      r|gt        |      z  }t        |      t        |      k7  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        |      k7  r#t        dt        |       d	t        |             ||;t        |D cg c]  }t        |d      s|j                   c}      }t        |      }|D cg c]8  }t        |t               st"        n|j%                  |j                  t"              : }}nYt        |t&              r|gt        |      z  }t        |      t        |      k7  r#t        dt        |       d	t        |             t        |      t        |      cxk(  rt        |      cxk(  rt        |      k(  sJ  J t)        t+        ||||            D ]  \  }\  }}}}t        |t,              r|j/                  |       }|dkD  rt1        ||||       t3        ||||       |s|sSd}|r|j4                  xs |}|t'        |      z  }|r2|st'        |j                        n|dz   t'        |j                        z   }|j6                  dd \  }}j9                  |      \  }}t;        ||||z   ||z         }t3        ||||       |j=                  ||f||
|       
 | S c c}w c c}w )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   <   K   | ]  }d |cxk  xr dk  nc   yw)r   r   N )rk   as     r>   rm   zdraw_box.<locals>.<genexpr>J  s     211;Q;;2s   zThe box_alpha value zThe number of widths ra   zThe number of colors  z: rQ   r!   )rW   r   r*   rU   DEFAULT_TEXT_COLORrN   r(   r   floatr$   allrE   r   rw   ra   rb   r   DEFAULT_OUTLINE_COLORgetstrr+   r]   r   put_on_canvasr   r   idrx   r%   r   r,   )rD   r   r   r   r   r   r   r   r   r   r   r   r   r|   font_objr   r   eleidxr    rd   rS   r,   ele_idstart_xstart_ytext_wtext_htext_box_objects                                r>   r   r      s   h (-A- z
-.F-GGbc0 - >>&v.D7R;R!7%7M+&|\BC#f+%	i%."c&k1Iy>S[('I'77]^abh^i]jk  2	22&yk1LM  08	K#f+-	i%."c&k1Iy>S[('I'77]^abh^i]jk  VJwq&7IQVVJKI-i8I
 	
  c9- "sxx)>?@
	 
 i%"c&k1Iy>S[('I'77]^abh^i]jk  v;#i.LC	NLc)nLLLLL+4FIy)4, )''c5% c8$##F+C19(sE5A(sE5A/D3F# ,0s388}dTkCM6Q"r2GW%--d3NFF''F"2Gf4DO
 -((	 II'""	  I)V MC K
s   8N%
N%.=N*rX   rL   rM   r0   r1   text_background_alphavertical_textwith_box_on_texttext_box_widthtext_box_colortext_box_alphawith_layoutc           
      V   |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        ||      }|xs t        }|xs t
        }|xs t        }t        | |t        ||            } t        j                  | d      }t        |      D ]  \  }}|	r/|j                  |
|
      }t        ||||
       t        ||||       t        |d	      r|j                   d
k(  rS|j"                  dd \  }}|s"|j!                  ||f|j                   ||       t%        |j                   ||t        ||            }|	r| j'                  |||
z   ||
z   f       | j'                  |||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bottomr,   r   rQ   )r#   r"   )rW   rE   r   rN   r   r   rU   rZ   rt   r   r*   r+   padr   r   rw   r,   rx   r?   rV   )rD   r   rX   rL   rM   r0   r1   r   r   r   r   r   r   r   r   r   r|   r   r   modified_boxr   r   text_segments                          r>   r   r     s   h $ !%** J
*+@*AA\]- * #!# Z
#N#33NO& # !9&AN&&3F3"9i8H#<'<N11J1L5L,.CDF
 >>&&)Df% %?S777OL(lNN -lNN sF#sxx2~ __Ra0'II'"	   /46KL	L   7^#;W~=U"V \GW+=>K%?N MrF   )rQ   r   )NN)Ng      ?)NNNNFFNNNNr   )rP   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_pathrC   r   r^   rJ   rK   rI   rH   r   rU   __all__r?   rE   rN   rZ   rb   r   r$   rt   r   r   r   r   r   boolr   r   r   rF   r>   <module>r      sa   A @ @  	 
   7 7   6 GGOOCKK(@(@AJJK	WW\\)V-IJ
  A    (i(():<MN  ! {
# "+JC
0   U  uS#sC=O7P  ("
   	  	
  .  265915 $!#"&"&#'.201}KK}} d3in-.} d5k5012	}
 d3in-.} ~} } } 3-} 3-} C=} 'sm} 'uo} }@  ## $+/-1"$($(&*Y Y }	Y
 }Y Y $C=Y $E?Y Y Y SMY SMY UOY Y YrF   