
    9i]+                     l   S SK r S SKrS SKJr  S SKJrJr  S SKrS SK	r
S SKrS SKJr  S SKJr  S SKJr  S SKJrJr  S SKJr  S SKJr  S S	KJr  S S
KJrJr  S SKJr  S SK J!r!  SSK"J#r#J$r$J%r%  \!" 5       r&Sr'Sr(Sr)/ SQr*Sr+Sr,\RZ                  " \R\                  \R\                  S9 " S S\5      5       r/g)    N)AnyDict)	Pipelines)OCRDetection)
OutputKeys)InputPipeline)	PIPELINES)	LoadImage)Config)	ModelFileTasks)device_placement)
get_logger   )	cal_width
nms_pythonrboxes_to_polygons         )皙?r   r   r   r   r   g?g333333?)module_namec                      ^  \ rS rSrSrS\4U 4S jjrU 4S jrS\S\	\\
4   4S jrS\	\\
4   S\	\\
4   4S	 jrS
\	\\
4   S\	\\
4   4S jrSrU =r$ )OCRDetectionPipeline"   a  OCR Detection Pipeline.

Example:

```python
>>> from modelscope.pipelines import pipeline

>>> ocr_detection = pipeline('ocr-detection', model='damo/cv_resnet18_ocr-detection-line-level_damo')
>>> result = ocr_detection('https://modelscope.oss-cn-beijing.aliyuncs.com/test/images/ocr_detection.jpg')

    {'polygons': array([[220,  14, 780,  14, 780,  64, 220,  64],
   [196, 369, 604, 370, 604, 425, 196, 425],
   [ 21, 730, 425, 731, 425, 787,  21, 786],
   [421, 731, 782, 731, 782, 789, 421, 789],
   [  0, 121, 109,   0, 147,  35,  26, 159],
   [697, 160, 773, 160, 773, 197, 697, 198],
   [547, 205, 623, 205, 623, 244, 547, 244],
   [548, 161, 623, 161, 623, 199, 547, 199],
   [698, 206, 772, 206, 772, 244, 698, 244]])}
```
note:
model = damo/cv_resnet18_ocr-detection-line-level_damo, for general text line detection, based on SegLink++.
model = damo/cv_resnet18_ocr-detection-word-level_damo, for general text word detection, based on SegLink++.
model = damo/cv_resnet50_ocr-detection-vlpt, for toaltext dataset, based on VLPT_pretrained DBNet.
model = damo/cv_resnet18_ocr-detection-db-line-level_damo, for general text line detection, based on DBNet.

