
    kh["                         d dl mZmZmZmZmZmZ d dlmZ d dl	Z
ddlmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZ  e       rd dlZd dlmZ d dlmZmZmZ ndZdZ G d d      Z G d de      Z y)    )ListOptionalUnionDictAnyTuple)ImageN   )PathManagerLABEL_MAP_CATALOGMODEL_CATALOG   )BaseLayoutModel   )	Rectangle	TextBlockLayout)is_effdet_availableis_torch_cuda_available)create_model)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STDtransforms_coco_eval)g
ףp=
?gv/?gCl?)gZd;O?gy&1?g?c                   2    e Zd ZeefdZdededef   fdZ	y)InputTransformc                 |   || _         || _        t        |ddd| j                   | j                        | _        t	        j
                  |D cg c]  }|dz  	 c}      j                  dddd      | _        t	        j
                  |D cg c]  }|dz  	 c}      j                  dddd      | _        y c c}w c c}w )NbilinearTmean)interpolationuse_prefetcher
fill_colorr   std   r
   r   )	r   r"   r   	transformtorchtensorviewmean_tensor
std_tensor)self
image_sizer   r"   xs        b/var/www/teggl/fontify/venv/lib/python3.12/site-packages/layoutparser/models/effdet/layoutmodel.py__init__zInputTransform.__init__,   s     	-$
 !<<$(?QS(?@EEaAqQ,,'=AC'=>CCAq!QO )@'=s   B4	B9imagereturntorch.Tensorc                    |j                  d      }d|j                  i}| j                  ||      \  }}|j                         D ci c]*  \  }}|t	        j
                  |      j                  d      , }}}t	        j
                  |      j                  d      }|j                         j                  | j                        j                  | j                        }||fS c c}}w )NRGBimg_sizer   )convertsizer$   itemsr%   r&   	unsqueezefloatsub_r(   div_r)   )r*   r/   
image_infoinputkeyvals         r-   
preprocesszInputTransform.preprocessB   s    e$ %**-
 NN5*=z@J@P@P@R
4<CCc",,Q//

 
 U#--a0""4#3#3499$//Jj  
s   /C$N)
__name__
__module____qualname__r   r   r.   r	   r   r   r@        r-   r   r   +   s-     # 	P,! !%0D*E !rE   r   c                       e Zd ZdZdgZdZeZdZ	 	 	 	 	 ddedede	e
   d	e	e
   d
edefdZdede	e   de	e
   d	e	e
   fdZded   fdZdddefdZded   fdZy)EfficientDetLayoutModela  Create a EfficientDet-based Layout Detection Model

    Args:
        config_path (:obj:`str`):
            The path to the configuration file.
        model_path (:obj:`str`, None):
            The path to the saved weights of the model.
            If set, overwrite the weights in the configuration file.
            Defaults to `None`.
        label_map (:obj:`dict`, optional):
            The map from the model prediction (ids) to real
            word labels (strings). If the config is from one of the supported
            datasets, Layout Parser will automatically initialize the label_map.
            Defaults to `None`.
        enforce_cpu(:obj:`bool`, optional):
            When set to `True`, it will enforce using cpu even if it is on a CUDA
            available device.
        extra_config (:obj:`dict`, optional):
            Extra configuration passed to the EfficientDet model
            configuration. Currently supported arguments:
                num_classes: specifying the number of classes for the models
                output_confidence_threshold: minmum object prediction confidence to retain

    Examples::
        >>> import layoutparser as lp
        >>> model = lp.EfficientDetLayoutModel("lp://PubLayNet/tf_efficientdet_d0/config")
        >>> model.detect(image)

    effdetefficientdetg      ?Nconfig_path
