
    j>3                        d dl Z d dlmZ d dlmZ d dlZd dlmZ d dlm	Z
 d dlZd dlmZ ddlmZmZ g dZ	 	 	 	 	 	 d(dedeeef         dedz  deeeef         dededededej        fdZ	 	 	 	 	 	 d(dej        deeef         dedz  deeeef         dededededej        fdZdeez  ej        z  deeef         dedej        fdZdedeeeeef                  fdZ 	 	 	 	 	 d)de!eef         dej        ded ed!ed"ed#ededefd$Z"	 	 	 	 	 d*de!eef         dej        ded ed!ed"ed#ededefd%Z#d+d&ej        dej        deeeef         dz  ddfd'Z$dS ),    N)deepcopy)Any)Figure   )BoundingBox	Polygon4P)visualize_pagevisualize_kie_page
draw_boxesr   r   r   333333?   TFgeometrypage_dimensionslabelcoloralpha	linewidthfillpreserve_aspect_ratioreturnc           
      D   t          |           dk    st          d | D                       rt          d          |\  }}	| \  \  }
}\  }}|rt          ||	          x}	}|
|	z  ||
z
  |	z  }}
||z  ||z
  |z  }}t	          j        |
|f||||g ||R g ||R |          S )a  Create a matplotlib rectangular patch for the element

    Args:
        geometry: bounding box of the element
        page_dimensions: dimensions of the Page in format (height, width)
        label: label to display when hovered
        color: color to draw box
        alpha: opacity parameter to fill the boxes, 0 = transparent
        linewidth: line width
        fill: whether the patch should be filled
        preserve_aspect_ratio: pass True if you passed True to the predictor

    Returns:
        a rectangular Patch
    r   c              3   h   K   | ]-}t          |t                     pt          |          d k    V  .dS )r   N)