modelc                   > [        U[        5      (       d   S5       e[        T#U ]  " S(SU0UD6  [        R                  SU 35        [        R                  " [        R                  R                  U[        R                  5      5      n[        US5      (       a7  [        UR                  S5      (       a  UR                  R                  U l        OSU l        U R                  S:X  aZ  U R                  R!                  U R"                  5      U l        U R$                  R'                  5         [        R                  S5        g	SS	KnUR*                  S
:  a  UR,                  R.                  nUR,                  R.                  R1                  5         UR2                  R4                  R7                  S[8        S5        UR2                  R4                  R7                  S[:        S5        UR=                  5         [>        R                  " [>        R                  " U R                  [        R@                  5      S5      nURC                  5       U l"        URG                  SS9nSURH                  l%        URM                  US9U l'        U RD                  RQ                  5          [S        U RT                  U RV                  5         URY                  URZ                  / SQSS9U l.        0 U l/        URa                  SURb                  S9   URe                  S/ URg                  S5      URh                  SS9nURj                  Rm                  SU5      nSSK7J8n	J9n
J:n  U	" 5       nURw                  U R\                  SS9n/ / / np[y        U5       GH
  u  nnUS   US   US   nnnUR{                  U[|        5      nUR~                  R                  UR                  US S/5      5      nUR~                  R                  UR                  US S!/5      S	S	2S	S24   5      nUR~                  R                  UR                  US S!/5      S	S	2SS	24   5      nUR                  UU/SS"9nUR                  U5        UR                  U5        UR                  U5        GM     UR                  U R\                  5      SS# nU" UUUU[        UR                  5      S$9u  nnnnU
" UUU5      u  nn UU R^                  S%'   U U R^                  S&'   S	S	S	5        U RN                  RQ                  5        n![        R                  S'U 35        URj                  R                  WR                  5       5      n"U"R                  U!U5        S	S	S	5        S	S	S	5        S	S	S	5        g	! , (       d  f       N= f! , (       d  f       N0= f! , (       d  f       N9= f! , (       d  f       g	= f))zl
use `model` to create a OCR detection pipeline for prediction
Args:
    model: model id on modelscope hub.
zmodel must be a single strr   zloading model from dir 
model_typez	SegLink++DBNetzloading model doner   Nz2.0node_thresholdzConfidence threshold for nodeslink_thresholdzConfidence threshold for linkszcheckpoint-80000T)allow_soft_placement)config)r      r%      input_images)shapename )reuseglobal_stepF)initializerdtype	trainablegCl?r   )SegLinkDetectorcombine_segments_pythondecode_segments_links_python)is_training      axisr&   )anchor_sizescombined_rboxescombined_countszloading model from  )J
isinstancestrsuper__init__loggerinfor   	from_fileospathjoinr   CONFIGURATIONhasattrr   r   todeviceocr_detectoreval
tensorflow__version__compatv1disable_eager_executionappflagsDEFINE_floatTF_NODE_THRESHOLDTF_LINK_THRESHOLDreset_default_graphospTF_CHECKPOINT_FOLDERget_default_graph_graphConfigProtogpu_optionsallow_growthSession_session
as_defaultr   	frameworkdevice_nameplaceholderfloat32r'   outputvariable_scope
AUTO_REUSEget_variableconstant_initializerint64trainExponentialMovingAverage	ocr_utilsr0   r1   r2   build_model	enumeratemultiplyOFFSET_VARIANCEnnsoftmaxreshapeconcatappendr(   listr9   Savervariables_to_restorerestore)$selfr   kwargscfgstf
model_pathr$   r,   variable_averagesr0   r1   r2   detectorall_maps	all_nodes	all_linksall_regimapscls_mapslnk_mapsreg_mapscls_problnk_prob_poslnk_prob_mutlnk_prob
image_sizesegmentsgroup_indicessegment_counts_r:   r;   sessmodel_loader	__class__s$                                      n/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/modelscope/pipelines/cv/ocr_detection_pipeline.pyr@   OCRDetectionPipeline.__init__A   s    %%%C'CC%/u//-eW56UI4K4K LM4!!gdjj,&G&G"jj33DO)DO??g% $

dkk :D""$KK,- $~~&YY\\IILL002FFLL%%&68I&FHFFLL%%&68I&FH""$Y%C%CD"$J ..0DK^^^>F.2F+JJfJ5DM'')%dnnd6F6FG(*

0+ )7 )-D% #%DK**2R]]*C&(oo)2(*(?(?(B"$((&+	 '6 '-
 -/HH,M,M!;-0) vu#2#4#+#7#7 --5 $8 $B 9;Bg9'0':GAt;?7D !E#$(G 19hH'){{8_'MH')uu}} "

