
    j=                     r    d dl Z d dlZd dlZd dlmZ ddlmZ dgZ G d de          Z	 G d d          Z
dS )	    N)Polygon   )DetectionPostProcessorDBPostProcessorc            	            e Zd ZdZ	 	 	 ddedededd	f fd
Zdej        dej        fdZ	dej        dej        dej        fdZ
 xZS )r   a  Implements a post processor for DBNet adapted from the implementation of `xuannianz
    <https://github.com/xuannianz/DifferentiableBinarization>`_.

    Args:
        unclip ratio: ratio used to unshrink polygons
        min_size_box: minimal length (pix) to keep a box
        max_candidates: maximum boxes to consider in a single page
        box_thresh: minimal objectness score to consider a box
        bin_thresh: threshold used to binzarized p_map at inference time

    皙?333333?T
box_thresh
bin_threshassume_straight_pagesreturnNc                 \    t                                          |||           d| _        d S )Ng      ?)super__init__unclip_ratio)selfr
   r   r   	__class__s       z/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/doctr/models/detection/differentiable_binarization/base.pyr   zDBPostProcessor.__init__    s0     	Z1FGGG    pointsc                    | j         sot          j        |          }t          j        |          }|d         d         dz   d|d         d         z   z  }d|d         d         |d         d         z   z  dz   }n*t          j        |          }t          j        |d          }|| j        z  |z  }t          j                    }|	                    |t          j
        t          j                   |                    |          }d}t          |          dk    rDd}	t          |          D ])\  }
}t          |          |	k    r|
}t          |          }	*||         g}t          j        |          }t          |          dk     rdS | j         rt          j        |          n:t          j        t          j        t          j        |                    dd          S )	zExpand a polygon (points) by a factor unclip_ratio, and returns a polygon

        Args:
            points: The first parameter.

        Returns:
            a box in absolute coordinates (xmin, ymin, xmax, ymax) or (4, 2) array (quadrangle)
           r   r   T)closedNaxis)r   cv2minAreaRect	boxPointscontourArea	arcLengthr   	pyclipperPyclipperOffsetAddPathJT_ROUNDET_CLOSEDPOLYGONExecutelen	enumeratenpasarrayboundingRectroll)r   r   rectarealengthdistanceoffset_pointsidxmax_size_idxpexpanded_pointss                r   polygon_to_boxzDBPostProcessor.polygon_to_box)   s    ) 		8?6**D]4((FGAJNq471:~6D$q'!*tAwqz12Q6FF?6**D]6$777F$++f4*,,vy193MNNN..**w<<!H$W-- & &aq66H$$C"1vvHs|nG&(j&9&9!##4 )VC_---s'G'GHH"STUUU	
r   predbitmapc           
         |j         dd         \  }}d}g }t          j        |                    t          j                  t          j        t          j                  \  }}|D ]j}	t	          j        |	dddf         	                    d          |	dddf         
                    d          z
  |k               r[| j        r^t          j        |	          \  }
}}}t	          j        |
|g|
||z   g|
|z   ||z   g|
|z   |gg          }|                     ||d          }n|                     ||	d          }|| j        k     r| j        r|                     |          }n'|                     t	          j        |	                    }| j        r||d         |k     s|d         |k     rKn>t          j                            |dddf         |dddf         z
  d	          |k     r| j        r@|\  }
}}}|
|z  ||z  |
|z   |z  ||z   |z  f\  }}}}|                    |||||g           t+          |t          j                  s|j         d
k    rt/          d          |dddfxx         |z  cc<   |dddfxx         |z  cc<   |                    t	          j        |t	          j        d|g          g                     l| j        sVt3          |          dk    r(t	          j        t	          j        |          dd          nt	          j        d|j                  S t3          |          dk    r(t	          j        t	          j        |          dd          nt	          j        d|j                  S )a?  Compute boxes from a bitmap/pred_map: find connected components then filter boxes

        Args:
            pred: Pred map from differentiable binarization output
            bitmap: Bitmap map computed from pred (binarized)
            angle_tol: Comparison tolerance of the angle with the median angle across the page
            ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop

        Returns:
            np tensor boxes for the bitmap, each box is a 5-element list
                containing x, y, w, h, score for the box
        Nr   r   r   T)r   F   r   )   r   zEWhen assume straight pages is false a box is a (4, 2) array (polygon)r   g        )r      r   dtype)r   r?   )shaper   findContoursastyper*   uint8RETR_EXTERNALCHAIN_APPROX_SIMPLEanymaxminr   r,   array	box_scorer
   r9   squeezelinalgnormappend