isinstancetuplelen).0elts     \/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/doctr/utils/visualization.py	<genexpr>zrect_patch.<locals>.<genexpr>-   s?       a aQTZU%;%;!;!Ls3xx1} a a a a a a    invalid geometry formatr   r   	edgecolor	facecolorr   )r   any
ValueErrormaxpatches	Rectangle)r   r   r   r   r   r   r   r   heightwidthxminyminxmaxymaxwhs                   r   
rect_patchr3      s    2 8}}S a aX` a a aaa2333 $MFE!)LT4,4 ,VU+++UlTD[E1!DVmdTkV3!D	t		!E/5//!E/5//	 	 	 	r!   c                 (   | j         dk    st          d          |\  }}	| dddf         |rt          |	|          n|	z  | dddf<   | dddf         |rt          |	|          n|z  | dddf<   t          j        | ||g ||R g ||R |          S )a  Create a matplotlib polygon patch for the element

    Args:
        geometry: bounding box of the element
        page_dimensions: dimensions of the Page in format (height, width)
        label: label to display when hovered
        color: color to draw box
        alpha: opacity parameter to fill the boxes, 0 = transparent
        linewidth: line width
        fill: whether the patch should be filled
        preserve_aspect_ratio: pass True if you passed True to the predictor

    Returns:
        a polygon Patch
       r   r"   Nr   r   r#   )shaper'   r(   r)   Polygon)
r   r   r   r   r   r   r   r   r+   r,   s
             r   polygon_patchr9   E   s    2 >V##2333 $MFEaaad^=R']s5&'9'9'9X]^HQQQTNaaad^=R'^s5&'9'9'9X^_HQQQTN?!E/5//!E/5//   r!   kwargsc                 Z   t          | t                    rUt          |           dk    rt          | |fi |S t          |           dk    r t	          t          j        |           |fi |S n3t          | t
          j                  r| j        dk    rt	          | |fi |S t          d          )a"  Create a matplotlib patch for the element

    Args:
        geometry: bounding box (straight or rotated) of the element
        page_dimensions: dimensions of the page in format (height, width)
        **kwargs: keyword arguments for the patch

    Returns:
        a matplotlib Patch
    r   r6   r5   r"   )
r   r   r   r3   r9   npasarrayndarrayr7   r'   )r   r   r:   s      r   create_obj_patchr?   p   s     (E"" Bx==AhBB6BBB]]a H!5!5QQ&QQQ  	Hbj	)	) Bhn.F.FXAA&AAA
.
/
//r!   
num_colorsc                 :   g }t          j        ddd| z            D ]~}|dz  }dt           j                                        dz  z   dz  }dt           j                                        dz  z   dz  }|                    t          j        |||                     |S )zGenerate num_colors color for matplotlib

    Args:
        num_colors: number of colors to generate

    Returns:
        colors: list of generated colors
            g     v@2   
   g      Y@Z   )r<   arangerandomrandappendcolorsys
hls_to_rgb)r@   colorsihue	lightness
saturations         r   
get_colorsrQ      s     FYsE5:#566 G G%i")..**R//58	29>>++b00E9
h)#y*EEFFFFMr!   rD   pageimage
words_onlydisplay_artefactsscaleinteractive
add_labelsc           
         |j         dd         \  }}	||	k    r
||	z  |z  |fn	|||	z  |z  f}
t          j        |
          \  }}|                    |           |                    d           |rg }| d         D ]}|sJt          |d         | d         fdd	d
d|}|                    |           |r|                    |           |d         D ]}|sJt          |d         | d         fddd
d|}|                    |           |r|                    |           |d         D ]}t          |d         | d         f|d          d|d         dddd|}|                    |           |r|                    |           `|r%t          |d                   dk    ryt          | d         d
         |d         d         |d         d         dz  z
  z            t          | d         d         |d         d
         |d         d         dz  z
  z            f}n`t          | d         d
         |d         d         d         z            t          | d         d         |d         d         d
         z            f}t          |d                   dk    r |j
        g ||d         R dddd |rU|d         D ]L}t          |d         | d         fddd
d|}|                    |           |r|                    |           M|r0ddl}|                    |d                               d!d"            |                    d#$           |S )%a  Visualize a full page with predicted blocks, lines and words

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from doctr.utils.visualization import visualize_page
    >>> from doctr.models import ocr_db_crnn
    >>> model = ocr_db_crnn(pretrained=True)
    >>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
    >>> out = model([[input_page]])
    >>> visualize_page(out[0].pages[0].export(), input_page)
    >>> plt.show()

    Args:
        page: the exported Page of a Document
        image: np array of the page, needs to have the same shape than page['dimensions']
        words_only: whether only words should be displayed
        display_artefacts: whether artefacts should be displayed
        scale: figsize of the largest windows side
        interactive: whether the plot should be interactive
        add_labels: for static plot, adds text labels on top of bounding box
        **kwargs: keyword arguments for the polygon patch

    Returns:
        the matplotlib figure
    Nr   figsizeoffblocksr   
dimensionsblock)r   r   r   r   r   r   r   linesline)r   r   r   wordsvalue (confidence: 
confidence.2%))r   r   r   )r   r      r      rD         ?)sizer   r   	artefactsartefact)rk   rk   rk   hoveraddc                 d    | j                             | j                                                  S N
annotationset_textartist	get_labelsels    r   <lambda>z visualize_page.<locals>.<lambda>  &    s~G^G^_b_i_s_s_u_uGvGv r!   rB   pad)r7   pltsubplotsimshowaxisr?   	add_patchrI   r   inttext
mplcursorsCursorconnecttight_layout)rR   rS   rT   rU   rV   rW   rX   r:   r2   r1   rl   figaxartistsr_   rectrb   wordtext_locrn   r   s                        r   r	   r	      ss   H ;rr?DAq%&UUEAIM5!!A0FDl4(((GCIIeGGENNN *')h A) A) 	%#j!4#5=DIab fl D LL %t$$$'N (	 (	D )'$d<&8@Ficd hn  T""" )NN4(((W  '$& "']SS$|:LSSSS#	 
   T""" NN4(((( 4
+,,11\ 21 5j9I!9LtT^O_`aObefOf9f ghh\ 21 5j9I!9LtT^O_`aObefOf9f ghh$  \ 21 5Z8H8KA8N NOO\ 21 5Z8H8KA8N NOO$
 4
+,,11 % M  "$"%"+   3B  	)!+. ) )'Z(& %)    T""" )NN4((( x 	'++33E;v;vwwwJr!   c                    |j         dd         \  }}	||	k    r
||	z  |z  |fn	|||	z  |z  f}
t          j        |
          \  }}|                    |           |                    d           |rg }d t          t          t          | d                             | d                   D             }| d                                         D ]q\  }}|D ]i}|set          |d         | d         f| d	|d
          d|d         d||         dd|}|
                    |           |r|                    |           jr|r0ddl}|                    |d                              dd            |                    d           |S )a  Visualize a full page with predicted blocks, lines and words

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from doctr.utils.visualization import visualize_page
    >>> from doctr.models import ocr_db_crnn
    >>> model = ocr_db_crnn(pretrained=True)
    >>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
    >>> out = model([[input_page]])
    >>> visualize_kie_page(out[0].pages[0].export(), input_page)
    >>> plt.show()

    Args:
        page: the exported Page of a Document
        image: np array of the page, needs to have the same shape than page['dimensions']
        words_only: whether only words should be displayed
        display_artefacts: whether artefacts should be displayed
        scale: figsize of the largest windows side
        interactive: whether the plot should be interactive
        add_labels: for static plot, adds text labels on top of bounding box
        **kwargs: keyword arguments for the polygon patch

    Returns:
        the matplotlib figure
    Nr   rZ   r\   c                     i | ]\  }}||	S  r   )r   r   ks      r   
<dictcomp>z&visualize_kie_page.<locals>.<dictcomp>F  s    fff85!afffr!   predictionsr   r^   z 
 rd   re   rf   rg   r   r`   r   ro   rq   c                 d    | j                             | j                                                  S rs   rt   ry   s    r   r{   z$visualize_kie_page.<locals>.<lambda>\  r|   r!   rB   r}   )r7   r   r   r   r   ziprQ   r   itemsr?   r   rI   r   r   r   r   )rR   rS   rT   rU   rV   rW   rX   r:   r2   r1   rl   r   r   r   rL   keyrd   
