
    YhD"                     t    d Z ddlZddlZddlZddlmc mZ ddlm	Z	 	 	 	 	 	 	 	 dd	Z
ddZ	 	 	 	 	 	 	 ddZdS )zs
Created by Jaided AI
Released Date: 18/08/2022
Description:
A wrapper for DBNet text detection module for EasyOCR
    N   )DBNet皙?   Fcpuc	                 n   t          | t          j                  rt          | j                  dk    r| }	n| g}	t          fd|	D              \  }
}fd|
D             }
t          j        t          j        |
                    	                    |          }t          j
                    5                      |	                    |                    }                    |||||||d          \  }}|r!                    |||||||d          \  }}n|}ddd           n# 1 swxY w Y   ||fS )a  
    A wrapper for DBNet inference routine.

    Parameters
    ----------
    image : np.ndarray or list of np.ndarray
        OpenCV BGR image array or list of it.
    detector : obj
        DBNet text detection object.
    threshold : float, optional
        Minimum probability for each pixel of heatmap tensor to be considered
        as a valid text pixel. The default is 0.2.
    bbox_min_score : float, optional
        Minimum score for each detected bounding box to be considered as a
        valid text bounding box. The default is 0.2.
    bbox_min_size : int, optional
        Minimum size for each detected bounding box to be considered as a
        valid text bounding box. The default is 3.
    max_candidates : int, optional
        Maximum number of detected bounding boxes to be considered as 
        candidates for valid text bounding boxes. Setting to 0 implies
        no maximum. The default is 0.
    canvas_size : int, optional
        Target detection size. Input image will be resized such that it's 
        shorter side is equal to the closest multiple of 32 to the provided 
        canvas_size. If detection_size is not provided, it will be resized to 
        the closest multiple of 32 each side. If the original size exceeds the 
        min-/max-detection sizes (specified in DBNet_inference.yaml), it will be 
        resized to be within the min-/max-sizes. The default is None.
    poly : boolean, optional
        If true, return the bounding boxes as find polygons, otherwise, return
        as rectagular. The default is False.
    device : str, optional
        Device to use. Options are "cpu" and "cuda". The default is 'cpu'.

    Returns
    -------
    bboxes : list of lists
        List of text bounding boxes in format [left, right, top, bottom].
    polys : list of lists
        List of polygon text bounding boxes. If argument poly is set to false,
        this output will also hold the value of output bboxes
       c                 <    g | ]}                     |          S  )resize_image).0imgcanvas_sizedetectors     f/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/easyocr/detection_db.py
<listcomp>ztest_net.<locals>.<listcomp>J   s*    #b#b#bPSH$9$9#{$K$K#b#b#b    c                 `    g | ]*}t          j                            |          d           +S ))   r   r   )np	transposenormalize_image)r   n_imgr   s     r   r   ztest_net.<locals>.<listcomp>L   s3    [[[5bl833E::IFF[[[r   F)text_thresholdbbox_min_scorebbox_min_sizemax_candidates
as_polygonTN)
isinstancer   ndarraylenshapeziptorch
from_numpyarraytono_grad
image2hmap	hmap2bbox)imager   	thresholdr   r   r   r   polydevice
image_arrsimagesoriginal_shapesimage_tensorhmapbboxes_polyss    `    `          r   test_netr7      s   j %$$ U[)9)9Q)>)>

