phucsd commited on
Commit
0e3f2cf
·
verified ·
1 Parent(s): 0e5f36b

Upload folder using huggingface_hub (part 4)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +44 -0
  2. ocr_webapp/PaddleOCR/deploy/Jetson/images/00057937.jpg +3 -0
  3. ocr_webapp/PaddleOCR/deploy/Jetson/images/det_res_french_0.jpg +3 -0
  4. ocr_webapp/PaddleOCR/deploy/Jetson/readme.md +84 -0
  5. ocr_webapp/PaddleOCR/deploy/Jetson/readme_ch.md +86 -0
  6. ocr_webapp/PaddleOCR/deploy/README.md +31 -0
  7. ocr_webapp/PaddleOCR/deploy/README_ch.md +31 -0
  8. ocr_webapp/PaddleOCR/deploy/fastdeploy/sophgo/README.md +102 -0
  9. ocr_webapp/PaddleOCR/deploy/fastdeploy/sophgo/python/README.md +52 -0
  10. ocr_webapp/PaddleOCR/deploy/fastdeploy/web/README.md +33 -0
  11. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/__init__.py +13 -0
  12. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/config.json +16 -0
  13. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/module.py +145 -0
  14. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/params.py +38 -0
  15. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/__init__.py +13 -0
  16. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/config.json +16 -0
  17. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/module.py +147 -0
  18. ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/params.py +40 -0
  19. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/__init__.py +13 -0
  20. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/config.json +15 -0
  21. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/module.py +151 -0
  22. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/params.py +37 -0
  23. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/__init__.py +13 -0
  24. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/config.json +15 -0
  25. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/module.py +148 -0
  26. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/params.py +48 -0
  27. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/__init__.py +13 -0
  28. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/config.json +15 -0
  29. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/module.py +151 -0
  30. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/params.py +41 -0
  31. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/__init__.py +13 -0
  32. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/config.json +16 -0
  33. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/module.py +156 -0
  34. ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/params.py +68 -0
  35. ocr_webapp/PaddleOCR/deploy/hubserving/readme.md +250 -0
  36. ocr_webapp/PaddleOCR/deploy/hubserving/readme_en.md +249 -0
  37. ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/__init__.py +13 -0
  38. ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/config.json +16 -0
  39. ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/module.py +143 -0
  40. ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/params.py +32 -0
  41. ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/__init__.py +13 -0
  42. ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/config.json +16 -0
  43. ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/module.py +149 -0
  44. ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/params.py +33 -0
  45. ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/__init__.py +13 -0
  46. ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/config.json +16 -0
  47. ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/module.py +143 -0
  48. ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/params.py +30 -0
  49. ocr_webapp/PaddleOCR/deploy/ios_demo/.gitignore +21 -0
  50. ocr_webapp/PaddleOCR/deploy/ios_demo/NOTICE +25 -0
.gitattributes CHANGED
@@ -49,3 +49,47 @@ ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/cmake_step3.png filter=lfs diff=
49
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/cmake_step4.png filter=lfs diff=lfs merge=lfs -text
50
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/result.jpg filter=lfs diff=lfs merge=lfs -text
51
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/vs_step1.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/cmake_step4.png filter=lfs diff=lfs merge=lfs -text
50
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/result.jpg filter=lfs diff=lfs merge=lfs -text
51
  ocr_webapp/PaddleOCR/deploy/cpp_infer/docs/imgs/vs_step1.png filter=lfs diff=lfs merge=lfs -text
52
+ ocr_webapp/PaddleOCR/deploy/ios_demo/PaddleOCRDemo/Resources/SampleImages/general_ocr_002.jpg filter=lfs diff=lfs merge=lfs -text
53
+ ocr_webapp/PaddleOCR/deploy/ios_demo/PaddleOCRDemoTests/Fixtures/ios_ocr_validation_reference.jpg filter=lfs diff=lfs merge=lfs -text
54
+ ocr_webapp/PaddleOCR/deploy/Jetson/images/00057937.jpg filter=lfs diff=lfs merge=lfs -text
55
+ ocr_webapp/PaddleOCR/deploy/Jetson/images/det_res_french_0.jpg filter=lfs diff=lfs merge=lfs -text
56
+ ocr_webapp/PaddleOCR/deploy/paddle2onnx/images/lite_demo_onnx.png filter=lfs diff=lfs merge=lfs -text
57
+ ocr_webapp/PaddleOCR/deploy/paddle2onnx/images/lite_demo_paddle.png filter=lfs diff=lfs merge=lfs -text
58
+ ocr_webapp/PaddleOCR/deploy/paddlecloud/images/architecture.jpeg filter=lfs diff=lfs merge=lfs -text
59
+ ocr_webapp/PaddleOCR/deploy/paddlecloud/images/paddlecloud.png filter=lfs diff=lfs merge=lfs -text
60
+ ocr_webapp/PaddleOCR/deploy/paddlejs/paddlejs_demo.gif filter=lfs diff=lfs merge=lfs -text
61
+ ocr_webapp/PaddleOCR/deploy/pdserving/imgs/demo.png filter=lfs diff=lfs merge=lfs -text
62
+ ocr_webapp/PaddleOCR/deploy/pdserving/imgs/pipeline_result.png filter=lfs diff=lfs merge=lfs -text
63
+ ocr_webapp/PaddleOCR/deploy/pdserving/imgs/results.png filter=lfs diff=lfs merge=lfs -text
64
+ ocr_webapp/PaddleOCR/deploy/pdserving/imgs/start_server.png filter=lfs diff=lfs merge=lfs -text
65
+ ocr_webapp/PaddleOCR/deploy/ppocr-android/ppocr-sdk/src/androidTest/res/raw/android_ocr_benchmark_reference.png filter=lfs diff=lfs merge=lfs -text
66
+ ocr_webapp/PaddleOCR/doc/banner.png filter=lfs diff=lfs merge=lfs -text
67
+ ocr_webapp/PaddleOCR/doc/datasets/ArT.jpg filter=lfs diff=lfs merge=lfs -text
68
+ ocr_webapp/PaddleOCR/doc/datasets/captcha_demo.png filter=lfs diff=lfs merge=lfs -text
69
+ ocr_webapp/PaddleOCR/doc/datasets/ccpd_demo.png filter=lfs diff=lfs merge=lfs -text
70
+ ocr_webapp/PaddleOCR/doc/datasets/CDLA_demo/val_0633.jpg filter=lfs diff=lfs merge=lfs -text
71
+ ocr_webapp/PaddleOCR/doc/datasets/CDLA_demo/val_0941.jpg filter=lfs diff=lfs merge=lfs -text
72
+ ocr_webapp/PaddleOCR/doc/datasets/ch_street_rec_1.png filter=lfs diff=lfs merge=lfs -text
73
+ ocr_webapp/PaddleOCR/doc/datasets/ch_street_rec_2.png filter=lfs diff=lfs merge=lfs -text
74
+ ocr_webapp/PaddleOCR/doc/datasets/doc.jpg filter=lfs diff=lfs merge=lfs -text
75
+ ocr_webapp/PaddleOCR/doc/datasets/funsd_demo/gt_train_00040534.jpg filter=lfs diff=lfs merge=lfs -text
76
+ ocr_webapp/PaddleOCR/doc/datasets/funsd_demo/gt_train_00070353.jpg filter=lfs diff=lfs merge=lfs -text
77
+ ocr_webapp/PaddleOCR/doc/datasets/icdar_rec.png filter=lfs diff=lfs merge=lfs -text
78
+ ocr_webapp/PaddleOCR/doc/datasets/labelme.jpg filter=lfs diff=lfs merge=lfs -text
79
+ ocr_webapp/PaddleOCR/doc/datasets/LSVT_1.jpg filter=lfs diff=lfs merge=lfs -text
80
+ ocr_webapp/PaddleOCR/doc/datasets/publaynet_demo/gt_PMC3724501_00006.jpg filter=lfs diff=lfs merge=lfs -text
81
+ ocr_webapp/PaddleOCR/doc/datasets/publaynet_demo/gt_PMC5086060_00002.jpg filter=lfs diff=lfs merge=lfs -text
82
+ ocr_webapp/PaddleOCR/doc/datasets/roLabelImg.png filter=lfs diff=lfs merge=lfs -text
83
+ ocr_webapp/PaddleOCR/doc/datasets/table_tal_demo/1.jpg filter=lfs diff=lfs merge=lfs -text
84
+ ocr_webapp/PaddleOCR/doc/datasets/table_tal_demo/2.jpg filter=lfs diff=lfs merge=lfs -text
85
+ ocr_webapp/PaddleOCR/doc/datasets/tablebank_demo/004.png filter=lfs diff=lfs merge=lfs -text
86
+ ocr_webapp/PaddleOCR/doc/datasets/tablebank_demo/005.png filter=lfs diff=lfs merge=lfs -text
87
+ ocr_webapp/PaddleOCR/doc/datasets/VoTT.jpg filter=lfs diff=lfs merge=lfs -text
88
+ ocr_webapp/PaddleOCR/doc/datasets/wildreceipt_demo/1bbe854b8817dedb8585e0732089fd1f752d2cec.jpeg filter=lfs diff=lfs merge=lfs -text
89
+ ocr_webapp/PaddleOCR/doc/datasets/wildreceipt_demo/2769.jpeg filter=lfs diff=lfs merge=lfs -text
90
+ ocr_webapp/PaddleOCR/doc/datasets/xfund_demo/gt_zh_train_0.jpg filter=lfs diff=lfs merge=lfs -text
91
+ ocr_webapp/PaddleOCR/doc/datasets/xfund_demo/gt_zh_train_1.jpg filter=lfs diff=lfs merge=lfs -text
92
+ ocr_webapp/PaddleOCR/doc/demo/error.png filter=lfs diff=lfs merge=lfs -text
93
+ ocr_webapp/PaddleOCR/doc/demo/proxy.png filter=lfs diff=lfs merge=lfs -text
94
+ ocr_webapp/PaddleOCR/doc/deployment.png filter=lfs diff=lfs merge=lfs -text
95
+ ocr_webapp/PaddleOCR/doc/deployment_en.png filter=lfs diff=lfs merge=lfs -text
ocr_webapp/PaddleOCR/deploy/Jetson/images/00057937.jpg ADDED

Git LFS Details

  • SHA256: c6132df199f3a548df8cccf512cbeaeb8533a2610798627b19bb2cc2a1ffca9f
  • Pointer size: 131 Bytes
  • Size of remote file: 293 kB
ocr_webapp/PaddleOCR/deploy/Jetson/images/det_res_french_0.jpg ADDED

Git LFS Details

  • SHA256: 777690a87047fcf90f0bd5c520853fe6d75deb4bd0bbb68d6a36ceb2d33de875
  • Pointer size: 131 Bytes
  • Size of remote file: 223 kB
