
    j'                         d dl Z d dlZd dlZd dlmZ d dlmZ ddlm	Z	 ddgZ
 G d de	          Z G d	 de          ZdS )
    N)Polygon)	BaseModel   )DetectionPostProcessor_FASTFASTPostProcessorc            	            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 FAST model.

    Args:
        bin_thresh: threshold used to binzarized p_map at inference time
        box_thresh: minimal objectness score to consider a box
        assume_straight_pages: whether the inputs were expected to have horizontal text elements
    皙?T
bin_thresh
box_threshassume_straight_pagesreturnNc                 \    t                                          |||           d| _        d S )N      ?)super__init__unclip_ratio)selfr   r   r   	__class__s       c/var/www/html/Carbon-Document/venv/lib/python3.11/site-packages/doctr/models/detection/fast/base.pyr   zFASTPostProcessor.__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 FASTPostProcessor.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         \  }}g }t          j        |                    t          j                  t          j        t          j                  \  }}|D ]}t	          j        |dddf         	                    d          |dddf         
                    d          z
  d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@|\  }	}
}}|	|z  |
|z  |	|z   |z  |
|z   |z  f\  }}}}|                    |||||g           o|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                     | j        sVt)          |          dk    r(t	          j        t	          j        |          dd          nt	          j        d
|j                  S t)          |          dk    r(t	          j        t	          j        |          dd          nt	          j        d|j                  S )aA  Compute boxes from a bitmap/pred_map: find connected components then filter boxes

        Args:
            pred: Pred map from differentiable linknet 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 6-element list
                containing x, y, w, h, alpha, score for the box
        Nr   r   r   T)r   Fr   g        )r      r   dtype)r   r?   )shaper   findContoursastyper,   uint8RETR_EXTERNALCHAIN_APPROX_SIMPLEanymaxminr   r.   array	box_scorer   r;   squeezeappendvstackr*   clipr-   zerosrA   )r   r<   r=   heightwidthboxescontours_contourxywhr   score_boxxminyminxmaxymaxs                       r   bitmap_to_boxesz!FASTPostProcessor.bitmap_to_boxesT   s   " RaR(02&v}}RX'>'>@QSVSjkk! 	H 	HGvgaaadm''Q'//'!!!Q$-2C2C2C2K2KKaOPP ) S -g66
1a%'X1v1q5zAE1q5>TUXYTY[\S].^%_%_tV4PPtWERRt&&) @**622**2:g+>+>??) 
H!
1a)*UAJQ%RSVWRW[aQa)a&dD$dD$e<==== 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,   ndarrayr;   rb   __classcell__)r   s   @r   r   r      s           &*	        $	 
 
           +

+
 
+
 +
 +
 +
Z8nj8n 
8n 
	8n 8n 8n 8n 8n 8n 8n 8nr   c            	           e Zd ZU dZdZeed<   dZeed<   dZ	de
eeej        f                  deeeef         d	eej        ej        ej        f         fd
ZdS )r   zFAST as described in `"FAST: Faster Arbitrarily-Shaped Text Detector with Minimalist Kernel Representation"
    <https://arxiv.org/pdf/2111.02394.pdf>`_.
       min_size_boxTr   g?targetoutput_shaper   c                 V
   t          d |D                       rt          d          t          d |D                       rt          d          |\  }}}t          |          |||f}t	          j        |t          j                  }t	          j        |t                    }t	          j        |t          j                  }	t          |          D ]P\  }
}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
            }t1          |||          D ]\  }}}|| j        k     r,d||
||d
         |d         d
z   |d         |d         d
z   f<   >t5          |          }|j        d
t	          j        | j        d          z
  z  |j        z  }d |D             }t?          j                     }|!                    |t>          j"        t>          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t5          |          j'        s-d||
||d
         |d         d
z   |d         |d         d
z   f<   tQ          j)        |	|
|f         |                    t          j                  gd           tQ          j)        ||
|f         |                    t          j                  gd           )R|||	fS )a,  Build the target, and it's mask to be used from loss computation.

        Args:
            target: target coming from dataset
            output_shape: shape of the output of the model without batch_size

        Returns:
            the new formatted target, mask and shrunken text kernel
        c              3   n   K   | ]0}|                                 D ]}|j        t          j        k    V  1d S )N)valuesrA   r,   float32.0tgtts      r   	<genexpr>z%_FAST.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 )N   r   r   )rr   r,   rH   rt   s      r   rx   z%_FAST.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   Frl   Nr   r   r   r   c                 ,    g | ]}t          |          S  )tuple)ru   coors     r   
<listcomp>z&_FAST.build_target.<locals>.<listcomp>   s    <<<tuT{{<<<r   r   )*rH   AssertionError
ValueErrorr*   r,   rQ   rE   onesrh   r+   rr   rB   copyndimlinalgnormconcatenaterJ   rI   roundrD   int32stackminimumziprm   r   r1   powershrink_ratior2   r$   r%   r&   r'   r(   r)   rK   reshapeis_validr   fillPoly)r   rn   ro   num_classesr[   rZ   target_shape
seg_targetseg_maskshrunken_kernelr6   rv   	class_idx_tgt	abs_boxespolys
boxes_sizepolyboxbox_sizepolygonr3   subjectpaddingshrunkens                            r   build_targetz_FAST.build_target   s    MMMMMMM 	` !^_____&_____ 	jhiii
 )QF[!Q7!#,bh!G!G!G
!w|4@@@&(h|28&L&L&L!&)) 7	[ 7	[HC#,SZZ\\#:#: 6[ 6[	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i!@8??SUS[C\C\B]_bcccLCN!;dkk"(>S>S=TVYZZZZ1[=6[p 8_44r   N)rc   rd   re   rf   rm   int__annotations__r   rh   r   listdictstrr,   ri   r}   r   r|   r   r   r   r      s           L#"&4&&&LV5T#rz/*+V5 CcM*V5 
rz2:rz1	2	V5 V5 V5 V5 V5 V5r   )r   numpyr,   r$   shapely.geometryr   doctr.models.corer   corer   __all__r   r   r|   r   r   <module>r      s    


         $ $ $ $ $ $ ' ' ' ' ' ' ) ) ) ) ) )'
(wn wn wn wn wn. wn wn wnt_5 _5 _5 _5 _5I _5 _5 _5 _5 _5r   