W
 "#b#b#b#b#bWa#b#b#bcFO[[[[TZ[[[F#BHV$4$45588@@L	  ""<??6#:#:;;&&(+ -6-;,9-;', ' . .	  	)) , / $1:1?0=1?+/ * 1 1HE11 E-              0 5=s   .A.D((D,/D,resnet18Tc                 H   t          dt          j                            dd          |d          }|dvrt	          d          |                    |j        |         d         |            t          j        |          j	        d	k    r8|r5	 t          j
                            |t          j        d
           nP#  Y nLxY wnHt          j                            |j                                      |          |_        |t"          _        |j                                         |S )a  
    A wrapper to initialize DBNet text detection model

    Parameters
    ----------
    trained_model : str
        Path to trained weight to use.
    backbone : str
        Backbone to use. Options are 'resnet18' or 'resnet50'. The default is 'resnet18'.
    device : str, optional
        Device to use. Options are "cpu" and "cuda". The default is 'cpu'.
    quantize : boolean, optional
        If use, apply model quantization method to the model. The default is True.
    cudnn_benchmark : boolen, optional
        DESCRIPTION. The default is False.

    Returns
    -------
    dbnet : obj
        DBNet text detection object.
    Feasyocrr   r   )initialize_modeldynamic_import_relative_pathr.   verbose)r8   resnet50z7Invalid backbone. Options are 'resnet18' or 'resnet50'.modelr   T)dtypeinplace)r   ospathjoin
ValueErrorr;   configsr$   r.   typequantizationquantize_dynamicqint8nnDataParallelr?   r'   cudnn	benchmarkeval)trained_modelbackboner.   quantizecudnn_benchmarkdbnets         r   get_detectorrU   i   s   , U13i1Q1Q!  E ///RSSS	5=27;(* * *|F E)) 	"33EVZ3[[[[		 h++EK88;;FCC)	KLs   ,B9 9B=c	                    t          j        |          j        | j        k    r=t          d                    g d                              | j        |                    t          || |||||||	  	        \  }
}d |D             }|S )a  
    A compatibility wrapper to allow supporting calling this method while 
    providing argument for other detector classes and reformat output accordingly.

    Parameters
    ----------
    detector : obj
        DBNet text detection object.
    image : np.ndarray or list of np.ndarray
        OpenCV BGR image array or list of it.
    canvas_size : int, optional
        Target detection size. Please see docstring under method resize_image()
        for explanation. The default is None.
    poly : boolean, optional
        If true, return the bounding boxes as find polygons, otherwise, return
        as rectagular. The default is False.
    threshold : float, optional
        Minimum probability for each pixel of heatmap tensor to be considered
        as a valid text pixel. The default is 0.2.
    bbox_min_score : float, optional
        Minimum score for each detected bounding box to be considered as a
        valid text bounding box. The default is 0.2.
    bbox_min_size : int, optional
        Minimum size for each detected bounding box to be considered as a
        valid text bounding box. The default is 3.
    max_candidates : int, optional
        Maximum number of detected bounding boxes to be considered as 
        candidates for valid text bounding box. Setting it to 0 implies
        no maximum. The default is 0.
    device : str, optional
        Device to use. Options are "cpu" and "cuda". The default is 'cpu'.
    **kwargs : keyword arguments
        Unused. Added to support calling this method while providing argument 
        for other detector class.

    Returns
    -------
    result : list of lists
        List of text bounding boxes in format [left, right, top, bottom].
     )zCDBNet detector is initialized with {} device, but detection routinezis called with device = {}.z.To use this detector both have to be the same.)r,   r   r   r   r   r-   r.   c                 &    g | ]}d  |D             S )c                     g | ]F}t          j        |                              t           j                                      d           GS ))r   r&   astypeint32reshape)r   boxs     r   r   z*get_textbox.<locals>.<listcomp>.<listcomp>   s>    MMMrx}}##BH--55r;;MMMr   r   )r   r6   s     r   r   zget_textbox.<locals>.<listcomp>   s(    fffRWMMuMMMfffr   )r$   r.   rG   RuntimeErrorrD   formatr7   )r   r+   r   r-   r,   r   r   r   r.   kwargsr5   
polys_listresults                r   get_textboxrd      s    f |F HO33388 % % %   vhov..	0 0 	0 U%)2.<-:-;+6$(&,	 	 	MAz gf[efffFMr   )r   r   r   r   NFr   )r8   r   TF)NFr   r   r   r   r   )__doc__rB   numpyr   r$   torch.backends.cudnnbackendsrM   DBNet.DBNetr   r7   rU   rd   r   r   r   <module>rj      s     
			      $ $ $ $ $ $ $ $ $       !X X X Xt* * * *\ #!$ !!"G G G G G Gr   