isinstancendarrayAssertionErrorvstackr(   clipr+   zerosrA   )r   r:   r;   heightwidthmin_size_boxboxescontours_contourxywhr   score_boxxminyminxmaxymaxs                        r   bitmap_to_boxeszDBPostProcessor.bitmap_to_boxesV   s   " RaR(02&v}}RX'>'>@QSVSjkk! '	H '	HGvgaaadm''Q'//'!!!Q$-2C2C2C2K2KKlZ[[ ) S -g66
1a%'X1v1q5zAE1q5>TUXYTY[\S].^%_%_tV4PPtWERRt&&) @**622**2:g+>+>?? ) <47\#9#9T!W|=S=S >TQT
T!QQQ$Z 7bAALPP) H!
1a)*UAJQ%RSVWRW[aQa)a&dD$dD$e<==== "$
33 r
f8L8L()pqqqQQQT


e#


QQQT


f$


RYbhU|.D.D'EFFGGGG) 	n7:5zzA~~272:e,,a33328T]eieoKpKpKpp7:5zzA~~272:e,,a33328TZbfblKmKmKmmr   )r   r	   T)__name__
__module____qualname____doc__floatboolr   r*   rR   r9   rh   __classcell__)r   s   @r   r   r      s        
 
  &*	        $	 
 
           +

+
 
+
 +
 +
 +
ZBnjBn 
Bn 
	Bn Bn Bn Bn Bn Bn Bn Bnr   c                   |   e Zd ZU dZdZdZdZdZdZe	e
d<   e	 dd	ej        d
ej        dej        dej        dedefd            Zdej        dej        dej        deej        ej        ej        f         fdZdeeeej        f                  deeeef         deej        ej        ej        ej        f         fdZdS )_DBNeta-  DBNet as described in `"Real-time Scene Text Detection with Differentiable Binarization"
    <https://arxiv.org/pdf/1911.08947.pdf>`_.

    Args:
        feature extractor: the backbone serving as feature extractor
        fpn_channels: number of channels each extracted feature maps is mapped to
    g?r	   gffffff?r=   Tr   ư>xsysabepsr   c                    t          j        | |d         z
            t          j        ||d         z
            z   }t          j        | |d         z
            t          j        ||d         z
            z   }t          j        |d         |d         z
            t          j        |d         |d         z
            z   }||z
  |z
  dt          j        ||z            z  |z   z  }t          j        |dd          }dt          j        |          z
  }	t          j        |	          }	t          j        ||z  |	z  |z  |z             }
t          j        t          j        ||                    |dk              |
|dk     <   |
S )a  Compute the distance for each point of the map (xs, ys) to the (a, b) segment

        Args:
            xs : map of x coordinates (height, width)
            ys : map of y coordinates (height, width)
            a: first point defining the [ab] segment
            b: second point defining the [ab] segment
            eps: epsilon to avoid division by zero

        Returns:
            The computed distance

        r   r   r   g            ?)r*   squaresqrtrU   
nan_to_numfmin)rs   rt   ru   rv   rw   square_dist_1square_dist_2square_distcosin
square_sinresults              r   compute_distancez_DBNet.compute_distance   sR   * 	"qt),,ryad/C/CC	"qt),,ryad/C/CCi!qt,,ry1!/E/EE},}<RW]]jMjEkEkAknqAqrtS))5)))
]:..
6CkQTWWXXGBGM=$I$IJJ5ST9Uuqyr   polygoncanvasmaskc                    |j         dk    s|j        d         dk    rt          d          t          |          }|j        dt          j        | j        d          z
  z  |j        z  }d |D             }t          j
                    }|                    |t          j        t          j                   t          j        |                    |          d                   }t!          j        ||                    t
          j                  gd           |dddf                                         }	|dddf                                         }