model_path	label_mapextra_configenforce_cpudevicec                     t               r|d}nd}|| _        ||ni }| j                  ||||       |j                  d| j                        | _        t        | j                  j                        | _	        y )Ncudacpuoutput_confidence_threshold)
r   rO   _initialize_modelget#DEFAULT_OUTPUT_CONFIDENCE_THRESHOLDrS   r   configr+   preprocessor)r*   rJ   rK   rL   rM   rN   rO   s          r-   r.   z EfficientDetLayoutModel.__init__w   sw     #$~F'3'?|R{J	<P+7+;+;)4+S+S,
( +4;;+A+ABrE   c                    | j                  ||      \  }}|j                  d      rg|j                  d      j                  d      dd \  }}|	t        |   }t        |      }t        j                  |      }t        ||dd|      | _	        nT|J d       |d	|v sJ d
       |}t        j                  |      }|rt        |      n|d	   }t        ||dd|      | _	        | j                  j                  | j                         | j                  j                          | j                  j                  | _        ||| _        y i | _        y )Nzlp:///r
   r   predictT)num_classes
bench_task
pretrainedcheckpoint_pathzVWhen the specified model is not layoutparser-based, you need to specify the model_pathr\   z|When the specified model is not layoutparser-based, you need to specify the label_map or add num_classes in the extra_config)config_parser
startswithlstripsplitr   lenr   get_local_pathr   modeltorO   evalrW   rL   )r*   rJ   rK   rL   rM   dataset_name
model_namer\   s           r-   rT   z)EfficientDetLayoutModel._initialize_model   sc    #'"4"4[*"MZ!!'*'2'9'9''B'H'H'MaPQ'R$L* -l;	i.K$33J?J%'$ *DJ &igi& %,)FN NNF %J$33J -6#i.<;VK%'$ *DJ 	

dkk"

jj''&/&;rE   r/   )z
np.ndarrayzImage.Imagec                 ^   | j                  |      }| j                  j                  |      \  }}| j                  |j	                  | j
                        |j                         D ci c]!  \  }}||j	                  | j
                        # c}}      }| j                  |      }|S c c}}w )N)image_loaderrX   r@   rf   rg   rO   r7   gather_output)r*   r/   model_inputsr<   r>   r?   model_outputslayouts           r-   detectzEfficientDetLayoutModel.detect   s    !!%(#'#4#4#?#?#F j

OODKK(6@6F6F6HI(#sS#&&%%I

 ##M2	 Js   (&B)ro   r1   r0   c                    |j                         j                         }t               }t        |      D ]  \  }}|d d dfxx   |d d df   z  cc<   |d d dfxx   |d d df   z  cc<   |D ]  }t	        |d         }t        |d         }|dd j                         \  }}	}
}|| j                  k  r |j                  t        t        ||	|
|z   ||	z         ||| j                  j                  ||                     |S )Nr   r   r   r
         )blockscoreidtype)rR   detachr   	enumerater9   inttolistrS   appendr   r   rL   rU   )r*   ro   box_predictionsindexsampledetrv   pred_catr,   ywhs               r-   rm   z%EfficientDetLayoutModel.gather_output   s   %))+224 (&}5 	ME61a4LF1a4L(L1a4LF1a4L(L c!fs1v; 1X__.
1a D<<<&&'1a!eQU;# !^^//(C			0 rE   c                 |    t        |t        j                        r!|dd d df   }t        j                  |d      }|S )N.r3   )mode)
isinstancenpndarrayr	   	fromarray)r*   r/   s     r-   rl   z$EfficientDetLayoutModel.image_loader   s;     eRZZ( #tt)$EOOE6ErE   )NNNFN)rA   rB   rC   __doc__DEPENDENCIESDETECTOR_NAMEr   rV   strr   r   boolr.   rT   r   rq   r   rm   rl   rD   rE   r-   rG   rG   R   s    < :L"M!M*.'
 $('+!CC C D>	C
 tnC C C66D6D SM6D D>	6D
 tn6DpE"=> > f >	%(C"D 	rE   rG   )!typingr   r   r   r   r   r   PILr	   numpyr   catalogr   r   r   base_layoutmodelr   elementsr   r   r   
file_utilsr   r   r%   rH   r   effdet.data.transformsr   r   r   r   rG   rD   rE   r-   <module>r      sb    ; :   B B . 4 4 F#  20
$! $!Nno nrE   