ocr_webapp/PaddleOCR/deploy/Jetson/readme.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ English | [简体中文](readme_ch.md)
2
+
3
+ # Jetson Deployment for PaddleOCR
4
+
5
+ This section introduces the deployment of PaddleOCR on Jetson NX, TX2, nano, AGX and other series of hardware.
6
+
7
+
8
+ ## 1. Prepare Environment
9
+
10
+ You need to prepare a Jetson development hardware. If you need TensorRT, you need to prepare the TensorRT environment. It is recommended to use TensorRT version 7.1.3;
11
+
12
+ 1. Install PaddlePaddle in Jetson
13
+
14
+ The PaddlePaddle download [link](https://www.paddlepaddle.org.cn/inference/user_guides/download_lib.html#python)
15
+ Please select the appropriate installation package for your Jetpack version, cuda version, and trt version. Here, we download paddlepaddle_gpu-2.3.0rc0-cp36-cp36m-linux_aarch64.whl.
16
+
17
+ Install PaddlePaddle:
18
+ ```shell
19
+ pip3 install -U paddlepaddle_gpu-2.3.0rc0-cp36-cp36m-linux_aarch64.whl
20
+ ```
21
+
22
+
23
+ 2. Download PaddleOCR code and install dependencies
24
+
25
+ Clone the PaddleOCR code:
26
+ ```
27
+ git clone https://github.com/PaddlePaddle/PaddleOCR
28
+ ```
29
+
30
+ and install dependencies:
31
+ ```
32
+ cd PaddleOCR
33
+ pip3 install -r requirements.txt
34
+ ```
35
+
36
+ *Note: Jetson hardware CPU is poor, dependency installation is slow, please wait patiently*
37
+
38
+ ## 2. Perform prediction
39
+
40
+ Obtain the PPOCR model from the [document](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/doc/doc_en/ppocr_introduction_en.md#6-model-zoo) model library. The following takes the PP-OCRv3 model as an example to introduce the use of the PPOCR model on Jetson:
41
+
42
+ Download and unzip the PP-OCRv3 models.
43
+ ```
44
+ wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar
45
+ wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar
46
+ tar xf ch_PP-OCRv3_det_infer.tar
47
+ tar xf ch_PP-OCRv3_rec_infer.tar
48
+ ```
49
+
50
+ The text detection inference:
51
+ ```
52
+ cd PaddleOCR
53
+ python3 tools/infer/predict_det.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --image_dir=./doc/imgs/french_0.jpg --use_gpu=True
54
+ ```
55
+
56
+ After executing the command, the predicted information will be printed out in the terminal, and the visualization results will be saved in the `./inference_results/` directory.
57
+ ![](./images/det_res_french_0.jpg)
58
+
59
+
60
+ The text recognition inference:
61
+ ```
62
+ python3 tools/infer/predict_det.py --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs_words/en/word_2.png --use_gpu=True --rec_image_shape="3,48,320"
63
+ ```
64
+
65
+ After executing the command, the predicted information will be printed on the terminal, and the output is as follows:
66
+ ```
67
+ [2022/04/28 15:41:45] root INFO: Predicts of ./doc/imgs_words/en/word_2.png:('yourself', 0.98084533)
68
+ ```
69
+
70
+ The text detection and text recognition inference:
71
+
72
+ ```
73
+ python3 tools/infer/predict_system.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs/00057937.jpg --use_gpu=True --rec_image_shape="3,48,320"
74
+ ```
75
+
76
+ After executing the command, the predicted information will be printed out in the terminal, and the visualization results will be saved in the `./inference_results/` directory.
77
+ ![](./images/00057937.jpg)
78
+
79
+ To enable TRT prediction, you only need to set `--use_tensorrt=True` on the basis of the above command:
80
+ ```
81
+ python3 tools/infer/predict_system.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs/ --rec_image_shape="3,48,320" --use_gpu=True --use_tensorrt=True
82
+ ```
83
+
84
+ For more ppocr model predictions, please refer to[document](../../doc/doc_en/models_list_en.md)
ocr_webapp/PaddleOCR/deploy/Jetson/readme_ch.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](readme.md) | 简体中文
2
+
3
+ # Jetson部署PaddleOCR模型
4
+
5
+ 本节介绍PaddleOCR在Jetson NX、TX2、nano、AGX等系列硬件的部署。
6
+
7
+
8
+ ## 1. 环境准备
9
+
10
+ 需要准备一台Jetson开发板,如果需要TensorRT预测,需准备好TensorRT环境,建议使用7.1.3版本的TensorRT;
11
+
12
+ 1. Jetson安装PaddlePaddle
13
+
14
+ PaddlePaddle下载[链接](https://www.paddlepaddle.org.cn/inference/user_guides/download_lib.html#python)
15
+ 请选择适合的您Jetpack版本、cuda版本、trt版本的安装包。
16
+
17
+ 安装命令:
18
+ ```shell
19
+ # 安装paddle,以paddlepaddle_gpu-2.3.0rc0-cp36-cp36m-linux_aarch64.whl 为例
20
+ pip3 install -U paddlepaddle_gpu-2.3.0rc0-cp36-cp36m-linux_aarch64.whl
21
+ ```
22
+
23
+
24
+ 2. 下载PaddleOCR代码并安装依赖
25
+
26
+ 首先 clone PaddleOCR 代码:
27
+ ```
28
+ git clone https://github.com/PaddlePaddle/PaddleOCR
29
+ ```
30
+
31
+ 然后,安装依赖:
32
+ ```
33
+ cd PaddleOCR
34
+ pip3 install -r requirements.txt
35
+ ```
36
+
37
+ *注:jetson硬件CPU较差,依赖安装较慢,请耐心等待*
38
+
39
+
40
+ ## 2. 执行预测
41
+
42
+ 从[文档](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/doc/doc_ch/ppocr_introduction.md#6-%E6%A8%A1%E5%9E%8B%E5%BA%93) 模型库中获取PPOCR模型,下面以PP-OCRv3模型为例,介绍在PPOCR模型在jetson上的使用方式:
43
+
44
+ 下载并解压PP-OCRv3模型
45
+ ```
46
+ wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar
47
+ wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar
48
+ tar xf ch_PP-OCRv3_det_infer.tar
49
+ tar xf ch_PP-OCRv3_rec_infer.tar
50
+ ```
51
+
52
+ 执行文本检测预测:
53
+ ```
54
+ cd PaddleOCR
55
+ python3 tools/infer/predict_det.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --image_dir=./doc/imgs/french_0.jpg --use_gpu=True
56
+ ```
57
+
58
+ 执行命令后在终端会打印出预测的信息,并在 `./inference_results/` 下保存可视化结果。
59
+ ![](./images/det_res_french_0.jpg)
60
+
61
+
62
+ 执行文本识别预测:
63
+ ```
64
+ python3 tools/infer/predict_det.py --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs_words/en/word_2.png --use_gpu=True --rec_image_shape="3,48,320"
65
+ ```
66
+
67
+ 执行命令后在终端会打印出预测的信息,输出如下:
68
+ ```
69
+ [2022/04/28 15:41:45] root INFO: Predicts of ./doc/imgs_words/en/word_2.png:('yourself', 0.98084533)
70
+ ```
71
+
72
+ 执行文本检测+文本识别串联预测:
73
+
74
+ ```
75
+ python3 tools/infer/predict_system.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs/ --use_gpu=True --rec_image_shape="3,48,320"
76
+ ```
77
+
78
+ 执行命令后在终端会打印出预测的信息,并在 `./inference_results/` 下保存可视化结果。
79
+ ![](./images/00057937.jpg)
80
+
81
+ 开启TRT预测只需要在以上命令基础上设置`--use_tensorrt=True`即可:
82
+ ```
83
+ python3 tools/infer/predict_system.py --det_model_dir=./inference/ch_PP-OCRv2_det_infer/ --rec_model_dir=./inference/ch_PP-OCRv2_rec_infer/ --image_dir=./doc/imgs/00057937.jpg --use_gpu=True --use_tensorrt=True --rec_image_shape="3,48,320"
84
+ ```
85
+
86
+ 更多ppocr模型预测请参考[文档](../../doc/doc_ch/models_list.md)
ocr_webapp/PaddleOCR/deploy/README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ English | [简体中文](README_ch.md)
2
+
3
+ # PP-OCR Deployment
4
+
5
+ - [Paddle Deployment Introduction](#1)
6
+ - [PP-OCR Deployment](#2)
7
+
8
+ <a name="1"></a>
9
+ ## Paddle Deployment Introduction
10
+
11
+ Paddle provides a variety of deployment schemes to meet the deployment requirements of different scenarios. Please choose according to the actual situation:
12
+
13
+ <div align="center">
14
+ <img src="../doc/deployment_en.png" width="800">
15
+ </div>
16
+
17
+
18
+ <a name="2"></a>
19
+ ## PP-OCR Deployment
20
+
21
+ PP-OCR has supported muti deployment schemes. Click the link to get the specific tutorial.
22
+
23
+ - [Python Inference](../doc/doc_en/inference_ppocr_en.md)
24
+ - [C++ Inference](./cpp_infer/readme.md)
25
+ - [Serving (Python/C++)](./pdserving/README.md)
26
+ - [Paddle-Lite (ARM CPU/OpenCL ARM GPU)](./lite/readme.md)
27
+ - [Paddle.js](./paddlejs/README.md)
28
+ - [Jetson Inference](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/deploy/Jetson/readme.md)
29
+ - [Paddle2ONNX](./paddle2onnx/readme.md)
30
+
31
+ If you need the deployment tutorial of academic algorithm models other than PP-OCR, please directly enter the main page of corresponding algorithms, [entrance](../doc/doc_en/algorithm_overview_en.md)。
ocr_webapp/PaddleOCR/deploy/README_ch.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](README.md) | 简体中文
2
+
3
+ # PP-OCR 模型推理部署
4
+
5
+ - [Paddle 推理部署方式简介](#1)
6
+ - [PP-OCR 推理部署](#2)
7
+
8
+ <a name="1"></a>
9
+ ## Paddle 推理部署方式简介
10
+
11
+ 飞桨提供多种部署方案,以满足不同场景的部署需求,请根据实际情况进行选择:
12
+
13
+ <div align="center">
14
+ <img src="../doc/deployment.png" width="800">
15
+ </div>
16
+
17
+
18
+ <a name="2"></a>
19
+ ## PP-OCR 推理部署
20
+
21
+ PP-OCR模型已打通多种场景部署方案,点击链接获取具体的使用教程。
22
+
23
+ - [Python 推理](../doc/doc_ch/inference_ppocr.md)
24
+ - [C++ 推理](./cpp_infer/readme_ch.md)
25
+ - [Serving 服务化部署(Python/C++)](./pdserving/README_CN.md)
26
+ - [Paddle-Lite 端侧部署(ARM CPU/OpenCL ARM GPU)](./lite/readme_ch.md)
27
+ - [Paddle.js 部署](./paddlejs/README_ch.md)
28
+ - [Jetson 推理](https://github.com/PaddlePaddle/PaddleOCR/blob/dygraph/deploy/Jetson/readme_ch.md)
29
+ - [Paddle2ONNX 推理](./paddle2onnx/readme_ch.md)
30
+
31
+ 需要PP-OCR以外的学术算法模型的推理部署,请直接进入相应算法主页面,[入口](../doc/doc_ch/algorithm_overview.md)。
ocr_webapp/PaddleOCR/deploy/fastdeploy/sophgo/README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](README.md) | 简体中文
2
+
3
+ # PaddleOCR 模型在SOPHGO上部署方案-FastDeploy
4
+
5
+ ## 1. 说明
6
+ PaddleOCR支持通过FastDeploy在SOPHGO上部署相关模型.
7
+
8
+ ## 2.支持模型列表
9
+
10
+ 下表中的模型下载链接由PaddleOCR模型库提供, 详见[PP-OCR系列模型列表](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.6/doc/doc_ch/models_list.md)
11
+
12
+ | PaddleOCR版本 | 文本框检测 | 方向分类模型 | 文字识别 |字典文件| 说明 |
13
+ |:----|:----|:----|:----|:----|:--------|
14
+ | ch_PP-OCRv3[推荐] |[ch_PP-OCRv3_det](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar) | [ch_ppocr_mobile_v2.0_cls](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) | [ch_PP-OCRv3_rec](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar) | [ppocr_keys_v1.txt](https://bj.bcebos.com/paddlehub/fastdeploy/ppocr_keys_v1.txt) | OCRv3系列原始超轻量模型,支持中英文、多语种文本检测 |
15
+ | en_PP-OCRv3[推荐] |[en_PP-OCRv3_det](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_det_infer.tar) | [ch_ppocr_mobile_v2.0_cls](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) | [en_PP-OCRv3_rec](https://paddleocr.bj.bcebos.com/PP-OCRv3/english/en_PP-OCRv3_rec_infer.tar) | [en_dict.txt](https://bj.bcebos.com/paddlehub/fastdeploy/en_dict.txt) | OCRv3系列原始超轻量模型,支持英文与数字识别,除检测模型和识别模型的训练数据与中文模型不同以外,无其他区别 |
16
+ | ch_PP-OCRv2 |[ch_PP-OCRv2_det](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_det_infer.tar) | [ch_ppocr_mobile_v2.0_cls](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) | [ch_PP-OCRv2_rec](https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_rec_infer.tar) | [ppocr_keys_v1.txt](https://bj.bcebos.com/paddlehub/fastdeploy/ppocr_keys_v1.txt) | OCRv2系列原始超轻量模型,支持中英文、多语种文本检测 |
17
+ | ch_PP-OCRv2_mobile |[ch_ppocr_mobile_v2.0_det](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_det_infer.tar) | [ch_ppocr_mobile_v2.0_cls](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) | [ch_ppocr_mobile_v2.0_rec](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_rec_infer.tar) | [ppocr_keys_v1.txt](https://bj.bcebos.com/paddlehub/fastdeploy/ppocr_keys_v1.txt) | OCRv2系列原始超轻量模型,支持中英文、多语种文本检测,比PPOCRv2更加轻量 |
18
+ | ch_PP-OCRv2_server |[ch_ppocr_server_v2.0_det](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_det_infer.tar) | [ch_ppocr_mobile_v2.0_cls](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar) | [ch_ppocr_server_v2.0_rec](https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_rec_infer.tar) |[ppocr_keys_v1.txt](https://bj.bcebos.com/paddlehub/fastdeploy/ppocr_keys_v1.txt) | OCRv2服务器系列模型, 支持中英文、多语种文本检测,比超轻量模型更大,但效果更好|
19
+
20
+ ## 3. 准备PP-OCR推理模型以及转换模型
21
+
22
+ PP-OCRv3包括文本检测模型(ch_PP-OCRv3_det)、方向分类模型(ch_ppocr_mobile_v2.0_cls)、文字识别模型(ch_PP-OCRv3_rec)
23
+ SOPHGO-TPU部署模型前需要将以上Paddle模型转换成bmodel模型,我们以ch_PP-OCRv3_det模型为例,具体步骤如下:
24
+ - 下载Paddle模型[ch_PP-OCRv3_det](https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar)
25
+ - Pddle模型转换为ONNX模型,请参考[Paddle2ONNX](https://github.com/PaddlePaddle/Paddle2ONNX)
26
+ - ONNX模型转换bmodel模型的过程,请参考[TPU-MLIR](https://github.com/sophgo/tpu-mlir)
27
+ 下面我们提供一个example, 供用户参考,完成模型的转换.
28
+
29
+ ### 3.1 下载ch_PP-OCRv3_det模型,并转换为ONNX模型
30
+ ```shell
31
+ wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar
32
+ tar xvf ch_PP-OCRv3_det_infer.tar
33
+
34
+ # 修改ch_PP-OCRv3_det模型的输入shape,由动态输入变成固定输入
35
+ python paddle_infer_shape.py --model_dir ch_PP-OCRv3_det_infer \
36
+ --model_filename inference.pdmodel \
37
+ --params_filename inference.pdiparams \
38
+ --save_dir ch_PP-OCRv3_det_infer_fix \
39
+ --input_shape_dict="{'x':[1,3,960,608]}"
40
+
41
+ # 请用户自行安装最新发布版本的paddle2onnx, 转换模型到ONNX格式的模型
42
+ paddle2onnx --model_dir ch_PP-OCRv3_det_infer_fix \
43
+ --model_filename inference.pdmodel \
44
+ --params_filename inference.pdiparams \
45
+ --save_file ch_PP-OCRv3_det_infer_fix.onnx \
46
+ --enable_dev_version True
47
+ ```
48
+
49
+ ### 3.2 导出bmodel模型
50
+
51
+ 以转换BM1684x的bmodel模型为例子,我们需要下载[TPU-MLIR](https://github.com/sophgo/tpu-mlir)工程,安装过程具体参见[TPU-MLIR文档](https://github.com/sophgo/tpu-mlir/blob/master/README.md)。
52
+ #### 3.2.1 安装
53
+ ``` shell
54
+ docker pull sophgo/tpuc_dev:latest
55
+
56
+ # myname1234是一个示例,也可以设置其他名字
57
+ docker run --privileged --name myname1234 -v $PWD:/workspace -it sophgo/tpuc_dev:latest
58
+
59
+ source ./envsetup.sh
60
+ ./build.sh
61
+ ```
62
+
63
+ #### 3.2.2 ONNX模型转换为bmodel模型
64
+ ``` shell
65
+ mkdir ch_PP-OCRv3_det && cd ch_PP-OCRv3_det
66
+
67
+ #在该文件中放入测试图片,同时将上一步转换的ch_PP-OCRv3_det_infer_fix.onnx放入该文件夹中
68
+ cp -rf ${REGRESSION_PATH}/dataset/COCO2017 .
69
+ cp -rf ${REGRESSION_PATH}/image .
70
+ #放入onnx模型文件ch_PP-OCRv3_det_infer_fix.onnx
71
+
72
+ mkdir workspace && cd workspace
73
+
74
+ #将ONNX模型转换为mlir模型,其中参数--output_names可以通过NETRON查看
75
+ model_transform.py \
76
+ --model_name ch_PP-OCRv3_det \
77
+ --model_def ../ch_PP-OCRv3_det_infer_fix.onnx \
78
+ --input_shapes [[1,3,960,608]] \
79
+ --mean 0.0,0.0,0.0 \
80
+ --scale 0.0039216,0.0039216,0.0039216 \
81
+ --keep_aspect_ratio \
82
+ --pixel_format rgb \
83
+ --output_names sigmoid_0.tmp_0 \
84
+ --test_input ../image/dog.jpg \
85
+ --test_result ch_PP-OCRv3_det_top_outputs.npz \
86
+ --mlir ch_PP-OCRv3_det.mlir
87
+
88
+ #将mlir模型转换为BM1684x的F32 bmodel模型
89
+ model_deploy.py \
90
+ --mlir ch_PP-OCRv3_det.mlir \
91
+ --quantize F32 \
92
+ --chip bm1684x \
93
+ --test_input ch_PP-OCRv3_det_in_f32.npz \
94
+ --test_reference ch_PP-OCRv3_det_top_outputs.npz \
95
+ --model ch_PP-OCRv3_det_1684x_f32.bmodel
96
+ ```
97
+ 最终获得可以在BM1684x上能够运行的bmodel模型ch_PP-OCRv3_det_1684x_f32.bmodel。按照上面同样的方法,可以将ch_ppocr_mobile_v2.0_cls,ch_PP-OCRv3_rec转换为bmodel的格式。如果需要进一步对模型进行加速,可以将ONNX模型转换为INT8 bmodel,具体步骤参见[TPU-MLIR文档](https://github.com/sophgo/tpu-mlir/blob/master/README.md)。
98
+
99
+
100
+ ## 4. 详细部署的部署示例
101
+ - [Python部署](python)
102
+ - [C++部署](cpp)
ocr_webapp/PaddleOCR/deploy/fastdeploy/sophgo/python/README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](README.md) | 简体中文
2
+ # PP-OCRv3 SOPHGO Python部署示例
3
+ 本目录下提供`infer.py`快速完成 PP-OCRv3 在SOPHGO TPU上部署的示例。
4
+
5
+ ## 1. 部署环境准备
6
+
7
+ 在部署前,需自行编译基于算能硬件的FastDeploy python wheel包并安装,参考文档[算能硬件部署环境](https://github.com/PaddlePaddle/FastDeploy/blob/develop/docs/cn/build_and_install#算能硬件部署环境)
8
+
9
+
10
+ ## 2.运行部署示例
11
+
12
+ ### 2.1 模型准备
13
+ 将Paddle模型转换为SOPHGO bmodel模型, 转换步骤参考[文档](../README.md)
14
+
15
+ ### 2.2 开始部署
16
+ ```bash
17
+ # 下载部署示例代码
18
+ git clone https://github.com/PaddlePaddle/FastDeploy.git
19
+ cd FastDeploy/examples/vision/ocr/PP-OCR/sophgo/python
20
+
21
+ # 如果您希望从PaddleOCR下载示例代码,请运行
22
+ git clone https://github.com/PaddlePaddle/PaddleOCR.git
23
+ # 注意:如果当前分支找不到下面的fastdeploy测试代码,请切换到dygraph分支
24
+ git checkout dygraph
25
+ cd PaddleOCR/deploy/fastdeploy/sophgo/python
26
+
27
+ # 下载图片
28
+ wget https://gitee.com/paddlepaddle/PaddleOCR/raw/release/2.6/doc/imgs/12.jpg
29
+
30
+ #下载字典文件
31
+ wget https://gitee.com/paddlepaddle/PaddleOCR/raw/release/2.6/ppocr/utils/ppocr_keys_v1.txt
32
+
33
+ # 推理
34
+ python3 infer.py --det_model ocr_bmodel/ch_PP-OCRv3_det_1684x_f32.bmodel \
35
+ --cls_model ocr_bmodel/ch_ppocr_mobile_v2.0_cls_1684x_f32.bmodel \
36
+ --rec_model ocr_bmodel/ch_PP-OCRv3_rec_1684x_f32.bmodel \
37
+ --rec_label_file ../ppocr_keys_v1.txt \
38
+ --image ../12.jpg
39
+
40
+ # 运行完成后返回结果如下所示
41
+ det boxes: [[42,413],[483,391],[484,428],[43,450]]rec text: 上海斯格威铂尔大酒店 rec score:0.952958 cls label: 0 cls score: 1.000000
42
+ det boxes: [[187,456],[399,448],[400,480],[188,488]]rec text: 打浦路15号 rec score:0.897335 cls label: 0 cls score: 1.000000
43
+ det boxes: [[23,507],[513,488],[515,529],[24,548]]rec text: 绿洲仕格维花园公寓 rec score:0.994589 cls label: 0 cls score: 1.000000
44
+ det boxes: [[74,553],[427,542],[428,571],[75,582]]rec text: 打浦路252935号 rec score:0.900663 cls label: 0 cls score: 1.000000
45
+
46
+ 可视化结果保存在sophgo_result.jpg中
47
+ ```
48
+
49
+ ## 3. 其它文档
50
+ - [PP-OCRv3 C++部署](../cpp)
51
+ - [转换 PP-OCRv3 SOPHGO模型文档](../README.md)
52
+ - 如果用户想要调整前后处理超参数、单独使用文字检测识别模型、使用其他模型等,更多详细文档与说明请参考[PP-OCR系列在CPU/GPU上的部署](../../cpu-gpu/cpp/README.md)
ocr_webapp/PaddleOCR/deploy/fastdeploy/web/README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](README.md) | 简体中文
2
+ # PP-OCRv3 前端部署示例
3
+
4
+ 本节介绍部署PaddleOCR的PP-OCRv3模型在浏览器中运行,以及@paddle-js-models/ocr npm包中的js接口。
5
+
6
+
7
+ ## 1. 前端部署PP-OCRv3模型
8
+ PP-OCRv3模型web demo使用[**参考文档**](https://github.com/PaddlePaddle/FastDeploy/tree/develop/examples/application/js/web_demo)
9
+
10
+ ## 2. PP-OCRv3 js接口
11
+
12
+ ```
13
+ import * as ocr from "@paddle-js-models/ocr";
14
+ await ocr.init(detConfig, recConfig);
15
+ const res = await ocr.recognize(img, option, postConfig);
16
+ ```
17
+ ocr模型加载和初始化,其中模型为Paddle.js模型格式,js模型转换方式参考[文档](https://github.com/PaddlePaddle/FastDeploy/tree/develop/examples/application/js/web_demo/README.md)
18
+
19
+ **init函数参数**
20
+
21
+ > * **detConfig**(dict): 文本检测模型配置参数,默认值为 {modelPath: 'https://js-models.bj.bcebos.com/PaddleOCR/PP-OCRv3/ch_PP-OCRv3_det_infer_js_960/model.json', fill: '#fff', mean: [0.485, 0.456, 0.406],std: [0.229, 0.224, 0.225]}; 其中,modelPath为文本检测模型路径,fill 为图像预处理padding的值,mean和std分别为预处理的均值和标准差
22
+ > * **recConfig**(dict)): 文本识别模型配置参数,默认值为 {modelPath: 'https://js-models.bj.bcebos.com/PaddleOCR/PP-OCRv3/ch_PP-OCRv3_rec_infer_js/model.json', fill: '#000', mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5]}; 其中,modelPath为文本检测模型路径,fill 为图像预处理padding的值,mean和std分别为预处理的均值和标准差
23
+
24
+
25
+ **recognize函数参数**
26
+
27
+ > * **img**(HTMLImageElement): 输入图像参数,类型为HTMLImageElement。
28
+ > * **option**(dict): 可视化文本检测框的canvas参数,可不用设置。
29
+ > * **postConfig**(dict): 文本检测后处理参数,默认值为:{shape: 960, thresh: 0.3, box_thresh: 0.6, unclip_ratio:1.5}; thresh是输出预测图的二值化阈值;box_thresh是输出框的阈值,低于此值的预测框会被丢弃,unclip_ratio是输出框扩大的比例。
30
+
31
+
32
+ ## 其它文档
33
+ - [PP-OCRv3 微信小程序部署文档](https://github.com/PaddlePaddle/FastDeploy/tree/develop/examples/application/js/mini_program)
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "kie_ser": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8871,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/module.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import numpy as np
30
+ import paddlehub as hub
31
+
32
+ from tools.infer.utility import base64_to_cv2
33
+ from ppstructure.kie.predict_kie_token_ser import SerPredictor
34
+ from ppstructure.utility import parse_args
35
+
36
+ from deploy.hubserving.kie_ser.params import read_params
37
+
38
+
39
+ @moduleinfo(
40
+ name="kie_ser",
41
+ version="1.0.0",
42
+ summary="kie ser service",
43
+ author="paddle-dev",
44
+ author_email="paddle-dev@baidu.com",
45
+ type="cv/KIE_SER")
46
+ class KIESer(hub.Module):
47
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
48
+ """
49
+ initialize with the necessary elements
50
+ """
51
+ cfg = self.merge_configs()
52
+
53
+ cfg.use_gpu = use_gpu
54
+ if use_gpu:
55
+ try:
56
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
57
+ int(_places[0])
58
+ print("use gpu: ", use_gpu)
59
+ print("CUDA_VISIBLE_DEVICES: ", _places)
60
+ cfg.gpu_mem = 8000
61
+ except:
62
+ raise RuntimeError(
63
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
64
+ )
65
+ cfg.ir_optim = True
66
+ cfg.enable_mkldnn = enable_mkldnn
67
+
68
+ self.ser_predictor = SerPredictor(cfg)
69
+
70
+ def merge_configs(self, ):
71
+ # deafult cfg
72
+ backup_argv = copy.deepcopy(sys.argv)
73
+ sys.argv = sys.argv[:1]
74
+ cfg = parse_args()
75
+
76
+ update_cfg_map = vars(read_params())
77
+
78
+ for key in update_cfg_map:
79
+ cfg.__setattr__(key, update_cfg_map[key])
80
+
81
+ sys.argv = copy.deepcopy(backup_argv)
82
+ return cfg
83
+
84
+ def read_images(self, paths=[]):
85
+ images = []
86
+ for img_path in paths:
87
+ assert os.path.isfile(
88
+ img_path), "The {} isn't a valid file.".format(img_path)
89
+ img = cv2.imread(img_path)
90
+ if img is None:
91
+ logger.info("error in loading image:{}".format(img_path))
92
+ continue
93
+ images.append(img)
94
+ return images
95
+
96
+ def predict(self, images=[], paths=[]):
97
+ """
98
+ Get the chinese texts in the predicted images.
99
+ Args:
100
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
101
+ paths (list[str]): The paths of images. If paths not images
102
+ Returns:
103
+ res (list): The result of chinese texts and save path of images.
104
+ """
105
+ if images != [] and isinstance(images, list) and paths == []:
106
+ predicted_data = images
107
+ elif images == [] and isinstance(paths, list) and paths != []:
108
+ predicted_data = self.read_images(paths)
109
+ else:
110
+ raise TypeError("The input data is inconsistent with expectations.")
111
+
112
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
113
+
114
+ all_results = []
115
+ for img in predicted_data:
116
+ if img is None:
117
+ logger.info("error in loading image")
118
+ all_results.append([])
119
+ continue
120
+ starttime = time.time()
121
+ ser_res, _, elapse = self.ser_predictor(img)
122
+ elapse = time.time() - starttime
123
+ logger.info("Predict time: {}".format(elapse))
124
+ all_results.append(ser_res)
125
+ return all_results
126
+
127
+ @serving
128
+ def serving_method(self, images, **kwargs):
129
+ """
130
+ Run as a service.
131
+ """
132
+ images_decode = [base64_to_cv2(image) for image in images]
133
+ results = self.predict(images_decode, **kwargs)
134
+ return results
135
+
136
+
137
+ if __name__ == '__main__':
138
+ ocr = OCRSystem()
139
+ ocr._initialize()
140
+ image_path = [
141
+ './doc/imgs/11.jpg',
142
+ './doc/imgs/12.jpg',
143
+ ]
144
+ res = ocr.predict(paths=image_path)
145
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser/params.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ from deploy.hubserving.ocr_system.params import read_params as pp_ocr_read_params
20
+
21
+
22
+ class Config(object):
23
+ pass
24
+
25
+
26
+ def read_params():
27
+ cfg = pp_ocr_read_params()
28
+
29
+ # SER params
30
+ cfg.kie_algorithm = "LayoutXLM"
31
+ cfg.use_visual_backbone = False
32
+
33
+ cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
34
+ cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
35
+ cfg.vis_font_path = "./doc/fonts/simfang.ttf"
36
+ cfg.ocr_order_method = "tb-yx"
37
+
38
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "kie_ser_re": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8872,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/module.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import numpy as np
30
+ import paddlehub as hub
31
+
32
+ from tools.infer.utility import base64_to_cv2
33
+ from ppstructure.kie.predict_kie_token_ser_re import SerRePredictor
34
+ from ppstructure.utility import parse_args
35
+
36
+ from deploy.hubserving.kie_ser_re.params import read_params
37
+
38
+
39
+ @moduleinfo(
40
+ name="kie_ser_re",
41
+ version="1.0.0",
42
+ summary="kie ser re service",
43
+ author="paddle-dev",
44
+ author_email="paddle-dev@baidu.com",
45
+ type="cv/KIE_SER_RE")
46
+ class KIESerRE(hub.Module):
47
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
48
+ """
49
+ initialize with the necessary elements
50
+ """
51
+ cfg = self.merge_configs()
52
+
53
+ cfg.use_gpu = use_gpu
54
+ if use_gpu:
55
+ try:
56
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
57
+ int(_places[0])
58
+ print("use gpu: ", use_gpu)
59
+ print("CUDA_VISIBLE_DEVICES: ", _places)
60
+ cfg.gpu_mem = 8000
61
+ except:
62
+ raise RuntimeError(
63
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
64
+ )
65
+ cfg.ir_optim = True
66
+ cfg.enable_mkldnn = enable_mkldnn
67
+
68
+ self.ser_re_predictor = SerRePredictor(cfg)
69
+
70
+ def merge_configs(self, ):
71
+ # deafult cfg
72
+ backup_argv = copy.deepcopy(sys.argv)
73
+ sys.argv = sys.argv[:1]
74
+ cfg = parse_args()
75
+
76
+ update_cfg_map = vars(read_params())
77
+
78
+ for key in update_cfg_map:
79
+ cfg.__setattr__(key, update_cfg_map[key])
80
+
81
+ sys.argv = copy.deepcopy(backup_argv)
82
+ return cfg
83
+
84
+ def read_images(self, paths=[]):
85
+ images = []
86
+ for img_path in paths:
87
+ assert os.path.isfile(
88
+ img_path), "The {} isn't a valid file.".format(img_path)
89
+ img = cv2.imread(img_path)
90
+ if img is None:
91
+ logger.info("error in loading image:{}".format(img_path))
92
+ continue
93
+ images.append(img)
94
+ return images
95
+
96
+ def predict(self, images=[], paths=[]):
97
+ """
98
+ Get the chinese texts in the predicted images.
99
+ Args:
100
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
101
+ paths (list[str]): The paths of images. If paths not images
102
+ Returns:
103
+ res (list): The result of chinese texts and save path of images.
104
+ """
105
+ if images != [] and isinstance(images, list) and paths == []:
106
+ predicted_data = images
107
+ elif images == [] and isinstance(paths, list) and paths != []:
108
+ predicted_data = self.read_images(paths)
109
+ else:
110
+ raise TypeError("The input data is inconsistent with expectations.")
111
+
112
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
113
+
114
+ all_results = []
115
+ for img in predicted_data:
116
+ if img is None:
117
+ logger.info("error in loading image")
118
+ all_results.append([])
119
+ continue
120
+ print(img.shape)
121
+ starttime = time.time()
122
+ re_res, _ = self.ser_re_predictor(img)
123
+ print(re_res)
124
+ elapse = time.time() - starttime
125
+ logger.info("Predict time: {}".format(elapse))
126
+ all_results.append(re_res)
127
+ return all_results
128
+
129
+ @serving
130
+ def serving_method(self, images, **kwargs):
131
+ """
132
+ Run as a service.
133
+ """
134
+ images_decode = [base64_to_cv2(image) for image in images]
135
+ results = self.predict(images_decode, **kwargs)
136
+ return results
137
+
138
+
139
+ if __name__ == '__main__':
140
+ ocr = OCRSystem()
141
+ ocr._initialize()
142
+ image_path = [
143
+ './doc/imgs/11.jpg',
144
+ './doc/imgs/12.jpg',
145
+ ]
146
+ res = ocr.predict(paths=image_path)
147
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/kie_ser_re/params.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ from deploy.hubserving.ocr_system.params import read_params as pp_ocr_read_params
20
+
21
+
22
+ class Config(object):
23
+ pass
24
+
25
+
26
+ def read_params():
27
+ cfg = pp_ocr_read_params()
28
+
29
+ # SER params
30
+ cfg.kie_algorithm = "LayoutXLM"
31
+ cfg.use_visual_backbone = False
32
+
33
+ cfg.ser_model_dir = "./inference/ser_vi_layoutxlm_xfund_infer"
34
+ cfg.re_model_dir = "./inference/re_vi_layoutxlm_xfund_infer"
35
+
36
+ cfg.ser_dict_path = "train_data/XFUND/class_list_xfun.txt"
37
+ cfg.vis_font_path = "./doc/fonts/simfang.ttf"
38
+ cfg.ocr_order_method = "tb-yx"
39
+
40
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "ocr_cls": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8866,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/module.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+ import paddlehub
24
+ from paddlehub.common.logger import logger
25
+ from paddlehub.module.module import moduleinfo, runnable, serving
26
+ import cv2
27
+ import paddlehub as hub
28
+
29
+ from tools.infer.utility import base64_to_cv2
30
+ from tools.infer.predict_cls import TextClassifier
31
+ from tools.infer.utility import parse_args
32
+ from deploy.hubserving.ocr_cls.params import read_params
33
+
34
+
35
+ @moduleinfo(
36
+ name="ocr_cls",
37
+ version="1.0.0",
38
+ summary="ocr angle cls service",
39
+ author="paddle-dev",
40
+ author_email="paddle-dev@baidu.com",
41
+ type="cv/text_angle_cls")
42
+ class OCRCls(hub.Module):
43
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
44
+ """
45
+ initialize with the necessary elements
46
+ """
47
+ cfg = self.merge_configs()
48
+
49
+ cfg.use_gpu = use_gpu
50
+ if use_gpu:
51
+ try:
52
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
53
+ int(_places[0])
54
+ print("use gpu: ", use_gpu)
55
+ print("CUDA_VISIBLE_DEVICES: ", _places)
56
+ cfg.gpu_mem = 8000
57
+ except:
58
+ raise RuntimeError(
59
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
60
+ )
61
+ cfg.ir_optim = True
62
+ cfg.enable_mkldnn = enable_mkldnn
63
+
64
+ self.text_classifier = TextClassifier(cfg)
65
+
66
+ def merge_configs(self, ):
67
+ # deafult cfg
68
+ backup_argv = copy.deepcopy(sys.argv)
69
+ sys.argv = sys.argv[:1]
70
+ cfg = parse_args()
71
+
72
+ update_cfg_map = vars(read_params())
73
+
74
+ for key in update_cfg_map:
75
+ cfg.__setattr__(key, update_cfg_map[key])
76
+
77
+ sys.argv = copy.deepcopy(backup_argv)
78
+ return cfg
79
+
80
+ def read_images(self, paths=[]):
81
+ images = []
82
+ for img_path in paths:
83
+ assert os.path.isfile(
84
+ img_path), "The {} isn't a valid file.".format(img_path)
85
+ img = cv2.imread(img_path)
86
+ if img is None:
87
+ logger.info("error in loading image:{}".format(img_path))
88
+ continue
89
+ images.append(img)
90
+ return images
91
+
92
+ def predict(self, images=[], paths=[]):
93
+ """
94
+ Get the text angle in the predicted images.
95
+ Args:
96
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
97
+ paths (list[str]): The paths of images. If paths not images
98
+ Returns:
99
+ res (list): The result of text detection box and save path of images.
100
+ """
101
+
102
+ if images != [] and isinstance(images, list) and paths == []:
103
+ predicted_data = images
104
+ elif images == [] and isinstance(paths, list) and paths != []:
105
+ predicted_data = self.read_images(paths)
106
+ else:
107
+ raise TypeError("The input data is inconsistent with expectations.")
108
+
109
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
110
+
111
+ img_list = []
112
+ for img in predicted_data:
113
+ if img is None:
114
+ continue
115
+ img_list.append(img)
116
+
117
+ rec_res_final = []
118
+ try:
119
+ img_list, cls_res, predict_time = self.text_classifier(img_list)
120
+ for dno in range(len(cls_res)):
121
+ angle, score = cls_res[dno]
122
+ rec_res_final.append({
123
+ 'angle': angle,
124
+ 'confidence': float(score),
125
+ })
126
+ except Exception as e:
127
+ print(e)
128
+ return [[]]
129
+
130
+ return [rec_res_final]
131
+
132
+ @serving
133
+ def serving_method(self, images, **kwargs):
134
+ """
135
+ Run as a service.
136
+ """
137
+ images_decode = [base64_to_cv2(image) for image in images]
138
+ results = self.predict(images_decode, **kwargs)
139
+ return results
140
+
141
+
142
+ if __name__ == '__main__':
143
+ ocr = OCRCls()
144
+ ocr._initialize()
145
+ image_path = [
146
+ './doc/imgs_words/ch/word_1.jpg',
147
+ './doc/imgs_words/ch/word_2.jpg',
148
+ './doc/imgs_words/ch/word_3.jpg',
149
+ ]
150
+ res = ocr.predict(paths=image_path)
151
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_cls/params.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+
20
+ class Config(object):
21
+ pass
22
+
23
+
24
+ def read_params():
25
+ cfg = Config()
26
+
27
+ #params for text classifier
28
+ cfg.cls_model_dir = "./inference/ch_ppocr_mobile_v2.0_cls_infer/"
29
+ cfg.cls_image_shape = "3, 48, 192"
30
+ cfg.label_list = ['0', '180']
31
+ cfg.cls_batch_num = 30
32
+ cfg.cls_thresh = 0.9
33
+
34
+ cfg.use_pdserving = False
35
+ cfg.use_tensorrt = False
36
+
37
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "ocr_det": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8865,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/module.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+
23
+ import copy
24
+ import paddlehub
25
+ from paddlehub.common.logger import logger
26
+ from paddlehub.module.module import moduleinfo, runnable, serving
27
+ import cv2
28
+ import numpy as np
29
+ import paddlehub as hub
30
+
31
+ from tools.infer.utility import base64_to_cv2
32
+ from tools.infer.predict_det import TextDetector
33
+ from tools.infer.utility import parse_args
34
+ from deploy.hubserving.ocr_system.params import read_params
35
+
36
+
37
+ @moduleinfo(
38
+ name="ocr_det",
39
+ version="1.0.0",
40
+ summary="ocr detection service",
41
+ author="paddle-dev",
42
+ author_email="paddle-dev@baidu.com",
43
+ type="cv/text_detection")
44
+ class OCRDet(hub.Module):
45
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
46
+ """
47
+ initialize with the necessary elements
48
+ """
49
+ cfg = self.merge_configs()
50
+
51
+ cfg.use_gpu = use_gpu
52
+ if use_gpu:
53
+ try:
54
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
55
+ int(_places[0])
56
+ print("use gpu: ", use_gpu)
57
+ print("CUDA_VISIBLE_DEVICES: ", _places)
58
+ cfg.gpu_mem = 8000
59
+ except:
60
+ raise RuntimeError(
61
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
62
+ )
63
+ cfg.ir_optim = True
64
+ cfg.enable_mkldnn = enable_mkldnn
65
+
66
+ self.text_detector = TextDetector(cfg)
67
+
68
+ def merge_configs(self, ):
69
+ # deafult cfg
70
+ backup_argv = copy.deepcopy(sys.argv)
71
+ sys.argv = sys.argv[:1]
72
+ cfg = parse_args()
73
+
74
+ update_cfg_map = vars(read_params())
75
+
76
+ for key in update_cfg_map:
77
+ cfg.__setattr__(key, update_cfg_map[key])
78
+
79
+ sys.argv = copy.deepcopy(backup_argv)
80
+ return cfg
81
+
82
+ def read_images(self, paths=[]):
83
+ images = []
84
+ for img_path in paths:
85
+ assert os.path.isfile(
86
+ img_path), "The {} isn't a valid file.".format(img_path)
87
+ img = cv2.imread(img_path)
88
+ if img is None:
89
+ logger.info("error in loading image:{}".format(img_path))
90
+ continue
91
+ images.append(img)
92
+ return images
93
+
94
+ def predict(self, images=[], paths=[]):
95
+ """
96
+ Get the text box in the predicted images.
97
+ Args:
98
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
99
+ paths (list[str]): The paths of images. If paths not images
100
+ Returns:
101
+ res (list): The result of text detection box and save path of images.
102
+ """
103
+
104
+ if images != [] and isinstance(images, list) and paths == []:
105
+ predicted_data = images
106
+ elif images == [] and isinstance(paths, list) and paths != []:
107
+ predicted_data = self.read_images(paths)
108
+ else:
109
+ raise TypeError("The input data is inconsistent with expectations.")
110
+
111
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
112
+
113
+ all_results = []
114
+ for img in predicted_data:
115
+ if img is None:
116
+ logger.info("error in loading image")
117
+ all_results.append([])
118
+ continue
119
+ dt_boxes, elapse = self.text_detector(img)
120
+ logger.info("Predict time : {}".format(elapse))
121
+
122
+ rec_res_final = []
123
+ for dno in range(len(dt_boxes)):
124
+ rec_res_final.append({
125
+ 'text_region': dt_boxes[dno].astype(np.int32).tolist()
126
+ })
127
+ all_results.append(rec_res_final)
128
+ return all_results
129
+
130
+ @serving
131
+ def serving_method(self, images, **kwargs):
132
+ """
133
+ Run as a service.
134
+ """
135
+ images_decode = [base64_to_cv2(image) for image in images]
136
+ results = self.predict(images_decode, **kwargs)
137
+ return results
138
+
139
+
140
+ if __name__ == '__main__':
141
+ ocr = OCRDet()
142
+ ocr._initialize()
143
+ image_path = [
144
+ './doc/imgs/11.jpg',
145
+ './doc/imgs/12.jpg',
146
+ ]
147
+ res = ocr.predict(paths=image_path)
148
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_det/params.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+
20
+ class Config(object):
21
+ pass
22
+
23
+
24
+ def read_params():
25
+ cfg = Config()
26
+
27
+ #params for text detector
28
+ cfg.det_algorithm = "DB"
29
+ cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
30
+ cfg.det_limit_side_len = 960
31
+ cfg.det_limit_type = 'max'
32
+
33
+ #DB parmas
34
+ cfg.det_db_thresh = 0.3
35
+ cfg.det_db_box_thresh = 0.6
36
+ cfg.det_db_unclip_ratio = 1.5
37
+ cfg.use_dilation = False
38
+ cfg.det_db_score_mode = "fast"
39
+
40
+ # #EAST parmas
41
+ # cfg.det_east_score_thresh = 0.8
42
+ # cfg.det_east_cover_thresh = 0.1
43
+ # cfg.det_east_nms_thresh = 0.2
44
+
45
+ cfg.use_pdserving = False
46
+ cfg.use_tensorrt = False
47
+
48
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "ocr_rec": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8867,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/module.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+ import paddlehub
24
+ from paddlehub.common.logger import logger
25
+ from paddlehub.module.module import moduleinfo, runnable, serving
26
+ import cv2
27
+ import paddlehub as hub
28
+
29
+ from tools.infer.utility import base64_to_cv2
30
+ from tools.infer.predict_rec import TextRecognizer
31
+ from tools.infer.utility import parse_args
32
+ from deploy.hubserving.ocr_rec.params import read_params
33
+
34
+
35
+ @moduleinfo(
36
+ name="ocr_rec",
37
+ version="1.0.0",
38
+ summary="ocr recognition service",
39
+ author="paddle-dev",
40
+ author_email="paddle-dev@baidu.com",
41
+ type="cv/text_recognition")
42
+ class OCRRec(hub.Module):
43
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
44
+ """
45
+ initialize with the necessary elements
46
+ """
47
+ cfg = self.merge_configs()
48
+
49
+ cfg.use_gpu = use_gpu
50
+ if use_gpu:
51
+ try:
52
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
53
+ int(_places[0])
54
+ print("use gpu: ", use_gpu)
55
+ print("CUDA_VISIBLE_DEVICES: ", _places)
56
+ cfg.gpu_mem = 8000
57
+ except:
58
+ raise RuntimeError(
59
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
60
+ )
61
+ cfg.ir_optim = True
62
+ cfg.enable_mkldnn = enable_mkldnn
63
+
64
+ self.text_recognizer = TextRecognizer(cfg)
65
+
66
+ def merge_configs(self, ):
67
+ # deafult cfg
68
+ backup_argv = copy.deepcopy(sys.argv)
69
+ sys.argv = sys.argv[:1]
70
+ cfg = parse_args()
71
+
72
+ update_cfg_map = vars(read_params())
73
+
74
+ for key in update_cfg_map:
75
+ cfg.__setattr__(key, update_cfg_map[key])
76
+
77
+ sys.argv = copy.deepcopy(backup_argv)
78
+ return cfg
79
+
80
+ def read_images(self, paths=[]):
81
+ images = []
82
+ for img_path in paths:
83
+ assert os.path.isfile(
84
+ img_path), "The {} isn't a valid file.".format(img_path)
85
+ img = cv2.imread(img_path)
86
+ if img is None:
87
+ logger.info("error in loading image:{}".format(img_path))
88
+ continue
89
+ images.append(img)
90
+ return images
91
+
92
+ def predict(self, images=[], paths=[]):
93
+ """
94
+ Get the text box in the predicted images.
95
+ Args:
96
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
97
+ paths (list[str]): The paths of images. If paths not images
98
+ Returns:
99
+ res (list): The result of text detection box and save path of images.
100
+ """
101
+
102
+ if images != [] and isinstance(images, list) and paths == []:
103
+ predicted_data = images
104
+ elif images == [] and isinstance(paths, list) and paths != []:
105
+ predicted_data = self.read_images(paths)
106
+ else:
107
+ raise TypeError("The input data is inconsistent with expectations.")
108
+
109
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
110
+
111
+ img_list = []
112
+ for img in predicted_data:
113
+ if img is None:
114
+ continue
115
+ img_list.append(img)
116
+
117
+ rec_res_final = []
118
+ try:
119
+ rec_res, predict_time = self.text_recognizer(img_list)
120
+ for dno in range(len(rec_res)):
121
+ text, score = rec_res[dno]
122
+ rec_res_final.append({
123
+ 'text': text,
124
+ 'confidence': float(score),
125
+ })
126
+ except Exception as e:
127
+ print(e)
128
+ return [[]]
129
+
130
+ return [rec_res_final]
131
+
132
+ @serving
133
+ def serving_method(self, images, **kwargs):
134
+ """
135
+ Run as a service.
136
+ """
137
+ images_decode = [base64_to_cv2(image) for image in images]
138
+ results = self.predict(images_decode, **kwargs)
139
+ return results
140
+
141
+
142
+ if __name__ == '__main__':
143
+ ocr = OCRRec()
144
+ ocr._initialize()
145
+ image_path = [
146
+ './doc/imgs_words/ch/word_1.jpg',
147
+ './doc/imgs_words/ch/word_2.jpg',
148
+ './doc/imgs_words/ch/word_3.jpg',
149
+ ]
150
+ res = ocr.predict(paths=image_path)
151
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_rec/params.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+
20
+ class Config(object):
21
+ pass
22
+
23
+
24
+ def read_params():
25
+ cfg = Config()
26
+
27
+ #params for text recognizer
28
+ cfg.rec_algorithm = "CRNN"
29
+ cfg.rec_model_dir = "./inference/ch_PP-OCRv3_rec_infer/"
30
+
31
+ cfg.rec_image_shape = "3, 48, 320"
32
+ cfg.rec_batch_num = 6
33
+ cfg.max_text_length = 25
34
+
35
+ cfg.rec_char_dict_path = "./ppocr/utils/ppocr_keys_v1.txt"
36
+ cfg.use_space_char = True
37
+
38
+ cfg.use_pdserving = False
39
+ cfg.use_tensorrt = False
40
+
41
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "ocr_system": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8868,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/module.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import numpy as np
30
+ import paddlehub as hub
31
+
32
+ from tools.infer.utility import base64_to_cv2
33
+ from tools.infer.predict_system import TextSystem
34
+ from tools.infer.utility import parse_args
35
+ from deploy.hubserving.ocr_system.params import read_params
36
+
37
+
38
+ @moduleinfo(
39
+ name="ocr_system",
40
+ version="1.0.0",
41
+ summary="ocr system service",
42
+ author="paddle-dev",
43
+ author_email="paddle-dev@baidu.com",
44
+ type="cv/PP-OCR_system")
45
+ class OCRSystem(hub.Module):
46
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
47
+ """
48
+ initialize with the necessary elements
49
+ """
50
+ cfg = self.merge_configs()
51
+
52
+ cfg.use_gpu = use_gpu
53
+ if use_gpu:
54
+ try:
55
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
56
+ int(_places[0])
57
+ print("use gpu: ", use_gpu)
58
+ print("CUDA_VISIBLE_DEVICES: ", _places)
59
+ cfg.gpu_mem = 8000
60
+ except:
61
+ raise RuntimeError(
62
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
63
+ )
64
+ cfg.ir_optim = True
65
+ cfg.enable_mkldnn = enable_mkldnn
66
+
67
+ self.text_sys = TextSystem(cfg)
68
+
69
+ def merge_configs(self, ):
70
+ # deafult cfg
71
+ backup_argv = copy.deepcopy(sys.argv)
72
+ sys.argv = sys.argv[:1]
73
+ cfg = parse_args()
74
+
75
+ update_cfg_map = vars(read_params())
76
+
77
+ for key in update_cfg_map:
78
+ cfg.__setattr__(key, update_cfg_map[key])
79
+
80
+ sys.argv = copy.deepcopy(backup_argv)
81
+ return cfg
82
+
83
+ def read_images(self, paths=[]):
84
+ images = []
85
+ for img_path in paths:
86
+ assert os.path.isfile(
87
+ img_path), "The {} isn't a valid file.".format(img_path)
88
+ img = cv2.imread(img_path)
89
+ if img is None:
90
+ logger.info("error in loading image:{}".format(img_path))
91
+ continue
92
+ images.append(img)
93
+ return images
94
+
95
+ def predict(self, images=[], paths=[]):
96
+ """
97
+ Get the chinese texts in the predicted images.
98
+ Args:
99
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
100
+ paths (list[str]): The paths of images. If paths not images
101
+ Returns:
102
+ res (list): The result of chinese texts and save path of images.
103
+ """
104
+
105
+ if images != [] and isinstance(images, list) and paths == []:
106
+ predicted_data = images
107
+ elif images == [] and isinstance(paths, list) and paths != []:
108
+ predicted_data = self.read_images(paths)
109
+ else:
110
+ raise TypeError("The input data is inconsistent with expectations.")
111
+
112
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
113
+
114
+ all_results = []
115
+ for img in predicted_data:
116
+ if img is None:
117
+ logger.info("error in loading image")
118
+ all_results.append([])
119
+ continue
120
+ starttime = time.time()
121
+ dt_boxes, rec_res, _ = self.text_sys(img)
122
+ elapse = time.time() - starttime
123
+ logger.info("Predict time: {}".format(elapse))
124
+
125
+ dt_num = len(dt_boxes)
126
+ rec_res_final = []
127
+
128
+ for dno in range(dt_num):
129
+ text, score = rec_res[dno]
130
+ rec_res_final.append({
131
+ 'text': text,
132
+ 'confidence': float(score),
133
+ 'text_region': dt_boxes[dno].astype(np.int32).tolist()
134
+ })
135
+ all_results.append(rec_res_final)
136
+ return all_results
137
+
138
+ @serving
139
+ def serving_method(self, images, **kwargs):
140
+ """
141
+ Run as a service.
142
+ """
143
+ images_decode = [base64_to_cv2(image) for image in images]
144
+ results = self.predict(images_decode, **kwargs)
145
+ return results
146
+
147
+
148
+ if __name__ == '__main__':
149
+ ocr = OCRSystem()
150
+ ocr._initialize()
151
+ image_path = [
152
+ './doc/imgs/11.jpg',
153
+ './doc/imgs/12.jpg',
154
+ ]
155
+ res = ocr.predict(paths=image_path)
156
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/ocr_system/params.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+
20
+ class Config(object):
21
+ pass
22
+
23
+
24
+ def read_params():
25
+ cfg = Config()
26
+
27
+ #params for text detector
28
+ cfg.det_algorithm = "DB"
29
+ cfg.det_model_dir = "./inference/ch_PP-OCRv3_det_infer/"
30
+ cfg.det_limit_side_len = 960
31
+ cfg.det_limit_type = 'max'
32
+
33
+ #DB parmas
34
+ cfg.det_db_thresh = 0.3
35
+ cfg.det_db_box_thresh = 0.5
36
+ cfg.det_db_unclip_ratio = 1.6
37
+ cfg.use_dilation = False
38
+ cfg.det_db_score_mode = "fast"
39
+
40
+ #EAST parmas
41
+ cfg.det_east_score_thresh = 0.8
42
+ cfg.det_east_cover_thresh = 0.1
43
+ cfg.det_east_nms_thresh = 0.2
44
+
45
+ #params for text recognizer
46
+ cfg.rec_algorithm = "CRNN"
47
+ cfg.rec_model_dir = "./inference/ch_PP-OCRv3_rec_infer/"
48
+
49
+ cfg.rec_image_shape = "3, 48, 320"
50
+ cfg.rec_batch_num = 6
51
+ cfg.max_text_length = 25
52
+
53
+ cfg.rec_char_dict_path = "./ppocr/utils/ppocr_keys_v1.txt"
54
+ cfg.use_space_char = True
55
+
56
+ #params for text classifier
57
+ cfg.use_angle_cls = True
58
+ cfg.cls_model_dir = "./inference/ch_ppocr_mobile_v2.0_cls_infer/"
59
+ cfg.cls_image_shape = "3, 48, 192"
60
+ cfg.label_list = ['0', '180']
61
+ cfg.cls_batch_num = 30
62
+ cfg.cls_thresh = 0.9
63
+
64
+ cfg.use_pdserving = False
65
+ cfg.use_tensorrt = False
66
+ cfg.drop_score = 0.5
67
+
68
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/readme.md ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [English](readme_en.md) | 简体中文
2
+
3
+ - [基于PaddleHub Serving的服务部署](#基于paddlehub-serving的服务部署)
4
+ - [1. 近期更新](#1-近期更新)
5
+ - [2. 快速启动服务](#2-快速启动服务)
6
+ - [2.1 安装PaddleHub](#21-安装PaddleHub)
7
+ - [2.2 下载推理模型](#22-下载推理模型)
8
+ - [2.3 安装服务模块](#23-安装服务模块)
9
+ - [2.4 启动服务](#24-启动服务)
10
+ - [2.4.1. 命令行命令启动(仅支持CPU)](#241-命令行命令启动仅支持cpu)
11
+ - [2.4.2 配置文件启动(支持CPU、GPU)](#242-配置文件启动支持cpugpu)
12
+ - [3. 发送预测请求](#3-发送预测请求)
13
+ - [4. 返回结果格式说明](#4-返回结果格式说明)
14
+ - [5. 自定义修改服务模块](#5-自定义修改服务模块)
15
+
16
+
17
+ PaddleOCR提供2种服务部署方式:
18
+ - 基于PaddleHub Serving的部署:代码路径为`./deploy/hubserving`,按照本教程使用;
19
+ - 基于PaddleServing的部署:代码路径为`./deploy/pdserving`,使用方法参考[文档](../../deploy/pdserving/README_CN.md)。
20
+
21
+ # 基于PaddleHub Serving的服务部署
22
+
23
+ hubserving服务部署目录下包括文本检测、文本方向分类,文本识别、文本检测+文本方向分类+文本识别3阶段串联,版面分析、表格识别和PP-Structure七种服务包,请根据需求选择相应的服务包进行安装和启动。目录结构如下:
24
+ ```
25
+ deploy/hubserving/
26
+ └─ ocr_cls 文本方向分类模块服务包
27
+ └─ ocr_det 文本检测模块服务包
28
+ └─ ocr_rec 文本识别模块服务包
29
+ └─ ocr_system 文本检测+文本方向分类+文本识别串联服务包
30
+ └─ structure_layout 版面分析服务包
31
+ └─ structure_table 表格识别服务包
32
+ └─ structure_system PP-Structure服务包
33
+ └─ kie_ser 关键信息抽取-SER服务包
34
+ └─ kie_ser_re 关键信息抽取-SER+RE服务包
35
+ ```
36
+
37
+ 每个服务包下包含3个文件。以2阶段串联服务包为例,目录如下:
38
+ ```
39
+ deploy/hubserving/ocr_system/
40
+ └─ __init__.py 空文件,必选
41
+ └─ config.json 配置文件,可选,使用配置启动服务时作为参数传入
42
+ └─ module.py 主模块,必选,包含服务的完整逻辑
43
+ └─ params.py 参数文件,必选,包含模型路径、前后处理参数等参数
44
+ ```
45
+ ## 1. 近期更新
46
+
47
+ * 2022.10.09 新增关键信息抽取服务。
48
+ * 2022.08.23 新增版面分析服务。
49
+ * 2022.05.05 新增PP-OCRv3检测和识别模型。
50
+ * 2022.03.30 新增PP-Structure和表格识别两种服务。
51
+
52
+ ## 2. 快速启动服务
53
+ 以下步骤以检测+识别2阶段串联服务为例,如果只需要检测服务或识别服务,替换相应文件路径即可。
54
+ ### 2.1 安装PaddleHub
55
+ paddlehub 需要 python>3.6.2
56
+ ```bash
57
+ pip3 install paddlehub==2.1.0 --upgrade -i https://mirror.baidu.com/pypi/simple
58
+ ```
59
+
60
+ ### 2.2 下载推理模型
61
+ 安装服务模块前,需要准备推理模型并放到正确路径。默认使用的是PP-OCRv3模型,默认模型路径为:
62
+ | 模型 | 路径 |
63
+ | ------- | - |
64
+ | 检测模型 | `./inference/ch_PP-OCRv3_det_infer/` |
65
+ | 识别模型 | `./inference/ch_PP-OCRv3_rec_infer/` |
66
+ | 方向分类器 | `./inference/ch_ppocr_mobile_v2.0_cls_infer/` |
67
+ | 版面分析模型 | `./inference/picodet_lcnet_x1_0_fgd_layout_infer/` |
68
+ | 表格结构识别模型 | `./inference/ch_ppstructure_mobile_v2.0_SLANet_infer/` |
69
+ | 关键信息抽取SER模型 | `./inference/ser_vi_layoutxlm_xfund_infer/` |
70
+ | 关键信息抽取RE模型 | `./inference/re_vi_layoutxlm_xfund_infer/` |
71
+
72
+ **模型路径可在`params.py`中查看和修改。**
73
+
74
+ 更多模型可以从PaddleOCR提供的模型库[PP-OCR](../../doc/doc_ch/models_list.md)和[PP-Structure](../../ppstructure/docs/models_list.md)下载,也可以替换成自己训练转换好的模型。
75
+
76
+ ### 2.3 安装服务模块
77
+ PaddleOCR提供5种服务模块,根据需要安装所需模块。
78
+
79
+ 在Linux环境(Windows环境请将`/`替换为`\`)下,安装模块命令如下表:
80
+ | 服务模块 | 命令 |
81
+ | ------- | - |
82
+ | 检测 | `hub install deploy/hubserving/ocr_det` |
83
+ | 分类 | `hub install deploy/hubserving/ocr_cls` |
84
+ | 识别 | `hub install deploy/hubserving/ocr_rec` |
85
+ | 检测+识别串联 | `hub install deploy/hubserving/ocr_system` |
86
+ | 表格识别 | `hub install deploy/hubserving/structure_table` |
87
+ | PP-Structure | `hub install deploy/hubserving/structure_system` |
88
+ | 版面分析 | `hub install deploy/hubserving/structure_layout` |
89
+ | 关键信息抽取SER | `hub install deploy/hubserving/kie_ser` |
90
+ | 关键信息抽取SER+RE | `hub install deploy/hubserving/kie_ser_re` |
91
+
92
+ ### 2.4 启动服务
93
+ #### 2.4.1. 命令行命令启动(仅支持CPU)
94
+ **启动命令:**
95
+ ```bash
96
+ hub serving start --modules Module1==Version1, Module2==Version2, ... \
97
+ --port 8866 \
98
+ --use_multiprocess \
99
+ --workers \
100
+ ```
101
+
102
+ **参数:**
103
+ |参数|用途|
104
+ |---|---|
105
+ |`--modules`/`-m`|PaddleHub Serving预安装模型,以多个Module==Version键值对的形式列出<br>**当不指定Version时,默认选择最新版本**|
106
+ |`--port`/`-p`|服务端口,默认为8866|
107
+ |`--use_multiprocess`|是否启用并发方式,默认为单进程方式,推荐多核CPU机器使用此方式<br>**Windows操作系统只支持单进程方式**|
108
+ |`--workers`|在并发方式下指定的并发任务数,默认为`2*cpu_count-1`,其中`cpu_count`为CPU核数|
109
+
110
+ 如启动串联服务:
111
+ ```bash
112
+ hub serving start -m ocr_system
113
+ ```
114
+
115
+ 这样就完成了一个服务化API的部署,使用默认端口号8866。
116
+
117
+ #### 2.4.2 配置文件启动(支持CPU、GPU)
118
+ **启动命令:**
119
+ ```bash
120
+ hub serving start -c config.json
121
+ ```
122
+
123
+ 其中,`config.json`格式如下:
124
+ ```json
125
+ {
126
+ "modules_info": {
127
+ "ocr_system": {
128
+ "init_args": {
129
+ "version": "1.0.0",
130
+ "use_gpu": true
131
+ },
132
+ "predict_args": {
133
+ }
134
+ }
135
+ },
136
+ "port": 8868,
137
+ "use_multiprocess": false,
138
+ "workers": 2
139
+ }
140
+ ```
141
+
142
+ - `init_args`中的可配参数与`module.py`中的`_initialize`函数接口一致。
143
+
144
+ **当`use_gpu`为`true`时,表示使用GPU启动服务。**
145
+ - `predict_args`中的可配参数与`module.py`中的`predict`函数接口一致。
146
+
147
+ **注意:**
148
+ - 使用配置文件启动服务时,其他参数会被忽略。
149
+ - 如果使用GPU预测(即,`use_gpu`置为`true`),则需要在启动服务之前,设置CUDA_VISIBLE_DEVICES环境变量,如:
150
+ ```bash
151
+ export CUDA_VISIBLE_DEVICES=0
152
+ ```
153
+ - **`use_gpu`不可与`use_multiprocess`同时为`true`**。
154
+
155
+ 如,使用GPU 3号卡启动串联服务:
156
+ ```bash
157
+ export CUDA_VISIBLE_DEVICES=3
158
+ hub serving start -c deploy/hubserving/ocr_system/config.json
159
+ ```
160
+
161
+ ## 3. 发送预测请求
162
+ 配置好服务端,可使用以下命令发送预测请求,获取预测结果:
163
+ ```bash
164
+ python tools/test_hubserving.py --server_url=server_url --image_dir=image_path
165
+ ```
166
+
167
+ 需要给脚本传递2个参数:
168
+ - `server_url`:服务地址,格式为`http://[ip_address]:[port]/predict/[module_name]`
169
+
170
+ 例如,如果使用配置文件启动分类,检测、识别,检测+分类+识别3阶段,表格识别和PP-Structure服务
171
+
172
+ 并为每个服务修改了port,那么发送请求的url将分别是:
173
+ ```
174
+ http://127.0.0.1:8865/predict/ocr_det
175
+ http://127.0.0.1:8866/predict/ocr_cls
176
+ http://127.0.0.1:8867/predict/ocr_rec
177
+ http://127.0.0.1:8868/predict/ocr_system
178
+ http://127.0.0.1:8869/predict/structure_table
179
+ http://127.0.0.1:8870/predict/structure_system
180
+ http://127.0.0.1:8870/predict/structure_layout
181
+ http://127.0.0.1:8871/predict/kie_ser
182
+ http://127.0.0.1:8872/predict/kie_ser_re
183
+ ```
184
+ - `image_dir`:测试图像路径,可以是单张图片路径,也可以是图像集合目录路径
185
+ - `visualize`:是否可视化结果,默认为False
186
+ - `output`:可视化结果保存路径,默认为`./hubserving_result`
187
+
188
+ 访问示例:
189
+ ```bash
190
+ python tools/test_hubserving.py --server_url=http://127.0.0.1:8868/predict/ocr_system --image_dir=./doc/imgs/ --visualize=false
191
+ ```
192
+
193
+ ## 4. 返回结果格式说明
194
+ 返回结果为列表(list),列表中的每一项为词典(dict),词典一共可能包含3种字段,信息如下:
195
+ |字段名称|数据类型|意义|
196
+ |---|---|---|
197
+ |angle|str|文本角度|
198
+ |text|str|文本内容|
199
+ |confidence|float| 文本识别置信度或文本角度分类置信度|
200
+ |text_region|list|文本位置坐标|
201
+ |html|str|表格的html字符串|
202
+ |regions|list|版面分析+表格识别+OCR的结果,每一项为一个list<br>包含表示区域坐标的`bbox`,区域类型的`type`和区域结果的`res`三个字段|
203
+ |layout|list|版面分析的结果,每一项一个dict,包含版面区域坐标的`bbox`,区域类型的`label`|
204
+
205
+ 不同模块返回的字段不同,如,文本识别服务模块返回结果不含`text_region`字段,具体信息如下:
206
+ |字段名/模块名 |ocr_det |ocr_cls |ocr_rec |ocr_system |structure_table |structure_system |structure_layout |kie_ser |kie_re |
207
+ |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
208
+ |angle | |✔ | |✔ | | | |
209
+ |text | | |✔ |✔ | |✔ | |✔ |✔ |
210
+ |confidence | |✔ |✔ |✔ | |✔ | |✔ |✔ |
211
+ |text_region |✔ | | |✔ | |✔ | |✔ |✔ |
212
+ |html | | | | |✔ |✔ | | | |
213
+ |regions | | | | |✔ |✔ | | | |
214
+ |layout | | | | | | |✔ | | |
215
+ |ser_res | | | | | | | |✔ | |
216
+ |re_res | | | | | | | | |✔ |
217
+
218
+ **说明:** 如果需要增加、删除、修改返回字段,可在相应模块的`module.py`文件中进行修改,完整流程参考下一节自定义修改服务模块。
219
+
220
+ ## 5. 自定义修改服务模块
221
+ 如果需要修改服务逻辑,一般需要操作以下步骤(以修改`deploy/hubserving/ocr_system`为例):
222
+
223
+ 1. 停止服务:
224
+ ```bash
225
+ hub serving stop --port/-p XXXX
226
+ ```
227
+ 2. 到`deploy/hubserving/ocr_system`下的`module.py`和`params.py`等文件中根据实际需求修改代码。
228
+
229
+ 例如,如果需要替换部署服务所用模型,则需要到`params.py`中修改模型路径参数`det_model_dir`和`rec_model_dir`,如果需要关闭文本方向分类器,则将参数`use_angle_cls`置为`False`
230
+
231
+ 当然,同时可能还需要修改其他相关参数,请根据实际情况修改调试。
232
+
233
+ **强烈建议修改后先直接运行`module.py`调试,能正确运行预测后再启动服务测试。**
234
+
235
+ **注意:** PPOCR-v3识别模型使用的图片输入shape为`3,48,320`,因此需要修改`params.py`中的`cfg.rec_image_shape = "3, 48, 320"`,如果不使用PPOCR-v3识别模型,则无需修改该参数。
236
+ 3. (可选)如果想要重命名模块需要更改`module.py`文件中的以下行:
237
+ - [`from deploy.hubserving.ocr_system.params import read_params`中的`ocr_system`](https://github.com/PaddlePaddle/PaddleOCR/blob/a923f35de57b5e378f8dd16e54d0a3e4f51267fd/deploy/hubserving/ocr_system/module.py#L35)
238
+ - [`name="ocr_system",`中的`ocr_system`](https://github.com/PaddlePaddle/PaddleOCR/blob/a923f35de57b5e378f8dd16e54d0a3e4f51267fd/deploy/hubserving/ocr_system/module.py#L39)
239
+ 4. (可选)可能需要删除`__pycache__`目录以强制刷新CPython缓存:
240
+ ```bash
241
+ find deploy/hubserving/ocr_system -name '__pycache__' -exec rm -r {} \;
242
+ ```
243
+ 5. 安装修改后的新服务包:
244
+ ```bash
245
+ hub install deploy/hubserving/ocr_system
246
+ ```
247
+ 6. 重新启动服务:
248
+ ```bash
249
+ hub serving start -m ocr_system
250
+ ```
ocr_webapp/PaddleOCR/deploy/hubserving/readme_en.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ English | [简体中文](readme.md)
2
+
3
+ - [Service deployment based on PaddleHub Serving](#service-deployment-based-on-paddlehub-serving)
4
+ - [1. Update](#1-update)
5
+ - [2. Quick start service](#2-quick-start-service)
6
+ - [2.1 Install PaddleHub](#21-install-paddlehub)
7
+ - [2.2 Download inference model](#22-download-inference-model)
8
+ - [2.3 Install Service Module](#23-install-service-module)
9
+ - [2.4 Start service](#24-start-service)
10
+ - [2.4.1 Start with command line parameters (CPU only)](#241-start-with-command-line-parameters-cpu-only)
11
+ - [2.4.2 Start with configuration file(CPU and GPU)](#242-start-with-configuration-filecpugpu)
12
+ - [3. Send prediction requests](#3-send-prediction-requests)
13
+ - [4. Returned result format](#4-returned-result-format)
14
+ - [5. User-defined service module modification](#5-user-defined-service-module-modification)
15
+
16
+ PaddleOCR provides 2 service deployment methods:
17
+ - Based on **PaddleHub Serving**: Code path is `./deploy/hubserving`. Please follow this tutorial.
18
+ - Based on **PaddleServing**: Code path is `./deploy/pdserving`. Please refer to the [tutorial](../../deploy/pdserving/README.md) for usage.
19
+
20
+ # Service deployment based on PaddleHub Serving
21
+
22
+ The hubserving service deployment directory includes seven service packages: text detection, text angle class, text recognition, text detection+text angle class+text recognition three-stage series connection, layout analysis, table recognition, and PP-Structure. Please select the corresponding service package to install and start the service according to your needs. The directory is as follows:
23
+ ```
24
+ deploy/hubserving/
25
+ └─ ocr_det text detection module service package
26
+ └─ ocr_cls text angle class module service package
27
+ └─ ocr_rec text recognition module service package
28
+ └─ ocr_system text detection+text angle class+text recognition three-stage series connection service package
29
+ └─ structure_layout layout analysis service package
30
+ └─ structure_table table recognition service package
31
+ └─ structure_system PP-Structure service package
32
+ └─ kie_ser KIE(SER) service package
33
+ └─ kie_ser_re KIE(SER+RE) service package
34
+ ```
35
+
36
+ Each service pack contains 3 files. Take the 2-stage series connection service package as an example, the directory is as follows:
37
+ ```
38
+ deploy/hubserving/ocr_system/
39
+ └─ __init__.py Empty file, required
40
+ └─ config.json Configuration file, optional, passed in as a parameter when using configuration to start the service
41
+ └─ module.py Main module file, required, contains the complete logic of the service
42
+ └─ params.py Parameter file, required, including parameters such as model path, pre and post-processing parameters
43
+ ```
44
+ ## 1. Update
45
+
46
+ * 2022.10.09 add KIE services.
47
+ * 2022.08.23 add layout analysis services.
48
+ * 2022.03.30 add PP-Structure and table recognition services.
49
+ * 2022.05.05 add PP-OCRv3 text detection and recognition services.
50
+
51
+ ## 2. Quick start service
52
+ The following steps take the 2-stage series service as an example. If only the detection service or recognition service is needed, replace the corresponding file path.
53
+
54
+ ### 2.1 Install PaddleHub
55
+ ```bash
56
+ pip3 install paddlehub==2.1.0 --upgrade
57
+ ```
58
+
59
+ ### 2.2 Download inference model
60
+ Before installing the service module, you need to prepare the inference model and put it in the correct path. By default, the PP-OCRv3 models are used, and the default model path is:
61
+ | Model | Path |
62
+ | ------- | - |
63
+ | text detection model | ./inference/ch_PP-OCRv3_det_infer/ |
64
+ | text recognition model | ./inference/ch_PP-OCRv3_rec_infer/ |
65
+ | text angle classifier | ./inference/ch_ppocr_mobile_v2.0_cls_infer/ |
66
+ | layout parse model | ./inference/picodet_lcnet_x1_0_fgd_layout_infer/ |
67
+ | tanle recognition | ./inference/ch_ppstructure_mobile_v2.0_SLANet_infer/ |
68
+ | KIE(SER) | ./inference/ser_vi_layoutxlm_xfund_infer/ |
69
+ | KIE(SER+RE) | ./inference/re_vi_layoutxlm_xfund_infer/ |
70
+
71
+ **The model path can be found and modified in `params.py`.**
72
+ More models provided by PaddleOCR can be obtained from the [model library](../../doc/doc_en/models_list_en.md). You can also use models trained by yourself.
73
+
74
+ ### 2.3 Install Service Module
75
+ PaddleOCR provides 5 kinds of service modules, install the required modules according to your needs.
76
+
77
+ * On the Linux platform(replace `/` with `\` if using Windows), the examples are as the following table:
78
+ | Service model | Command |
79
+ | text detection | `hub install deploy/hubserving/ocr_det` |
80
+ | text angle class: | `hub install deploy/hubserving/ocr_cls` |
81
+ | text recognition: | `hub install deploy/hubserving/ocr_rec` |
82
+ | 2-stage series: | `hub install deploy/hubserving/ocr_system` |
83
+ | table recognition | `hub install deploy/hubserving/structure_table` |
84
+ | PP-Structure | `hub install deploy/hubserving/structure_system` |
85
+ | KIE(SER) | `hub install deploy/hubserving/kie_ser` |
86
+ | KIE(SER+RE) | `hub install deploy/hubserving/kie_ser_re` |
87
+
88
+ ### 2.4 Start service
89
+ #### 2.4.1 Start with command line parameters (CPU only)
90
+ **start command:**
91
+ ```bash
92
+ hub serving start --modules Module1==Version1, Module2==Version2, ... \
93
+ --port 8866 \
94
+ --use_multiprocess \
95
+ --workers \
96
+ ```
97
+
98
+ **Parameters:**
99
+ |parameters|usage|
100
+ |---|---|
101
+ |`--modules`/`-m`|PaddleHub Serving pre-installed model, listed in the form of multiple Module==Version key-value pairs<br>**When Version is not specified, the latest version is selected by default**|
102
+ |`--port`/`-p`|Service port, default is 8866|
103
+ |`--use_multiprocess`|Enable concurrent mode, by default using the single-process mode, this mode is recommended for multi-core CPU machines<br>**Windows operating system only supports single-process mode**|
104
+ |`--workers`|The number of concurrent tasks specified in concurrent mode, the default is `2*cpu_count-1`, where `cpu_count` is the number of CPU cores|
105
+
106
+ For example, start the 2-stage series service:
107
+ ```bash
108
+ hub serving start -m ocr_system
109
+ ```
110
+
111
+ This completes the deployment of a service API, using the default port number 8866.
112
+
113
+ #### 2.4.2 Start with configuration file(CPU and GPU)
114
+ **start command:**
115
+ ```bash
116
+ hub serving start --config/-c config.json
117
+ ```
118
+
119
+ In which the format of `config.json` is as follows:
120
+ ```json
121
+ {
122
+ "modules_info": {
123
+ "ocr_system": {
124
+ "init_args": {
125
+ "version": "1.0.0",
126
+ "use_gpu": true
127
+ },
128
+ "predict_args": {
129
+ }
130
+ }
131
+ },
132
+ "port": 8868,
133
+ "use_multiprocess": false,
134
+ "workers": 2
135
+ }
136
+ ```
137
+ - The configurable parameters in `init_args` are consistent with the `_initialize` function interface in `module.py`.
138
+
139
+ **When `use_gpu` is `true`, it means that the GPU is used to start the service**.
140
+ - The configurable parameters in `predict_args` are consistent with the `predict` function interface in `module.py`.
141
+
142
+ **Note:**
143
+ - When using the configuration file to start the service, other parameters will be ignored.
144
+ - If you use GPU prediction (that is, `use_gpu` is set to `true`), you need to set the environment variable CUDA_VISIBLE_DEVICES before starting the service, such as:
145
+ ```bash
146
+ export CUDA_VISIBLE_DEVICES=0
147
+ ```
148
+ - **`use_gpu` and `use_multiprocess` cannot be `true` at the same time.**
149
+
150
+ For example, use GPU card No. 3 to start the 2-stage series service:
151
+ ```bash
152
+ export CUDA_VISIBLE_DEVICES=3
153
+ hub serving start -c deploy/hubserving/ocr_system/config.json
154
+ ```
155
+
156
+ ## 3. Send prediction requests
157
+ After the service starts, you can use the following command to send a prediction request to obtain the prediction result:
158
+ ```bash
159
+ python tools/test_hubserving.py --server_url=server_url --image_dir=image_path
160
+ ```
161
+
162
+ Two parameters need to be passed to the script:
163
+ - **server_url**:service address, the format of which is
164
+ `http://[ip_address]:[port]/predict/[module_name]`
165
+
166
+ For example, if using the configuration file to start the text angle classification, text detection, text recognition, detection+classification+recognition 3 stages, table recognition and PP-Structure service,
167
+
168
+ also modified the port for each service, then the `server_url` to send the request will be:
169
+
170
+ ```
171
+ http://127.0.0.1:8865/predict/ocr_det
172
+ http://127.0.0.1:8866/predict/ocr_cls
173
+ http://127.0.0.1:8867/predict/ocr_rec
174
+ http://127.0.0.1:8868/predict/ocr_system
175
+ http://127.0.0.1:8869/predict/structure_table
176
+ http://127.0.0.1:8870/predict/structure_system
177
+ http://127.0.0.1:8870/predict/structure_layout
178
+ http://127.0.0.1:8871/predict/kie_ser
179
+ http://127.0.0.1:8872/predict/kie_ser_re
180
+ ```
181
+ - **image_dir**:Test image path, which can be a single image path or an image directory path
182
+ - **visualize**:Whether to visualize the results, the default value is False
183
+ - **output**:The folder to save the Visualization result, the default value is `./hubserving_result`
184
+
185
+ Example:
186
+ ```bash
187
+ python tools/test_hubserving.py --server_url=http://127.0.0.1:8868/predict/ocr_system --image_dir=./doc/imgs/ --visualize=false`
188
+ ```
189
+
190
+ ## 4. Returned result format
191
+ The returned result is a list. Each item in the list is a dictionary which may contain three fields. The information is as follows:
192
+
193
+ |field name|data type|description|
194
+ |----|----|----|
195
+ |angle|str|angle|
196
+ |text|str|text content|
197
+ |confidence|float|text recognition confidence|
198
+ |text_region|list|text location coordinates|
199
+ |html|str|table HTML string|
200
+ |regions|list|The result of layout analysis + table recognition + OCR, each item is a list<br>including `bbox` indicating area coordinates, `type` of area type and `res` of area results|
201
+ |layout|list|The result of layout analysis, each item is a dict, including `bbox` indicating area coordinates, `label` of area type|
202
+
203
+ The fields returned by different modules are different. For example, the results returned by the text recognition service module do not contain `text_region`, detailed table is as follows:
204
+
205
+ |field name/module name |ocr_det |ocr_cls |ocr_rec |ocr_system |structure_table |structure_system |structure_layout |kie_ser |kie_re |
206
+ |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
207
+ |angle | |✔ | |✔ | | | |
208
+ |text | | |✔ |✔ | |✔ | |✔ |✔ |
209
+ |confidence | |✔ |✔ |✔ | |✔ | |✔ |✔ |
210
+ |text_region |✔ | | |✔ | |✔ | |✔ |✔ |
211
+ |html | | | | |✔ |✔ | | | |
212
+ |regions | | | | |✔ |✔ | | | |
213
+ |layout | | | | | | |✔ | | |
214
+ |ser_res | | | | | | | |✔ | |
215
+ |re_res | | | | | | | | |✔ |
216
+
217
+ **Note:** If you need to add, delete or modify the returned fields, you can modify the file `module.py` of the corresponding module. For the complete process, refer to the user-defined modification service module in the next section.
218
+
219
+ ## 5. User-defined service module modification
220
+ If you need to modify the service logic, the following steps are generally required (take the modification of `deploy/hubserving/ocr_system` for example):
221
+
222
+ 1. Stop service:
223
+ ```bash
224
+ hub serving stop --port/-p XXXX
225
+ ```
226
+ 2. Modify the code in the corresponding files under `deploy/hubserving/ocr_system`, such as `module.py` and `params.py`, to your actual needs.
227
+
228
+ For example, if you need to replace the model used by the deployed service, you need to modify model path parameters `det_model_dir` and `rec_model_dir` in `params.py`. If you want to turn off the text direction classifier, set the parameter `use_angle_cls` to `False`.
229
+
230
+ Of course, other related parameters may need to be modified at the same time. Please modify and debug according to the actual situation.
231
+
232
+ **It is suggested to run `module.py` directly for debugging after modification before starting the service test.**
233
+
234
+ **Note** The image input shape used by the PPOCR-v3 recognition model is `3, 48, 320`, so you need to modify `cfg.rec_image_shape = "3, 48, 320"` in `params.py`, if you do not use the PPOCR-v3 recognition model, then there is no need to modify this parameter.
235
+ 3. (Optional) If you want to rename the module, the following lines should be modified:
236
+ - [`ocr_system` within `from deploy.hubserving.ocr_system.params import read_params`](https://github.com/PaddlePaddle/PaddleOCR/blob/a923f35de57b5e378f8dd16e54d0a3e4f51267fd/deploy/hubserving/ocr_system/module.py#L35)
237
+ - [`ocr_system` within `name="ocr_system",`](https://github.com/PaddlePaddle/PaddleOCR/blob/a923f35de57b5e378f8dd16e54d0a3e4f51267fd/deploy/hubserving/ocr_system/module.py#L39)
238
+ 4. (Optional) It may require you to delete the directory `__pycache__` to force flush build cache of CPython:
239
+ ```bash
240
+ find deploy/hubserving/ocr_system -name '__pycache__' -exec rm -r {} \;
241
+ ```
242
+ 5. Install modified service module:
243
+ ```bash
244
+ hub install deploy/hubserving/ocr_system/
245
+ ```
246
+ 6. Restart service:
247
+ ```bash
248
+ hub serving start -m ocr_system
249
+ ```
ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "structure_layout": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8871,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/module.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import paddlehub as hub
30
+
31
+ from tools.infer.utility import base64_to_cv2
32
+ from ppstructure.layout.predict_layout import LayoutPredictor as _LayoutPredictor
33
+ from ppstructure.utility import parse_args
34
+ from deploy.hubserving.structure_layout.params import read_params
35
+
36
+
37
+ @moduleinfo(
38
+ name="structure_layout",
39
+ version="1.0.0",
40
+ summary="PP-Structure layout service",
41
+ author="paddle-dev",
42
+ author_email="paddle-dev@baidu.com",
43
+ type="cv/structure_layout")
44
+ class LayoutPredictor(hub.Module):
45
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
46
+ """
47
+ initialize with the necessary elements
48
+ """
49
+ cfg = self.merge_configs()
50
+ cfg.use_gpu = use_gpu
51
+ if use_gpu:
52
+ try:
53
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
54
+ int(_places[0])
55
+ print("use gpu: ", use_gpu)
56
+ print("CUDA_VISIBLE_DEVICES: ", _places)
57
+ cfg.gpu_mem = 8000
58
+ except:
59
+ raise RuntimeError(
60
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
61
+ )
62
+ cfg.ir_optim = True
63
+ cfg.enable_mkldnn = enable_mkldnn
64
+
65
+ self.layout_predictor = _LayoutPredictor(cfg)
66
+
67
+ def merge_configs(self):
68
+ # deafult cfg
69
+ backup_argv = copy.deepcopy(sys.argv)
70
+ sys.argv = sys.argv[:1]
71
+ cfg = parse_args()
72
+
73
+ update_cfg_map = vars(read_params())
74
+
75
+ for key in update_cfg_map:
76
+ cfg.__setattr__(key, update_cfg_map[key])
77
+
78
+ sys.argv = copy.deepcopy(backup_argv)
79
+ return cfg
80
+
81
+ def read_images(self, paths=[]):
82
+ images = []
83
+ for img_path in paths:
84
+ assert os.path.isfile(
85
+ img_path), "The {} isn't a valid file.".format(img_path)
86
+ img = cv2.imread(img_path)
87
+ if img is None:
88
+ logger.info("error in loading image:{}".format(img_path))
89
+ continue
90
+ images.append(img)
91
+ return images
92
+
93
+ def predict(self, images=[], paths=[]):
94
+ """
95
+ Get the chinese texts in the predicted images.
96
+ Args:
97
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
98
+ paths (list[str]): The paths of images. If paths not images
99
+ Returns:
100
+ res (list): The layout results of images.
101
+ """
102
+
103
+ if images != [] and isinstance(images, list) and paths == []:
104
+ predicted_data = images
105
+ elif images == [] and isinstance(paths, list) and paths != []:
106
+ predicted_data = self.read_images(paths)
107
+ else:
108
+ raise TypeError("The input data is inconsistent with expectations.")
109
+
110
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
111
+
112
+ all_results = []
113
+ for img in predicted_data:
114
+ if img is None:
115
+ logger.info("error in loading image")
116
+ all_results.append([])
117
+ continue
118
+ starttime = time.time()
119
+ res, _ = self.layout_predictor(img)
120
+ elapse = time.time() - starttime
121
+ logger.info("Predict time: {}".format(elapse))
122
+
123
+ for item in res:
124
+ item['bbox'] = item['bbox'].tolist()
125
+ all_results.append({'layout': res})
126
+ return all_results
127
+
128
+ @serving
129
+ def serving_method(self, images, **kwargs):
130
+ """
131
+ Run as a service.
132
+ """
133
+ images_decode = [base64_to_cv2(image) for image in images]
134
+ results = self.predict(images_decode, **kwargs)
135
+ return results
136
+
137
+
138
+ if __name__ == '__main__':
139
+ layout = LayoutPredictor()
140
+ layout._initialize()
141
+ image_path = ['./ppstructure/docs/table/1.png']
142
+ res = layout.predict(paths=image_path)
143
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/structure_layout/params.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+
20
+ class Config(object):
21
+ pass
22
+
23
+
24
+ def read_params():
25
+ cfg = Config()
26
+
27
+ # params for layout analysis
28
+ cfg.layout_model_dir = './inference/picodet_lcnet_x1_0_fgd_layout_infer/'
29
+ cfg.layout_dict_path = './ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt'
30
+ cfg.layout_score_threshold = 0.5
31
+ cfg.layout_nms_threshold = 0.5
32
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "structure_system": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8870,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/module.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import numpy as np
30
+ import paddlehub as hub
31
+
32
+ from tools.infer.utility import base64_to_cv2
33
+ from ppstructure.predict_system import StructureSystem as PPStructureSystem
34
+ from ppstructure.predict_system import save_structure_res
35
+ from ppstructure.utility import parse_args
36
+ from deploy.hubserving.structure_system.params import read_params
37
+
38
+
39
+ @moduleinfo(
40
+ name="structure_system",
41
+ version="1.0.0",
42
+ summary="PP-Structure system service",
43
+ author="paddle-dev",
44
+ author_email="paddle-dev@baidu.com",
45
+ type="cv/structure_system")
46
+ class StructureSystem(hub.Module):
47
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
48
+ """
49
+ initialize with the necessary elements
50
+ """
51
+ cfg = self.merge_configs()
52
+
53
+ cfg.use_gpu = use_gpu
54
+ if use_gpu:
55
+ try:
56
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
57
+ int(_places[0])
58
+ print("use gpu: ", use_gpu)
59
+ print("CUDA_VISIBLE_DEVICES: ", _places)
60
+ cfg.gpu_mem = 8000
61
+ except:
62
+ raise RuntimeError(
63
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
64
+ )
65
+ cfg.ir_optim = True
66
+ cfg.enable_mkldnn = enable_mkldnn
67
+
68
+ self.table_sys = PPStructureSystem(cfg)
69
+
70
+ def merge_configs(self):
71
+ # deafult cfg
72
+ backup_argv = copy.deepcopy(sys.argv)
73
+ sys.argv = sys.argv[:1]
74
+ cfg = parse_args()
75
+
76
+ update_cfg_map = vars(read_params())
77
+
78
+ for key in update_cfg_map:
79
+ cfg.__setattr__(key, update_cfg_map[key])
80
+
81
+ sys.argv = copy.deepcopy(backup_argv)
82
+ return cfg
83
+
84
+ def read_images(self, paths=[]):
85
+ images = []
86
+ for img_path in paths:
87
+ assert os.path.isfile(
88
+ img_path), "The {} isn't a valid file.".format(img_path)
89
+ img = cv2.imread(img_path)
90
+ if img is None:
91
+ logger.info("error in loading image:{}".format(img_path))
92
+ continue
93
+ images.append(img)
94
+ return images
95
+
96
+ def predict(self, images=[], paths=[]):
97
+ """
98
+ Get the chinese texts in the predicted images.
99
+ Args:
100
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
101
+ paths (list[str]): The paths of images. If paths not images
102
+ Returns:
103
+ res (list): The result of chinese texts and save path of images.
104
+ """
105
+
106
+ if images != [] and isinstance(images, list) and paths == []:
107
+ predicted_data = images
108
+ elif images == [] and isinstance(paths, list) and paths != []:
109
+ predicted_data = self.read_images(paths)
110
+ else:
111
+ raise TypeError("The input data is inconsistent with expectations.")
112
+
113
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
114
+
115
+ all_results = []
116
+ for img in predicted_data:
117
+ if img is None:
118
+ logger.info("error in loading image")
119
+ all_results.append([])
120
+ continue
121
+ starttime = time.time()
122
+ res, _ = self.table_sys(img)
123
+ elapse = time.time() - starttime
124
+ logger.info("Predict time: {}".format(elapse))
125
+
126
+ # parse result
127
+ res_final = []
128
+ for region in res:
129
+ region.pop('img')
130
+ res_final.append(region)
131
+ all_results.append({'regions': res_final})
132
+ return all_results
133
+
134
+ @serving
135
+ def serving_method(self, images, **kwargs):
136
+ """
137
+ Run as a service.
138
+ """
139
+ images_decode = [base64_to_cv2(image) for image in images]
140
+ results = self.predict(images_decode, **kwargs)
141
+ return results
142
+
143
+
144
+ if __name__ == '__main__':
145
+ structure_system = StructureSystem()
146
+ structure_system._initialize()
147
+ image_path = ['./ppstructure/docs/table/1.png']
148
+ res = structure_system.predict(paths=image_path)
149
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/structure_system/params.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ from deploy.hubserving.structure_table.params import read_params as table_read_params
20
+
21
+
22
+ def read_params():
23
+ cfg = table_read_params()
24
+
25
+ # params for layout parser model
26
+ cfg.layout_model_dir = ''
27
+ cfg.layout_dict_path = './ppocr/utils/dict/layout_publaynet_dict.txt'
28
+ cfg.layout_score_threshold = 0.5
29
+ cfg.layout_nms_threshold = 0.5
30
+
31
+ cfg.mode = 'structure'
32
+ cfg.output = './output'
33
+ return cfg
ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules_info": {
3
+ "structure_table": {
4
+ "init_args": {
5
+ "version": "1.0.0",
6
+ "use_gpu": true
7
+ },
8
+ "predict_args": {
9
+ }
10
+ }
11
+ },
12
+ "port": 8869,
13
+ "use_multiprocess": false,
14
+ "workers": 2
15
+ }
16
+
ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/module.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ import os
20
+ import sys
21
+ sys.path.insert(0, ".")
22
+ import copy
23
+
24
+ import time
25
+ import paddlehub
26
+ from paddlehub.common.logger import logger
27
+ from paddlehub.module.module import moduleinfo, runnable, serving
28
+ import cv2
29
+ import numpy as np
30
+ import paddlehub as hub
31
+
32
+ from tools.infer.utility import base64_to_cv2
33
+ from ppstructure.table.predict_table import TableSystem as _TableSystem
34
+ from ppstructure.predict_system import save_structure_res
35
+ from ppstructure.utility import parse_args
36
+ from deploy.hubserving.structure_table.params import read_params
37
+
38
+
39
+ @moduleinfo(
40
+ name="structure_table",
41
+ version="1.0.0",
42
+ summary="PP-Structure table service",
43
+ author="paddle-dev",
44
+ author_email="paddle-dev@baidu.com",
45
+ type="cv/structure_table")
46
+ class TableSystem(hub.Module):
47
+ def _initialize(self, use_gpu=False, enable_mkldnn=False):
48
+ """
49
+ initialize with the necessary elements
50
+ """
51
+ cfg = self.merge_configs()
52
+ cfg.use_gpu = use_gpu
53
+ if use_gpu:
54
+ try:
55
+ _places = os.environ["CUDA_VISIBLE_DEVICES"]
56
+ int(_places[0])
57
+ print("use gpu: ", use_gpu)
58
+ print("CUDA_VISIBLE_DEVICES: ", _places)
59
+ cfg.gpu_mem = 8000
60
+ except:
61
+ raise RuntimeError(
62
+ "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
63
+ )
64
+ cfg.ir_optim = True
65
+ cfg.enable_mkldnn = enable_mkldnn
66
+
67
+ self.table_sys = _TableSystem(cfg)
68
+
69
+ def merge_configs(self):
70
+ # deafult cfg
71
+ backup_argv = copy.deepcopy(sys.argv)
72
+ sys.argv = sys.argv[:1]
73
+ cfg = parse_args()
74
+
75
+ update_cfg_map = vars(read_params())
76
+
77
+ for key in update_cfg_map:
78
+ cfg.__setattr__(key, update_cfg_map[key])
79
+
80
+ sys.argv = copy.deepcopy(backup_argv)
81
+ return cfg
82
+
83
+ def read_images(self, paths=[]):
84
+ images = []
85
+ for img_path in paths:
86
+ assert os.path.isfile(
87
+ img_path), "The {} isn't a valid file.".format(img_path)
88
+ img = cv2.imread(img_path)
89
+ if img is None:
90
+ logger.info("error in loading image:{}".format(img_path))
91
+ continue
92
+ images.append(img)
93
+ return images
94
+
95
+ def predict(self, images=[], paths=[]):
96
+ """
97
+ Get the chinese texts in the predicted images.
98
+ Args:
99
+ images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
100
+ paths (list[str]): The paths of images. If paths not images
101
+ Returns:
102
+ res (list): The result of chinese texts and save path of images.
103
+ """
104
+
105
+ if images != [] and isinstance(images, list) and paths == []:
106
+ predicted_data = images
107
+ elif images == [] and isinstance(paths, list) and paths != []:
108
+ predicted_data = self.read_images(paths)
109
+ else:
110
+ raise TypeError("The input data is inconsistent with expectations.")
111
+
112
+ assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
113
+
114
+ all_results = []
115
+ for img in predicted_data:
116
+ if img is None:
117
+ logger.info("error in loading image")
118
+ all_results.append([])
119
+ continue
120
+ starttime = time.time()
121
+ res, _ = self.table_sys(img)
122
+ elapse = time.time() - starttime
123
+ logger.info("Predict time: {}".format(elapse))
124
+
125
+ all_results.append({'html': res['html']})
126
+ return all_results
127
+
128
+ @serving
129
+ def serving_method(self, images, **kwargs):
130
+ """
131
+ Run as a service.
132
+ """
133
+ images_decode = [base64_to_cv2(image) for image in images]
134
+ results = self.predict(images_decode, **kwargs)
135
+ return results
136
+
137
+
138
+ if __name__ == '__main__':
139
+ table_system = TableSystem()
140
+ table_system._initialize()
141
+ image_path = ['./ppstructure/docs/table/table.jpg']
142
+ res = table_system.predict(paths=image_path)
143
+ print(res)
ocr_webapp/PaddleOCR/deploy/hubserving/structure_table/params.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import absolute_import
16
+ from __future__ import division
17
+ from __future__ import print_function
18
+
19
+ from deploy.hubserving.ocr_system.params import read_params as pp_ocr_read_params
20
+
21
+
22
+ def read_params():
23
+ cfg = pp_ocr_read_params()
24
+
25
+ # params for table structure model
26
+ cfg.table_max_len = 488
27
+ cfg.table_model_dir = './inference/en_ppocr_mobile_v2.0_table_structure_infer/'
28
+ cfg.table_char_dict_path = './ppocr/utils/dict/table_structure_dict.txt'
29
+ cfg.show_log = False
30
+ return cfg
ocr_webapp/PaddleOCR/deploy/ios_demo/.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CocoaPods
2
+ Pods/
3
+
4
+ # Xcode
5
+ PaddleOCRDemo.xcworkspace/xcuserdata/
6
+ PaddleOCRDemo.xcodeproj/xcuserdata/
7
+ PaddleOCRDemo.xcodeproj/project.xcworkspace/xcuserdata/
8
+ *.xcuserstate
9
+ DerivedData/
10
+ build/
11
+
12
+ # fetch_ios_demo_models.sh download cache
13
+ .fetch_ios_demo_models_work/
14
+
15
+ # Models — ignore all files under Models/; track only `.gitkeep` so det/, rec/, … stay in the tree
16
+ PaddleOCRDemo/Models/**
17
+ !PaddleOCRDemo/Models/*/
18
+ !PaddleOCRDemo/Models/*/.gitkeep
19
+
20
+ # Local validation reports
21
+ out/
ocr_webapp/PaddleOCR/deploy/ios_demo/NOTICE ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PaddleOCR iOS demo — third-party notices
2
+ ===============================================================================
3
+
4
+ This demo application is part of the PaddleOCR project (Apache License 2.0).
5
+ It may bundle or link third-party components in addition to the PaddleOCR
6
+ repository LICENSE. The following components are included in **source** form
7
+ in this tree:
8
+
9
+ Clipper / polyclipping (polygon clipping and offsetting)
10
+ --------------------------------------------------------------------------------------------
11
+ • Upstream: polyclipping clipper 6.4.2 (Angus Johnson)
12
+ • Bundled: `PaddleOCRDemo/ThirdParty/Clipper1/` (clipper.cpp, clipper.hpp)
13
+ • SPDX: BSL-1.0 (Boost Software License 1.0)
14
+ • Full text: `PaddleOCRDemo/ThirdParty/Clipper1/LICENSE`
15
+
16
+ CocoaPods dependencies (onnxruntime-objc, OpenCV, Yams, etc.)
17
+ -------------------------------------------------------------
18
+ • Versions and upstream packages are recorded in `Podfile.lock` after
19
+ `pod install`. Each pod is subject to its own license as published by
20
+ the respective project; consult the Pods project and upstream repos
21
+ for notices required by those licenses.
22
+
23
+ If you distribute binaries built from this demo, ensure your product’s
24
+ open-source / third-party attribution (e.g. in-app “Licenses” or
25
+ distribution packaging) satisfies your legal and policy requirements.