8b!W =(?H ,.55== "

8b!W =a!e D,FL+-55== "

8b!W =ae D,FL')yy,1M67 (1 (9H &,,X6%,,X6#NN84# (;( &(XXd.?.?%@1%E
Ea&%%#)-h.C.C)DFFB- <S$m^<E89H$569H$56c Df 113t&9*$FG')xx~~-BBD(F$,,T:> 4u H *) DCf 43u HG *)sW   !W?AV2G>V"V2#AV!7V2?W
VV2!
V/+V22
W 	<W
Wc                 &   > [         TU ]  " U40 UD6$ )a  
Detect text instance in the text image.

Args:
    input (`Image`):
        The pipeline handles three types of images:

        - A string containing an HTTP link pointing to an image
        - A string containing a local path to an image
        - An image loaded in PIL or opencv directly

        The pipeline currently supports single image input.

Return:
    An array of contour polygons of detected N text instances in image,
    every row is [x1, y1, x2, y2, x3, y3, x4, y4, ...].
)r?   __call__)r|   inputr}   r   s      r   r   OCRDetectionPipeline.__call__   s    $ w000    r   returnc                 2   U R                   S:X  a  U R                  U5      nU$ [        R                  " U5      nUR                  u  pEn[
        R                  " [        XE5      [        XE5      S4[
        R                  S9nX7S U2S U2S S 24'   Sn[        R                  " XxU45      n	[        R                  " U	[        R                  5      n	U	[
        R                  " / SQ[
        R                  S9-
  n	SS Kn
U R                  R!                  5          U
R#                  X/5      nU
R#                  [        XE5      [        XE5      /5      nXR$                  S'   XR$                  S'   S S S 5        S	[
        R&                  " U	SS
90nU$ ! , (       d  f       N'= f)Nr    r&   )r.   r%   )gQ^@gR1]@g\(Y@r   	orig_sizeresize_sizeimgr7   )r   preprocessorr   convert_to_ndarrayr(   npzerosmaxre   cv2resizecvtColorCOLOR_RGB2BGRarrayrM   r[   ra   stackrf   expand_dims)r|   r   resultr   hwcimg_padr   img_pad_resizer   r   s               r   
preprocessOCRDetectionPipeline.preprocess   sJ   ??g%&&u-FM ..u5CiiGA!hhA	3q9a8

KG!$BQBAIK ZZ{1KLN \\.#:K:KLN+bhh(

/< <N $'') hh'ABHHc!iQ%;<	+4K(-8M*	 * R^^NCDFM *)s   AF
Fc                    U R                   S:X  a  U R                  U5      nU$ U R                  R                  5          U R                  R                  5          U R
                  US   0nU R                  R                  U R                  US9nUsS S S 5        sS S S 5        $ ! , (       d  f       O= f S S S 5        g ! , (       d  f       g = f)Nr    r   )	feed_dict)r   rK   r[   ra   r`   r'   runrf   )r|   r   outputsr   sess_outputss        r   forwardOCRDetectionPipeline.forward   s    ??g%''.GN'')]]--/!%!2!2E%L AI#'==#4#4y $5 $:L'	 0/ *)/// *))s#   B>7B#	B>#
B1	-B>>
Cinputsc           
         U R                   S:X  a  [        R                  US   0nU$ US   S   nUS   S   nUS:X  d  XCR                  S   :  a  [	        S5      eUS U2S S 24   nUS   u  pVUS   u  px[        U5      n	[        U5      [        U5      -  n
[        U5      [        U5      -  n[        R                  " S[        R                  " U	S S 2S S S	24   U-  US
-
  5      5      U	S S 2S S S	24'   [        R                  " S[        R                  " U	S S 2S
S S	24   U
-  US
-
  5      5      U	S S 2S
S S	24'   [        R                  " U	5      R                  [        R                  5      n	U	R                  5        Vs/ s H  o[        U5      /-   PM     nn[        U5      n[        R                   " U Vs/ s H  oS S PM	     sn5      n[        R                  U0nU$ s  snf s  snf )Nr    det_polygonsr:   r   r;   z"modelscope error: No text detectedr   r   r4   r   r   )r   r   POLYGONSr(   	Exceptionr   floatr   maximumminimumroundastypeint32tolistr   r   r   )r|   r   r   rboxescountorig_horig_wresize_hresize_wpolygonsscale_yscale_xodt_n9dt_nmsdt_polygonss                   r   postprocess OCRDetectionPipeline.postprocess   s   ??g% ))6.+ABFM-.q1F,-a0EzU\\!_4 DEEFUFAI&F $K0NF!'!6H)&1HFmeHo5GFmeHo5G  "zz2::hq#A#v.8&1*E GHQ!V "

2::hq!$Q$w/'96A:F!HHQ1Wxx)00:H 2:1BC1BA)A,'1BEC&F((6#:6abqE6#:;K ));7FM D#:s   >G 7G%)r[   r`   r'   r   rK   rf   )__name__
__module____qualname____firstlineno____doc__r>   r@   r   r   r   r   r   r   r   __static_attributes____classcell__)r   s   @r   r   r   "   s    8h?c h?T1( $sCx. 8
(T#s(^ 
(S#X 
($sCx. T#s(^  r   r   )0mathrD   os.pathrE   rX   typingr   r   r   numpyr   torchmodelscope.metainfor   "modelscope.models.cv.ocr_detectionr   modelscope.outputsr   modelscope.pipelines.baser   r	   modelscope.pipelines.builderr
   modelscope.preprocessorsr   modelscope.utils.configr   modelscope.utils.constantr   r   modelscope.utils.devicer   modelscope.utils.loggerr   rn   r   r   r   rA   RBOX_DIM
OFFSET_DIMWORD_POLYGON_DIMrr   rU   rV   register_moduleocr_detectionr   r<   r   r   <module>r      s     	   
   ) ; ) 5 2 . * 6 4 . @ @	 
 0   	Y%<%<>b8 b>br   