predictionr   r   s                       r   r
   r
     s   H ;rr?DAq%&UUEAIM5!!A0FDl4(((GCIIeGGENNN *')ffs:c$}:M6N6N+O+OQUVcQd'e'efffF=)//11 ) )
U 	) 	)J )'z*& !ggj&9ggT`Iaggg +    T""" )NN4(((	)   x 	'++33E;v;vwwwJr!   boxesc           
         |j         dd         \  }}t          |           }|ddddgfxx         |z  cc<   |ddddgfxx         |z  cc<   |                    t          j                  }|                                D ]=}|\  }}	}
}t          j        |||	f|
|ft          |t                    r|ndd          }>t          j        |           t          j        di | dS )	a  Draw an array of relative straight boxes on an image

    Args:
        boxes: array of relative boxes, of shape (*, 4)
        image: np array, float32 or uint8
        color: color to use for bounding box edges
        **kwargs: keyword arguments from `matplotlib.pyplot.plot`
    Nr   r   r   rj   )r   r      )r   	thicknessr   )r7   r   astyper<   int32tolistcv2	rectangler   r   r   r   plot)r   rS   r   r:   r2   r1   _boxesboxr-   r.   r/   r0   s               r   r   r   b  s    ;rr?DAqe__F
111q!f9
111q!f9]]28$$F}} 
 
!$dD$D$<$jPU>V>V5gUU\gst
 
 
 JuHvr!   )Nr   r   r   TF)TTrD   TT)FTrD   TTrs   )%rJ   copyr   typingr   r   matplotlib.patchesr)   matplotlib.pyplotpyplotr   numpyr<   matplotlib.figurer   common_typesr   r   __all__r   r   strfloatboolr*   r3   r>   r8   r9   Patchr?   listrQ   dictr	   r
   r   r   r!   r   <module>r      s  
              



 $ $ $ $ $ $           $ $ $ $ $ $ 0 0 0 0 0 0 0 0
@
@
@ (1"'. ..38_. :. u$%	.
 . . .  . . . . .h (1"'( (j(38_( :( u$%	(
 ( ( (  ( _( ( ( (V0I%
2038_0 0 ]	0 0 0 023 4eUE.A(B#C    * "y y
sCx.y:y y 	y
 y y y y y y y y~ "H H
sCx.H:H H 	H
 H H H H H H H HV bj  E#sC-<PSW<W mq      r!   