
    y hD"                     r    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y)zs
Created by Jaided AI
Released Date: 18/08/2022
Description:
A wrapper for DBNet text detection module for EasyOCR
    N   )DBNetc	                    t        | t        j                        rt        | j                        dk(  r| }	n| g}	t        |	D 
cg c]  }
|j                  |
|       c}
 \  }}|D cg c]'  }t        j                  |j                  |      d      ) }}t        j                  t        j                  |            j                  |      }t        j                         5  |j                  |j                  |            }|j                  |||||||d      \  }}|r|j                  |||||||d      \  }}n|}ddd       ||fS c c}
w c c}w # 1 sw Y   fS xY w)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
       )   r   r   F)text_thresholdbbox_min_scorebbox_min_sizemax_candidates
as_polygonTN)
isinstancenpndarraylenshapezipresize_image	transposenormalize_imagetorch
from_numpyarraytono_grad
image2hmap	hmap2bbox)imagedetector	thresholdr	   r
   r   canvas_sizepolydevice
image_arrsimgimagesoriginal_shapesn_imgimage_tensorhmapbboxes_polyss                      p/home/developers/rajanand/mypropertyqr-fmb-refixing-v2/venv/lib/python3.12/site-packages/easyocr/detection_db.pytest_netr.      sh   j %$U[[)9Q)>
W
 "Wa#bPSH$9$9#{$K#bcFOTZ[5bll833E:IF[F[##BHHV$4588@L	 ""<??6#:;&&(+ -6-;,9-;', ' .	 )) , / $1:1?0=1?+/ * 1HE1 E-0 5=; $c[0 5=s   E	&,EAEEc                 @   t        dt        j                  j                  dd      |d      }|dvrt	        d      |j                  |j                  |   d   |        t        j                  |      j                  d	k(  r4|rz	 t        j                  j                  |t        j                  d
       nHt        j                  j                  |j                        j!                  |      |_        |t"        _        |j                  j'                          |S #  Y  xY w)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)resnet18resnet50z7Invalid backbone. Options are 'resnet18' or 'resnet50'.modelcpuT)dtypeinplace)r   ospathjoin
ValueErrorr1   configsr   r"   typequantizationquantize_dynamicqint8nnDataParallelr6   r   cudnn	benchmarkeval)trained_modelbackboner"   quantizecudnn_benchmarkdbnets         r-   get_detectorrM   i   s    , U13i1Q!E //RSS	5==27;(*||F  E)""33EVZ3[ hh++EKK8;;FC)	KKLs   0D Dc	                    t        j                  |      j                  | j                  k7  r6t        dj	                  g d      j                  | j                  |            t        || |||||||	      \  }
}|D cg c]Q  }|D cg c]C  }t        j                  |      j                  t        j                        j                  d      E c}S }}}|S c c}w c c}}w )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"   )r   r"   r?   RuntimeErrorr<   formatr.   r   r   astypeint32reshape)r   r   r    r!   r   r	   r
   r   r"   kwargsr+   
polys_listr,   boxresults                  r-   get_textboxrZ      s    f ||F  HOO3388 %  vhoov.	0 	0 U%)2.<-:-;+6$(&,	MAz \ffRWuMrxx}##BHH-55r;MfFfM Nfs   ?	CACCC)皙?r[      r   NFr7   )r4   r7   TF)NFr[   r[   r\   r   r7   )__doc__r:   numpyr   r   torch.backends.cudnnbackendsrE   DBNet.DBNetr   r.   rM   rZ        r-   <module>rd      s_    
   $ $  !Xt*\ #!$ !!"Grc   