|dddf                                         }|dddf                                         }|
|	z
  dz   }||z
  dz   }|dddf         |	z
  |dddf<   |dddf         |z
  |dddf<   t          j        t          j        d|dz
  |                              d|          ||f          }t          j        t          j        d|dz
  |                              |d          ||f          }t          j        |j        d         ||f|j        	          }t7          |j        d                   D ]U}|dz   |j        d         z  }|                     ||||         ||                   }t          j        ||z  dd          ||<   Vt          j        |d
          }t)          t+          d|	          |j        d         dz
            }t)          t+          d|
          |j        d         dz
            }t)          t+          d|          |j        d         dz
            }t)          t+          d|          |j        d         dz
            }t          j        d|||z
  ||z
  |z   ||	z
  ||
z
  |z   f         z
  |||dz   ||dz   f                   |||dz   ||dz   f<   |||fS )a  Draw a polygon threshold map on a canvas, as described in the DB paper

        Args:
            polygon : array of coord., to draw the boundary of the polygon
            canvas : threshold map to fill with polygons
            mask : mask for training on threshold polygons
        r   r   z1polygon should be a 2 dimensional array of coordsc                 ,    g | ]}t          |          S  tuple.0coors     r   
<listcomp>z*_DBNet.draw_thresh_map.<locals>.<listcomp>   s    33345;;333r   r   ry   N)numr@   r   )ndimrB   AttributeErrorr   r/   r*   powershrink_ratior0   r"   r#   r$   r%   r&   rK   r'   r   fillPolyrD   int32rJ   rI   broadcast_tolinspacereshaperV   rA   ranger   rU   fmax)r   r   r   r   polygon_shaper1   subjectpaddingpadded_polygonrd   rf   re   rg   rX   rW   rs   rt   distance_mapijabsolute_distance
xmin_valid
xmax_valid
ymin_valid
ymax_valids                            r   draw_thresh_mapz_DBNet.draw_thresh_map   s&    <1a 0A 5 5 !TUUU  (( %RXd6G-K-K)KL}Occ337333+--!3Y5OPPP%'Xgooh.G.G.J%K%K 	TN11"(;;<cBBB aaad#''))aaad#''))aaad#''))aaad#''))taq1,11,1Q	u)M)M)M)U)UVWY^)_)_bhjoapqqQ
)O)O)O)W)WX^`a)b)bekmrdstt xq!165 AWWWw}Q'(( 	J 	JAQ'-**A $ 5 5b"gaj'RS* U U g&7(&BAqIILOOvl333 Qv|A':;;
Qv|A':;;
Qv|A':;;
Qv|A':;;
 LN7T!J$5$>>
T@QT^aeTehmTm@mm :
Q.
Z!^0KKLL
 L
zJN*Ja,GGH $$r   targetoutput_shapec                 P   t          d |D                       rt          d          t          d |D                       rt          d          t          |          dk    r9t	          t          |d                                                             j        nt          j	        }|\  }}}t          |          |||f}t          j
        |t          j                  }t          j        |t                    }	t          j
        |t          j	                  }
t          j
        |t          j                  }t          |          D ]I\  }}t          |                                          D ] \  }}|j        d         dk    rd|	||f<   |                                }|j        dk    r|d d d d dfxx         |z  cc<   |d d d d d	fxx         |z  cc<   |}t          j                            |d d d
d d f         |d d dd d f         z
  d          }t          j        |                    d	          |                    d	          fd                                                              t          j                  }n|d d dd
gfxx         |z  cc<   |d d d	dgfxx         |z  cc<   |                                                    t          j                  }t          j        |d d dd	gf         |d d ddgf         |d d d
dgf         |d d d
d	gf         gd	          }t          j        |d d d
f         |d d df         z
  |d d df         |d d d	f         z
            }t9          |||          D ]\  }}}|| j        k     r,d|	|||d	         |d         d	z   |d         |d
         d	z   f<   >t=          |          }|j        d	t          j         | j!        d
          z
  z  |j"        z  }d |D             }tG          j$                    }|%                    |tF          j&        tF          j'                   |(                    |           }t          |          dk    r-d|	|||d	         |d         d	z   |d         |d
         d	z   f<   t          j)        |d                   *                    dd
          }|j        d         d
k    st=          |          j+        s-d|	|||d	         |d         d	z   |d         |d
         d	z   f<   tY          j-        |||f         |                    t          j                  gd           | .                    ||
||f         |||f                   \  }|
||f<   |||f<   "K|
                    |          | j/        | j0        z
  z  | j0        z   }
|                    |          }|	                    t                    }	|
                    |          }
|                    t                    }||	|
|fS )Nc              3   n   K   | ]0}|                                 D ]}|j        t          j        k    V  1d S )N)valuesrA   r*   float32r   tgtts      r   	<genexpr>z&_DBNet.build_target.<locals>.<genexpr>  s@      MM

MM1qw"*$MMMMMMMr   z;the expected dtype of target 'boxes' entry is 'np.float32'.c           	   3      K   | ]R}|                                 D ];}t          j        |d d d df         dk    |d d d df         dk     z            V  <Sd S )Nr>   r   r   )r   r*   rH   r   s      r   r   z&_DBNet.build_target.<locals>.<genexpr>  ss      __3RUR\R\R^R^__QrvqBQBx!|!!!RaR%1566_______r   zIthe 'boxes' entry of the target is expected to take values between 0 & 1.r   r@   Fr=   r   r   r   r   c                 ,    g | ]}t          |          S r   r   r   s     r   r   z'_DBNet.build_target.<locals>.<listcomp>J  s    <<<tuT{{<<<r   ry   )1rH   rS   
ValueErrorr(   nextiterr   rA   r*   r   rV   rE   onesrn   r)   rB   copyr   rN   rO   concatenaterJ   rI   roundrD   r   stackminimumziprY   r   r/   r   r   r0   r"   r#   r$   r%   r&   r'   rK   r   is_validr   r   r   
thresh_max
thresh_min)r   r   r   input_dtypenum_classesra   r`   target_shape
seg_targetseg_maskthresh_targetthresh_maskr4   r   	class_idx_tgt	abs_boxespolys
boxes_sizepolyboxbox_sizer   r1   r   r   shrunkens                              r   build_targetz_DBNet.build_target  s   
 MMMMMMM 	` !^_____&_____ 	jhiii>A&kkAood4q	 0 0 2 23344::SUS]
 )QF[!Q7!#,bh!G!G!G
!w|4@@@$&H\$L$L$L"$(<rx"H"H"H!&)) 9	 9	HC#,SZZ\\#:#: 8 8	4:a=A%%/4HS)^, !IIKK	>Q&&aaaAg&&&!+&&&aaaAg&&&!+&&&%E!#	!!!Q'0BYqqqRSUVUVUVwEW0W^`!a!aJ "	a0@0@)--PQBRBR/SUW X X ^ ^ ` ` g ghjhp q qIIaaa!Qi(((A-(((aaa!Qi(((A-((( ) 1 1 8 8 B BIH%aaa!Qi0%aaa!Qi0%aaa!Qi0%aaa!Qi0	   E "$IaaadOi1o,MyYZYZYZ\]Y]ajklklklnokoapOp!q!qJ+.ui+L+L  'D#x$"333]biQ#a&1*1Dc!fsSTvXYzFY!YZ  &dmmG&|q28D<Mq3Q3Q/QRU\UccH<<t<<<G'799GOOGY-?A[\\\&y99H 8}}))]biQ#a&1*1Dc!fsSTvXYzFY!YZ !x44<<RCCH~a(A--WX5F5F5O-]biQ#a&1*1Dc!fsSTvXYzFY!YZ LCN!;hoobh>W>W=XZ]^^^ X\WkWkmCN;[i=XX XTD-Y7S)^9T9T3;8t &,,[99T_t=^_bfbqq&&{33
??4((%,,[99!((..8]K??r   N)rr   )ri   rj   rk   rl   r   r   r   rY   r   rn   __annotations__staticmethodr*   rR   rm   r   r   r   listdictstrintr   r   r   r   rq   rq      s}          LJJL"&4&&&  JJ : :	
  
   \>@%@% 
@% j	@%
 
rz2:rz1	2@% @% @% @%DY@T#rz/*+Y@ CcM*Y@ 
rz2:rz2:=	>	Y@ Y@ Y@ Y@ Y@ Y@r   rq   )r   numpyr*   r"   shapely.geometryr   corer   __all__r   rq   r   r   r   <module>r      s    


         $ $ $ $ $ $ ) ) ) ) ) )
En En En En En, En En EnPJ@ J@ J@ J@ J@ J@ J@ J@ J@ J@r   