Skip to content

📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

Add rapid table module

SWHLbe434b228ac1
diff --git a/python/rapid_structure/README.md b/python/rapid_structure/README.md
index 0cdd090..ccc5ce5 100644
--- a/python/rapid_structure/README.md
+++ b/python/rapid_structure/README.md
@@ -2,57 +2,6 @@
- 模型和推理代码均来自于[PP-Structure](https://github.com/PaddlePaddle/PaddleOCR/blob/release%2F2.6/ppstructure/README_ch.md#32)部分。
- 该部分的功能主要针对文档类图像,包括版面分析和表格识别两类。
-#### Rapid Layout
-<p align="left">
- <a href=""><img src="https://img.shields.io/badge/Python->=3.7,<=3.10-aff.svg"></a>
- <a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
- <a href="https://pypi.org/project/rapid-layout/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapid-layout?style=plastic"></a>
-</p>
+### [Rapid Layout](./docs/README_Layout.md)
-##### 简介和说明
-- 该部分主要是做文档类图像的版面分析。具体来说,就是分析给定的文档类别图像(论文截图等),定位其中类别和位置,如标题、段落、表格和图片等各个部分。
-- 目前支持三种类别的版面分析模型:中文、英文和表格版面分析模型,具体可参见下面表格:
-
- | 模型类型 | 模型名称 | 模型大小 | 支持种类 |
- |:---:|:---:|:---:|:---:|
- | 表格 | `layout_table.onnx` | 7.06M | `table` |
- | 英文 | `layout_publaynet.onnx` | 7.06M | `text title list table figure` |
- | 中文 | `layout_cdla.onnx` | 7.07M | `text title figure figure_caption table table_caption` <br> `header footer reference equation` |
-- 模型下载地址为:[百度网盘](https://pan.baidu.com/s/1PI9fksW6F6kQfJhwUkewWg?pwd=p29g) | [Google Drive](https://drive.google.com/drive/folders/1DAPWSN2zGQ-ED_Pz7RaJGTjfkN2-Mvsf?usp=sharing)
-
-#### 使用方式
-1. pip安装
- - 由于模型较小,预先将中文版面分析模型(`layout_cdla.onnx`)打包进了whl包内,如果做中文版面分析,可直接安装使用
- ```bash
- $ pip install rapid-layout
- ```
-2. python脚本运行
- ```python
- import cv2
- from rapid_layout import RapidLayout
-
- layout_engine = RapidLayout()
-
- img = cv2.imread('test_images/ch.png')
-
- layout_res, elapse = layout_engine(img)
- ```
-3. 终端运行
- ```bash
- # 假设在rapid_structure目录下
- $ rapid_layout --img_path test_images/ch.png
- ```
-4. 结果
- - 返回结果
- ```python
- # bbox: [左上角x0,左上角y0, 右下角x0, 右上角x1]
- # label: 类别
- [
- {'bbox': array([321.4160495, 91.53214898, 562.06141263, 199.85522603]), 'label': 'text'},
- {'bbox': array([58.67292211, 107.29000663, 300.25448676, 199.68142]), 'label': 'table_caption'}
- ]
- ```
- - 可视化结果
- <div align="center">
- <img src="./test_images/layout_result.jpg" width="80%" height="80%">
- </div>
+### [Rapid Table](./docs/README_Table.md)
diff --git a/python/rapid_structure/demo.py b/python/rapid_structure/demo.py
index daa28f9..913b202 100644
--- a/python/rapid_structure/demo.py
+++ b/python/rapid_structure/demo.py
@@ -7,6 +7,7 @@ from pathlib import Path
import cv2
import numpy as np
from rapid_layout import RapidLayout
+from rapid_table import RapidTable
def vis_layout(img: np.ndarray, layout_res: list) -> None:
@@ -31,15 +32,45 @@ def vis_layout(img: np.ndarray, layout_res: list) -> None:
print(f'The infer result has saved in {image_save}')
-if __name__ == '__main__':
+def vis_table(table_res):
+ style_res = '''<style>td {border-left: 1px solid;border-bottom:1px solid;}
+ table, th {border-top:1px solid;font-size: 10px;
+ border-collapse: collapse;border-right: 1px solid;}
+ </style>'''
+ prefix_table, suffix_table = table_res.split('<body>')
+ new_table_res = f'{prefix_table}{style_res}<body>{suffix_table}'
+
+ draw_img_save = Path("./inference_results/")
+ if not draw_img_save.exists():
+ draw_img_save.mkdir(parents=True, exist_ok=True)
+
+ html_path = str(draw_img_save / 'table_result.html')
+ with open(html_path, 'w', encoding='utf-8') as f:
+ f.write(new_table_res)
+ print(f'The infer result has saved in {html_path}')
+
+
+def demo_layout():
model_path = 'rapid_layout/models/layout_cdla.onnx'
layout_engine = RapidLayout(model_path)
- img_path = 'test_images/ch.png'
+ img = cv2.imread('test_images/layout.png')
- img = cv2.imread(img_path)
-
- layout_res, elapse = layout_engine(img)
+ layout_res, _ = layout_engine(img)
vis_layout(img, layout_res)
print(layout_res)
+
+
+def demo_table():
+ rapid_table = RapidTable()
+ img = cv2.imread('test_images/table.jpg')
+ table_html_str, _ = rapid_table(img)
+
+ vis_table(table_html_str)
+ print(table_html_str)
+
+
+if __name__ == '__main__':
+ # demo_layout()
+ demo_table()
diff --git a/python/rapid_structure/docs/README_Layout.md b/python/rapid_structure/docs/README_Layout.md
new file mode 100644
index 0000000..16b0a4d
--- /dev/null
+++ b/python/rapid_structure/docs/README_Layout.md
@@ -0,0 +1,55 @@
+## Rapid Layout
+<p align="left">
+ <a href=""><img src="https://img.shields.io/badge/Python->=3.7,<=3.10-aff.svg"></a>
+ <a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
+ <a href="https://pypi.org/project/rapid-layout/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapid-layout?style=plastic"></a>
+</p>
+
+##### 简介和说明
+- 该部分主要是做文档类图像的版面分析。
+- 具体来说,就是分析给定的文档类别图像(论文截图等),定位其中类别和位置,如标题、段落、表格和图片等各个部分。
+- 目前支持三种类别的版面分析模型:中文、英文和表格版面分析模型,具体可参见下面表格:
+
+ | 模型类型 | 模型名称 | 模型大小 | 支持种类 |
+ |:---:|:---:|:---:|:---:|
+ | 表格 | `layout_table.onnx` | 7.06M | `table` |
+ | 英文 | `layout_publaynet.onnx` | 7.06M | `text title list table figure` |
+ | 中文 | `layout_cdla.onnx` | 7.07M | `text title figure figure_caption table table_caption` <br> `header footer reference equation` |
+- 模型下载地址为:[百度网盘](https://pan.baidu.com/s/1PI9fksW6F6kQfJhwUkewWg?pwd=p29g) | [Google Drive](https://drive.google.com/drive/folders/1DAPWSN2zGQ-ED_Pz7RaJGTjfkN2-Mvsf?usp=sharing)
+
+#### 使用方式
+1. pip安装
+ - 由于模型较小,预先将中文版面分析模型(`layout_cdla.onnx`)打包进了whl包内,如果做中文版面分析,可直接安装使用
+ ```bash
+ $ pip install rapid-layout
+ ```
+2. python脚本运行
+ ```python
+ import cv2
+ from rapid_layout import RapidLayout
+
+ layout_engine = RapidLayout()
+
+ img = cv2.imread('test_images/layout.png')
+
+ layout_res, elapse = layout_engine(img)
+ ```
+3. 终端运行
+ ```bash
+ # 假设在rapid_structure目录下
+ $ rapid_layout --img_path test_images/ch.png
+ ```
+4. 结果
+ - 返回结果
+ ```python
+ # bbox: [左上角x0,左上角y0, 右下角x0, 右上角x1]
+ # label: 类别
+ [
+ {'bbox': array([321.4160495, 91.53214898, 562.06141263, 199.85522603]), 'label': 'text'},
+ {'bbox': array([58.67292211, 107.29000663, 300.25448676, 199.68142]), 'label': 'table_caption'}
+ ]
+ ```
+ - 可视化结果
+ <div align="center">
+ <img src="./test_images/layout_result.jpg" width="80%" height="80%">
+ </div>
diff --git a/python/rapid_structure/docs/README_Table.md b/python/rapid_structure/docs/README_Table.md
new file mode 100644
index 0000000..bc07a80
--- /dev/null
+++ b/python/rapid_structure/docs/README_Table.md
@@ -0,0 +1,49 @@
+## Rapid Table
+<p align="left">
+ <a href=""><img src="https://img.shields.io/badge/Python->=3.7,<=3.10-aff.svg"></a>
+ <a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
+ <a href="https://pypi.org/project/rapid-table/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapid-table?style=plastic"></a>
+</p>
+
+##### 简介和说明
+- 该部分主要是做文档类图像的表格结构还原。
+- 具体来说,就是分析给定的表格图像,将表格还原为对应的html格式。
+- 目前支持两种类别的表格识别模型:中文和英文表格识别模型,具体可参见下面表格:
+
+ | 模型类型 | 模型名称 | 模型大小 |
+ |:---:|:---:|:---:|
+ | 英文 | `en_ppstructure_mobile_v2_SLANet.onnx` | 7.3M |
+ | 中文 | `ch_ppstructure_mobile_v2_SLANet.onnx` | 7.4M |
+- 模型下载地址为:[百度网盘](https://pan.baidu.com/s/1PI9fksW6F6kQfJhwUkewWg?pwd=p29g) | [Google Drive](https://drive.google.com/drive/folders/1DAPWSN2zGQ-ED_Pz7RaJGTjfkN2-Mvsf?usp=sharing)
+
+#### 使用方式
+1. pip安装
+ - 由于模型较小,预先将英文表格识别模型(`en_ppstructure_mobile_v2_SLANet.onnx`)打包进了whl包内,如果做英文表格识别,可直接安装使用
+ ```bash
+ $ pip install rapid-table
+ ```
+2. python脚本运行
+ ```python
+ import cv2
+ from rapid_table import RapidTable
+
+ rapid_table = RapidTable()
+
+ img = cv2.imread('test_images/table.jpg')
+ table_html_str, _ = rapid_table(img)
+ print(table_html_str)
+ ```
+3. 终端运行
+ ```bash
+ # 假设在rapid_structure目录下
+ $ rapid_talbe --img_path test_images/table.jpg
+ ```
+4. 结果
+ - 返回结果
+ ```html
+ <html><body><table><thead><tr><td>Methods</td><td></td><td></td><td></td><td>FPS</td></tr></thead><tbody><tr><td>SegLink [26]</td><td>70.0</td><td>86d><td.0</td><td>77.0</td><td>8.9</td></tr><tr><td>PixelLink [4]</td><td>73.2</td><td>83.0</td><td>77.8</td><td></td></tr><tr><td>TextSnake [18]</td><td>73.9</td><td>83.2</td><td>78.3</td><td>1.1</td></tr><tr><td>TextField [37]</td><td>75.9</td><td>87.4</td><td>81.3</td><td>5.2</td></tr><tr><td>MSR[38]</td><td>76.7</td><td>87.87.4</td><td>81.7</td><td></td></tr><tr><td>FTSN [3]</td><td>77.1</td><td>87.6</td><td>82.0</td><td></td></tr><tr><td>LSE[30]</td><td>81.7</td><td>84.2</td><td>82.9</td><><ttd></td></tr><tr><td>CRAFT [2]</td><td>78.2</td><td>88.2</td><td>82.9</td><td>8.6</td></tr><tr><td>MCN[16]</td><td>79</td><td>88</td><td>83</td><td></td></tr><tr><td>ATRR</>[35]</td><td>82.1</td><td>85.2</td><td>83.6</td><td></td></tr><tr><td>PAN [34]</td><td>83.8</td><td>84.4</td><td>84.1</td><td>30.2</td></tr><tr><td>DB[12]</td><td>79.2</t91/d><td>91.5</td><td>84.9</td><td>32.0</td></tr><tr><td>DRRG[41]</td><td>82.30</td><td>88.05</td><td>85.08</td><td></td></tr><tr><td>Ours (SynText)</td><td>80.68</td><td>85<t..40</td><td>82.97</td><td>12.68</td></tr><tr><td>Ours (MLT-17)</td><td>84.54</td><td>86.62</td><td>85.57</td><td>12.31</td></tr></tbody></table></body></html>
+ ```
+ - 可视化结果
+ <div align="center">
+ <table><thead><tr><td>Methods</td><td></td><td></td><td></td><td>FPS</td></tr></thead><tbody><tr><td>SegLink [26]</td><td>70.0</td><td>86d><td.0</td><td>77.0</td><td>8.9</td></tr><tr><td>PixelLink [4]</td><td>73.2</td><td>83.0</td><td>77.8</td><td></td></tr><tr><td>TextSnake [18]</td><td>73.9</td><td>83.2</td><td>78.3</td><td>1.1</td></tr><tr><td>TextField [37]</td><td>75.9</td><td>87.4</td><td>81.3</td><td>5.2</td></tr><tr><td>MSR[38]</td><td>76.7</td><td>87.87.4</td><td>81.7</td><td></td></tr><tr><td>FTSN [3]</td><td>77.1</td><td>87.6</td><td>82.0</td><td></td></tr><tr><td>LSE[30]</td><td>81.7</td><td>84.2</td><td>82.9</td><><ttd></td></tr><tr><td>CRAFT [2]</td><td>78.2</td><td>88.2</td><td>82.9</td><td>8.6</td></tr><tr><td>MCN[16]</td><td>79</td><td>88</td><td>83</td><td></td></tr><tr><td>ATRR</>[35]</td><td>82.1</td><td>85.2</td><td>83.6</td><td></td></tr><tr><td>PAN [34]</td><td>83.8</td><td>84.4</td><td>84.1</td><td>30.2</td></tr><tr><td>DB[12]</td><td>79.2</t91/d><td>91.5</td><td>84.9</td><td>32.0</td></tr><tr><td>DRRG[41]</td><td>82.30</td><td>88.05</td><td>85.08</td><td></td></tr><tr><td>Ours (SynText)</td><td>80.68</td><td>85<t..40</td><td>82.97</td><td>12.68</td></tr><tr><td>Ours (MLT-17)</td><td>84.54</td><td>86.62</td><td>85.57</td><td>12.31</td></tr></tbody></table>
+ </div>
\ No newline at end of file
diff --git a/python/rapid_structure/rapid_layout/rapid_layout.py b/python/rapid_structure/rapid_layout/rapid_layout.py
index 9dca399..b7c29b8 100644
--- a/python/rapid_structure/rapid_layout/rapid_layout.py
+++ b/python/rapid_structure/rapid_layout/rapid_layout.py
@@ -21,7 +21,7 @@ from .utils import (OrtInferSession, PicoDetPostProcess, create_operators,
root_dir = Path(__file__).resolve().parent
-class RapidLayout(object):
+class RapidLayout():
def __init__(self,
model_path: str = None):
config_path = str(root_dir / 'config.yaml')
diff --git a/python/rapid_structure/rapid_table/__init__.py b/python/rapid_structure/rapid_table/__init__.py
new file mode 100644
index 0000000..e4a5ed5
--- /dev/null
+++ b/python/rapid_structure/rapid_table/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .rapid_table import RapidTable
diff --git a/python/rapid_structure/rapid_table/models/.gitkeep b/python/rapid_structure/rapid_table/models/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/python/rapid_structure/rapid_table/rapid_table.py b/python/rapid_structure/rapid_table/rapid_table.py
new file mode 100644
index 0000000..895cf41
--- /dev/null
+++ b/python/rapid_structure/rapid_table/rapid_table.py
@@ -0,0 +1,77 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import time
+import copy
+from pathlib import Path
+
+import numpy as np
+from rapidocr_onnxruntime import RapidOCR
+
+from .table_matcher import TableMatch
+from .table_structure import TableStructurer
+
+root_dir = Path(__file__).resolve().parent
+
+
+class RapidTable():
+ def __init__(self, model_path: str = None):
+ self.ocr_sys = RapidOCR()
+
+ if model_path is None:
+ model_path = str(root_dir / 'models' / 'en_ppstructure_mobile_v2_SLANet.onnx')
+
+ self.table_structure = TableStructurer(model_path)
+ self.table_matcher = TableMatch()
+
+ def __call__(self, img):
+ s = time.time()
+ dt_boxes, rec_res = self._ocr(copy.deepcopy(img))
+
+ structure_res, _ = self.table_structure(copy.deepcopy(img))
+ pred_html = self.table_matcher(structure_res, dt_boxes, rec_res)
+
+ elapse = time.time() - s
+ return pred_html, elapse
+
+ def _ocr(self, img):
+ h, w = img.shape[:2]
+
+ ocr_result, _ = self.ocr_sys(img)
+ dt_boxes, rec_res, scores = list(zip(*ocr_result))
+ rec_res = list(zip(rec_res, scores))
+
+ r_boxes = []
+ for box in dt_boxes:
+ box = np.array(box)
+ x_min = max(0, box[:, 0].min() - 1)
+ x_max = min(w, box[:, 0].max() + 1)
+ y_min = max(0, box[:, 1].min() - 1)
+ y_max = min(h, box[:, 1].max() + 1)
+ box = [x_min, y_min, x_max, y_max]
+ r_boxes.append(box)
+ dt_boxes = np.array(r_boxes)
+ return dt_boxes, rec_res
+
+
+def main():
+ import argparse
+ import cv2
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--img_path', type=str, required=True)
+ parser.add_argument('--model_path', type=str,
+ default=str(root_dir / 'models' / 'en_ppstructure_mobile_v2_SLANet.onnx'))
+ args = parser.parse_args()
+
+ rapid_table = RapidTable(args.model_path)
+
+ img = cv2.imread(args.img_path)
+
+ table_html_str, elapse = rapid_table(img)
+
+ print(table_html_str)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/python/rapid_structure/rapid_table/table_matcher/__init__.py b/python/rapid_structure/rapid_table/table_matcher/__init__.py
new file mode 100644
index 0000000..9bff7d7
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_matcher/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .matcher import TableMatch
diff --git a/python/rapid_structure/rapid_table/table_matcher/matcher.py b/python/rapid_structure/rapid_table/table_matcher/matcher.py
new file mode 100644
index 0000000..d60ddb1
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_matcher/matcher.py
@@ -0,0 +1,158 @@
+# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# -*- encoding: utf-8 -*-
+import numpy as np
+
+from .utils import compute_iou, deal_bb, distance
+
+
+class TableMatch():
+ def __init__(self, filter_ocr_result=True, use_master=False):
+ self.filter_ocr_result = filter_ocr_result
+ self.use_master = use_master
+
+ def __call__(self, structure_res, dt_boxes, rec_res):
+ pred_structures, pred_bboxes = structure_res
+ if self.filter_ocr_result:
+ dt_boxes, rec_res = self._filter_ocr_result(pred_bboxes, dt_boxes,
+ rec_res)
+ matched_index = self.match_result(dt_boxes, pred_bboxes)
+ pred_html, pred = self.get_pred_html(pred_structures,
+ matched_index,
+ rec_res)
+ return pred_html
+
+ def match_result(self, dt_boxes, pred_bboxes):
+ matched = {}
+ for i, gt_box in enumerate(dt_boxes):
+ distances = []
+ for j, pred_box in enumerate(pred_bboxes):
+ if len(pred_box) == 8:
+ pred_box = [
+ np.min(pred_box[0::2]), np.min(pred_box[1::2]),
+ np.max(pred_box[0::2]), np.max(pred_box[1::2])
+ ]
+ distances.append((distance(gt_box, pred_box),
+ 1. - compute_iou(gt_box, pred_box)
+ )) # compute iou and l1 distance
+ sorted_distances = distances.copy()
+ # select det box by iou and l1 distance
+ sorted_distances = sorted(
+ sorted_distances, key=lambda item: (item[1], item[0]))
+ if distances.index(sorted_distances[0]) not in matched.keys():
+ matched[distances.index(sorted_distances[0])] = [i]
+ else:
+ matched[distances.index(sorted_distances[0])].append(i)
+ return matched
+
+ def get_pred_html(self, pred_structures, matched_index, ocr_contents):
+ end_html = []
+ td_index = 0
+ for tag in pred_structures:
+ if '</td>' in tag:
+ if '<td></td>' == tag:
+ end_html.extend('<td>')
+ if td_index in matched_index.keys():
+ b_with = False
+ if '<b>' in ocr_contents[matched_index[td_index][0]] \
+ and len(matched_index[td_index]) > 1:
+ b_with = True
+ end_html.extend('<b>')
+ for i, td_index_index in enumerate(matched_index[td_index]):
+ content = ocr_contents[td_index_index][0]
+ if len(matched_index[td_index]) > 1:
+ if len(content) == 0:
+ continue
+
+ if content[0] == ' ':
+ content = content[1:]
+
+ if '<b>' in content:
+ content = content[3:]
+
+ if '</b>' in content:
+ content = content[:-4]
+
+ if len(content) == 0:
+ continue
+
+ if i != len(matched_index[td_index]) - 1 \
+ and ' ' != content[-1]:
+ content += ' '
+ end_html.extend(content)
+ if b_with:
+ end_html.extend('</b>')
+
+ if '<td></td>' == tag:
+ end_html.append('</td>')
+ else:
+ end_html.append(tag)
+ td_index += 1
+ else:
+ end_html.append(tag)
+ return ''.join(end_html), end_html
+
+ def get_pred_html_master(self, pred_structures, matched_index,
+ ocr_contents):
+ end_html = []
+ td_index = 0
+ for token in pred_structures:
+ if '</td>' in token:
+ txt = ''
+ b_with = False
+ if td_index in matched_index.keys():
+ if '<b>' in ocr_contents[matched_index[td_index][
+ 0]] and len(matched_index[td_index]) > 1:
+ b_with = True
+ for i, td_index_index in enumerate(matched_index[td_index]):
+ content = ocr_contents[td_index_index][0]
+ if len(matched_index[td_index]) > 1:
+ if len(content) == 0:
+ continue
+ if content[0] == ' ':
+ content = content[1:]
+ if '<b>' in content:
+ content = content[3:]
+ if '</b>' in content:
+ content = content[:-4]
+ if len(content) == 0:
+ continue
+ if i != len(matched_index[
+ td_index]) - 1 and ' ' != content[-1]:
+ content += ' '
+ txt += content
+ if b_with:
+ txt = '<b>{}</b>'.format(txt)
+ if '<td></td>' == token:
+ token = '<td>{}</td>'.format(txt)
+ else:
+ token = '{}</td>'.format(txt)
+ td_index += 1
+ token = deal_eb_token(token)
+ end_html.append(token)
+ html = ''.join(end_html)
+ html = deal_bb(html)
+ return html, end_html
+
+ def _filter_ocr_result(self, pred_bboxes, dt_boxes, rec_res):
+ y1 = pred_bboxes[:, 1::2].min()
+ new_dt_boxes = []
+ new_rec_res = []
+
+ for box, rec in zip(dt_boxes, rec_res):
+ if np.max(box[1::2]) < y1:
+ continue
+ new_dt_boxes.append(box)
+ new_rec_res.append(rec)
+ return new_dt_boxes, new_rec_res
diff --git a/python/rapid_structure/rapid_table/table_matcher/utils.py b/python/rapid_structure/rapid_table/table_matcher/utils.py
new file mode 100644
index 0000000..bb2b0cb
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_matcher/utils.py
@@ -0,0 +1,244 @@
+# copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# -*- encoding: utf-8 -*-
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import re
+
+
+def deal_isolate_span(thead_part):
+ """
+ Deal with isolate span cases in this function.
+ It causes by wrong prediction in structure recognition model.
+ eg. predict <td rowspan="2"></td> to <td></td> rowspan="2"></b></td>.
+ :param thead_part:
+ :return:
+ """
+ # 1. find out isolate span tokens.
+ isolate_pattern = "<td></td> rowspan=\"(\d)+\" colspan=\"(\d)+\"></b></td>|" \
+ "<td></td> colspan=\"(\d)+\" rowspan=\"(\d)+\"></b></td>|" \
+ "<td></td> rowspan=\"(\d)+\"></b></td>|" \
+ "<td></td> colspan=\"(\d)+\"></b></td>"
+ isolate_iter = re.finditer(isolate_pattern, thead_part)
+ isolate_list = [i.group() for i in isolate_iter]
+
+ # 2. find out span number, by step 1 results.
+ span_pattern = " rowspan=\"(\d)+\" colspan=\"(\d)+\"|" \
+ " colspan=\"(\d)+\" rowspan=\"(\d)+\"|" \
+ " rowspan=\"(\d)+\"|" \
+ " colspan=\"(\d)+\""
+ corrected_list = []
+ for isolate_item in isolate_list:
+ span_part = re.search(span_pattern, isolate_item)
+ spanStr_in_isolateItem = span_part.group()
+ # 3. merge the span number into the span token format string.
+ if spanStr_in_isolateItem is not None:
+ corrected_item = '<td{}></td>'.format(spanStr_in_isolateItem)
+ corrected_list.append(corrected_item)
+ else:
+ corrected_list.append(None)
+
+ # 4. replace original isolated token.
+ for corrected_item, isolate_item in zip(corrected_list, isolate_list):
+ if corrected_item is not None:
+ thead_part = thead_part.replace(isolate_item, corrected_item)
+ else:
+ pass
+ return thead_part
+
+
+def deal_duplicate_bb(thead_part):
+ """
+ Deal duplicate <b> or </b> after replace.
+ Keep one <b></b> in a <td></td> token.
+ :param thead_part:
+ :return:
+ """
+ # 1. find out <td></td> in <thead></thead>.
+ td_pattern = "<td rowspan=\"(\d)+\" colspan=\"(\d)+\">(.+?)</td>|" \
+ "<td colspan=\"(\d)+\" rowspan=\"(\d)+\">(.+?)</td>|" \
+ "<td rowspan=\"(\d)+\">(.+?)</td>|" \
+ "<td colspan=\"(\d)+\">(.+?)</td>|" \
+ "<td>(.*?)</td>"
+ td_iter = re.finditer(td_pattern, thead_part)
+ td_list = [t.group() for t in td_iter]
+
+ # 2. is multiply <b></b> in <td></td> or not?
+ new_td_list = []
+ for td_item in td_list:
+ if td_item.count('<b>') > 1 or td_item.count('</b>') > 1:
+ # multiply <b></b> in <td></td> case.
+ # 1. remove all <b></b>
+ td_item = td_item.replace('<b>', '').replace('</b>', '')
+ # 2. replace <tb> -> <tb><b>, </tb> -> </b></tb>.
+ td_item = td_item.replace('<td>', '<td><b>').replace('</td>',
+ '</b></td>')
+ new_td_list.append(td_item)
+ else:
+ new_td_list.append(td_item)
+
+ # 3. replace original thead part.
+ for td_item, new_td_item in zip(td_list, new_td_list):
+ thead_part = thead_part.replace(td_item, new_td_item)
+ return thead_part
+
+
+def deal_bb(result_token):
+ """
+ In our opinion, <b></b> always occurs in <thead></thead> text's context.
+ This function will find out all tokens in <thead></thead> and insert <b></b> by manual.
+ :param result_token:
+ :return:
+ """
+ # find out <thead></thead> parts.
+ thead_pattern = '<thead>(.*?)</thead>'
+ if re.search(thead_pattern, result_token) is None:
+ return result_token
+ thead_part = re.search(thead_pattern, result_token).group()
+ origin_thead_part = copy.deepcopy(thead_part)
+
+ # check "rowspan" or "colspan" occur in <thead></thead> parts or not .
+ span_pattern = "<td rowspan=\"(\d)+\" colspan=\"(\d)+\">|<td colspan=\"(\d)+\" rowspan=\"(\d)+\">|<td rowspan=\"(\d)+\">|<td colspan=\"(\d)+\">"
+ span_iter = re.finditer(span_pattern, thead_part)
+ span_list = [s.group() for s in span_iter]
+ has_span_in_head = True if len(span_list) > 0 else False
+
+ if not has_span_in_head:
+ # <thead></thead> not include "rowspan" or "colspan" branch 1.
+ # 1. replace <td> to <td><b>, and </td> to </b></td>
+ # 2. it is possible to predict text include <b> or </b> by Text-line recognition,
+ # so we replace <b><b> to <b>, and </b></b> to </b>
+ thead_part = thead_part.replace('<td>', '<td><b>')\
+ .replace('</td>', '</b></td>')\
+ .replace('<b><b>', '<b>')\
+ .replace('</b></b>', '</b>')
+ else:
+ # <thead></thead> include "rowspan" or "colspan" branch 2.
+ # Firstly, we deal rowspan or colspan cases.
+ # 1. replace > to ><b>
+ # 2. replace </td> to </b></td>
+ # 3. it is possible to predict text include <b> or </b> by Text-line recognition,
+ # so we replace <b><b> to <b>, and </b><b> to </b>
+
+ # Secondly, deal ordinary cases like branch 1
+
+ # replace ">" to "<b>"
+ replaced_span_list = []
+ for sp in span_list:
+ replaced_span_list.append(sp.replace('>', '><b>'))
+ for sp, rsp in zip(span_list, replaced_span_list):
+ thead_part = thead_part.replace(sp, rsp)
+
+ # replace "</td>" to "</b></td>"
+ thead_part = thead_part.replace('</td>', '</b></td>')
+
+ # remove duplicated <b> by re.sub
+ mb_pattern = "(<b>)+"
+ single_b_string = "<b>"
+ thead_part = re.sub(mb_pattern, single_b_string, thead_part)
+
+ mgb_pattern = "(</b>)+"
+ single_gb_string = "</b>"
+ thead_part = re.sub(mgb_pattern, single_gb_string, thead_part)
+
+ # ordinary cases like branch 1
+ thead_part = thead_part.replace('<td>', '<td><b>').replace('<b><b>',
+ '<b>')
+
+ # convert <tb><b></b></tb> back to <tb></tb>, empty cell has no <b></b>.
+ # but space cell(<tb> </tb>) is suitable for <td><b> </b></td>
+ thead_part = thead_part.replace('<td><b></b></td>', '<td></td>')
+ # deal with duplicated <b></b>
+ thead_part = deal_duplicate_bb(thead_part)
+ # deal with isolate span tokens, which causes by wrong predict by structure prediction.
+ # eg.PMC5994107_011_00.png
+ thead_part = deal_isolate_span(thead_part)
+ # replace original result with new thead part.
+ result_token = result_token.replace(origin_thead_part, thead_part)
+ return result_token
+
+
+def deal_eb_token(master_token):
+ """
+ post process with <eb></eb>, <eb1></eb1>, ...
+ emptyBboxTokenDict = {
+ "[]": '<eb></eb>',
+ "[' ']": '<eb1></eb1>',
+ "['<b>', ' ', '</b>']": '<eb2></eb2>',
+ "['\\u2028', '\\u2028']": '<eb3></eb3>',
+ "['<sup>', ' ', '</sup>']": '<eb4></eb4>',
+ "['<b>', '</b>']": '<eb5></eb5>',
+ "['<i>', ' ', '</i>']": '<eb6></eb6>',
+ "['<b>', '<i>', '</i>', '</b>']": '<eb7></eb7>',
+ "['<b>', '<i>', ' ', '</i>', '</b>']": '<eb8></eb8>',
+ "['<i>', '</i>']": '<eb9></eb9>',
+ "['<b>', ' ', '\\u2028', ' ', '\\u2028', ' ', '</b>']": '<eb10></eb10>',
+ }
+ :param master_token:
+ :return:
+ """
+ master_token = master_token.replace('<eb></eb>', '<td></td>')
+ master_token = master_token.replace('<eb1></eb1>', '<td> </td>')
+ master_token = master_token.replace('<eb2></eb2>', '<td><b> </b></td>')
+ master_token = master_token.replace('<eb3></eb3>', '<td>\u2028\u2028</td>')
+ master_token = master_token.replace('<eb4></eb4>', '<td><sup> </sup></td>')
+ master_token = master_token.replace('<eb5></eb5>', '<td><b></b></td>')
+ master_token = master_token.replace('<eb6></eb6>', '<td><i> </i></td>')
+ master_token = master_token.replace('<eb7></eb7>',
+ '<td><b><i></i></b></td>')
+ master_token = master_token.replace('<eb8></eb8>',
+ '<td><b><i> </i></b></td>')
+ master_token = master_token.replace('<eb9></eb9>', '<td><i></i></td>')
+ master_token = master_token.replace('<eb10></eb10>',
+ '<td><b> \u2028 \u2028 </b></td>')
+ return master_token
+
+
+def distance(box_1, box_2):
+ x1, y1, x2, y2 = box_1
+ x3, y3, x4, y4 = box_2
+ dis = abs(x3 - x1) + abs(y3 - y1) + abs(x4 - x2) + abs(y4 - y2)
+ dis_2 = abs(x3 - x1) + abs(y3 - y1)
+ dis_3 = abs(x4 - x2) + abs(y4 - y2)
+ return dis + min(dis_2, dis_3)
+
+
+def compute_iou(rec1, rec2):
+ """
+ computing IoU
+ :param rec1: (y0, x0, y1, x1), which reflects
+ (top, left, bottom, right)
+ :param rec2: (y0, x0, y1, x1)
+ :return: scala value of IoU
+ """
+ # computing area of each rectangles
+ S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
+ S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
+
+ # computing the sum_area
+ sum_area = S_rec1 + S_rec2
+
+ # find the each edge of intersect rectangle
+ left_line = max(rec1[1], rec2[1])
+ right_line = min(rec1[3], rec2[3])
+ top_line = max(rec1[0], rec2[0])
+ bottom_line = min(rec1[2], rec2[2])
+
+ # judge if there is an intersect
+ if left_line >= right_line or top_line >= bottom_line:
+ return 0.0
+ else:
+ intersect = (right_line - left_line) * (bottom_line - top_line)
+ return (intersect / (sum_area - intersect)) * 1.0
diff --git a/python/rapid_structure/rapid_table/table_structure/__init__.py b/python/rapid_structure/rapid_table/table_structure/__init__.py
new file mode 100644
index 0000000..a548391
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_structure/__init__.py
@@ -0,0 +1,14 @@
+# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from .table_structure import TableStructurer
diff --git a/python/rapid_structure/rapid_table/table_structure/table_structure.py b/python/rapid_structure/rapid_table/table_structure/table_structure.py
new file mode 100644
index 0000000..fdc297d
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_structure/table_structure.py
@@ -0,0 +1,60 @@
+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import time
+import numpy as np
+
+from .utils import (OrtInferSession, TableLabelDecode, TablePreprocess)
+
+
+class TableStructurer(object):
+ def __init__(self, model_path: str):
+ self.preprocess_op = TablePreprocess()
+
+ session_instance = OrtInferSession(model_path)
+ self.predictor = session_instance.session
+ self.input_name = session_instance.get_input_name()
+
+ self.character = session_instance.get_metadata()
+ self.postprocess_op = TableLabelDecode(self.character)
+
+ def __call__(self, img):
+ starttime = time.time()
+ data = {'image': img}
+ data = self.preprocess_op(data)
+ img = data[0]
+ if img is None:
+ return None, 0
+ img = np.expand_dims(img, axis=0)
+ img = img.copy()
+
+ input_dict = {self.input_name: img}
+ outputs = self.predictor.run(None, input_dict)
+
+ preds = {
+ 'loc_preds': outputs[0],
+ 'structure_probs': outputs[1]
+ }
+
+ shape_list = np.expand_dims(data[-1], axis=0)
+ post_result = self.postprocess_op(preds, [shape_list])
+
+ bbox_list = post_result['bbox_batch_list'][0]
+
+ structure_str_list = post_result['structure_batch_list'][0]
+ structure_str_list = structure_str_list[0]
+ structure_str_list = [
+ '<html>', '<body>', '<table>'
+ ] + structure_str_list + ['</table>', '</body>', '</html>']
+ elapse = time.time() - starttime
+ return (structure_str_list, bbox_list), elapse
diff --git a/python/rapid_structure/rapid_table/table_structure/utils.py b/python/rapid_structure/rapid_table/table_structure/utils.py
new file mode 100644
index 0000000..80edcf0
--- /dev/null
+++ b/python/rapid_structure/rapid_table/table_structure/utils.py
@@ -0,0 +1,345 @@
+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+
+import cv2
+import numpy as np
+from onnxruntime import (GraphOptimizationLevel, InferenceSession,
+ SessionOptions)
+
+
+class OrtInferSession(object):
+ def __init__(self, onnx_path: str):
+ self.__verify_model(onnx_path)
+
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+ sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
+
+ cpu_ep = 'CPUExecutionProvider'
+ cpu_provider_options = {"arena_extend_strategy": "kSameAsRequested",}
+ EP_list = [(cpu_ep, cpu_provider_options)]
+
+ self.session = InferenceSession(onnx_path,
+ sess_options=sess_opt,
+ providers=EP_list)
+
+ def get_input_name(self, input_idx=0):
+ return self.session.get_inputs()[input_idx].name
+
+ def get_output_name(self, output_idx=0):
+ return self.session.get_outputs()[output_idx].name
+
+ def get_metadata(self, key: str = 'character') -> list:
+ meta_dict = self.session.get_modelmeta().custom_metadata_map
+ content_list = meta_dict[key].splitlines()
+ return content_list
+
+ @staticmethod
+ def __verify_model(model_path):
+ model_path = Path(model_path)
+ if not model_path.exists():
+ raise FileNotFoundError(f'{model_path} does not exists.')
+ if not model_path.is_file():
+ raise FileExistsError(f'{model_path} is not a file.')
+
+
+class TableLabelDecode(object):
+ """ """
+ def __init__(self,
+ dict_character,
+ merge_no_span_structure=True,
+ **kwargs):
+ if merge_no_span_structure:
+ if "<td></td>" not in dict_character:
+ dict_character.append("<td></td>")
+ if "<td>" in dict_character:
+ dict_character.remove("<td>")
+
+ dict_character = self.add_special_char(dict_character)
+ self.dict = {}
+ for i, char in enumerate(dict_character):
+ self.dict[char] = i
+ self.character = dict_character
+ self.td_token = ['<td>', '<td', '<td></td>']
+
+ def __call__(self, preds, batch=None):
+ structure_probs = preds['structure_probs']
+ bbox_preds = preds['loc_preds']
+ shape_list = batch[-1]
+ result = self.decode(structure_probs, bbox_preds, shape_list)
+ if len(batch) == 1: # only contains shape
+ return result
+
+ label_decode_result = self.decode_label(batch)
+ return result, label_decode_result
+
+ def decode(self, structure_probs, bbox_preds, shape_list):
+ """convert text-label into text-index.
+ """
+ ignored_tokens = self.get_ignored_tokens()
+ end_idx = self.dict[self.end_str]
+
+ structure_idx = structure_probs.argmax(axis=2)
+ structure_probs = structure_probs.max(axis=2)
+
+ structure_batch_list = []
+ bbox_batch_list = []
+ batch_size = len(structure_idx)
+ for batch_idx in range(batch_size):
+ structure_list = []
+ bbox_list = []
+ score_list = []
+ for idx in range(len(structure_idx[batch_idx])):
+ char_idx = int(structure_idx[batch_idx][idx])
+ if idx > 0 and char_idx == end_idx:
+ break
+
+ if char_idx in ignored_tokens:
+ continue
+
+ text = self.character[char_idx]
+ if text in self.td_token:
+ bbox = bbox_preds[batch_idx, idx]
+ bbox = self._bbox_decode(bbox, shape_list[batch_idx])
+ bbox_list.append(bbox)
+ structure_list.append(text)
+ score_list.append(structure_probs[batch_idx, idx])
+ structure_batch_list.append([structure_list, np.mean(score_list)])
+ bbox_batch_list.append(np.array(bbox_list))
+ result = {
+ 'bbox_batch_list': bbox_batch_list,
+ 'structure_batch_list': structure_batch_list,
+ }
+ return result
+
+ def decode_label(self, batch):
+ """convert text-label into text-index.
+ """
+ structure_idx = batch[1]
+ gt_bbox_list = batch[2]
+ shape_list = batch[-1]
+ ignored_tokens = self.get_ignored_tokens()
+ end_idx = self.dict[self.end_str]
+
+ structure_batch_list = []
+ bbox_batch_list = []
+ batch_size = len(structure_idx)
+ for batch_idx in range(batch_size):
+ structure_list = []
+ bbox_list = []
+ for idx in range(len(structure_idx[batch_idx])):
+ char_idx = int(structure_idx[batch_idx][idx])
+ if idx > 0 and char_idx == end_idx:
+ break
+ if char_idx in ignored_tokens:
+ continue
+ structure_list.append(self.character[char_idx])
+
+ bbox = gt_bbox_list[batch_idx][idx]
+ if bbox.sum() != 0:
+ bbox = self._bbox_decode(bbox, shape_list[batch_idx])
+ bbox_list.append(bbox)
+ structure_batch_list.append(structure_list)
+ bbox_batch_list.append(bbox_list)
+ result = {
+ 'bbox_batch_list': bbox_batch_list,
+ 'structure_batch_list': structure_batch_list,
+ }
+ return result
+
+ def _bbox_decode(self, bbox, shape):
+ h, w, ratio_h, ratio_w, pad_h, pad_w = shape
+ bbox[0::2] *= w
+ bbox[1::2] *= h
+ return bbox
+
+ def get_ignored_tokens(self):
+ beg_idx = self.get_beg_end_flag_idx("beg")
+ end_idx = self.get_beg_end_flag_idx("end")
+ return [beg_idx, end_idx]
+
+ def get_beg_end_flag_idx(self, beg_or_end):
+ if beg_or_end == "beg":
+ idx = np.array(self.dict[self.beg_str])
+ elif beg_or_end == "end":
+ idx = np.array(self.dict[self.end_str])
+ else:
+ assert False, "unsupport type %s in get_beg_end_flag_idx" \
+ % beg_or_end
+ return idx
+
+ def add_special_char(self, dict_character):
+ self.beg_str = "sos"
+ self.end_str = "eos"
+ dict_character = dict_character
+ dict_character = [self.beg_str] + dict_character + [self.end_str]
+ return dict_character
+
+
+class TablePreprocess(object):
+ def __init__(self):
+ self.table_max_len = 488
+ self.build_pre_process_list()
+ self.ops = self.create_operators()
+
+ def __call__(self, data):
+ """ transform """
+ if self.ops is None:
+ self.ops = []
+
+ for op in self.ops:
+ data = op(data)
+ if data is None:
+ return None
+ return data
+
+ def create_operators(self,):
+ """
+ create operators based on the config
+
+ Args:
+ params(list): a dict list, used to create some operators
+ """
+ assert isinstance(self.pre_process_list, list), ('operator config should be a list')
+ ops = []
+ for operator in self.pre_process_list:
+ assert isinstance(operator,
+ dict) and len(operator) == 1, "yaml format error"
+ op_name = list(operator)[0]
+ param = {} if operator[op_name] is None else operator[op_name]
+ op = eval(op_name)(**param)
+ ops.append(op)
+ return ops
+
+ def build_pre_process_list(self):
+ resize_op = {'ResizeTableImage': {'max_len': self.table_max_len, }}
+ pad_op = {
+ 'PaddingTableImage': {
+ 'size': [self.table_max_len, self.table_max_len]
+ }
+ }
+ normalize_op = {
+ 'NormalizeImage': {
+ 'std': [0.229, 0.224, 0.225],
+ 'mean': [0.485, 0.456, 0.406],
+ 'scale': '1./255.',
+ 'order': 'hwc'
+ }
+ }
+ to_chw_op = {'ToCHWImage': None}
+ keep_keys_op = {'KeepKeys': {'keep_keys': ['image', 'shape']}}
+ self.pre_process_list = [
+ resize_op, normalize_op, pad_op, to_chw_op, keep_keys_op
+ ]
+
+
+class ResizeTableImage(object):
+ def __init__(self, max_len, resize_bboxes=False, infer_mode=False,
+ **kwargs):
+ super(ResizeTableImage, self).__init__()
+ self.max_len = max_len
+ self.resize_bboxes = resize_bboxes
+ self.infer_mode = infer_mode
+
+ def __call__(self, data):
+ img = data['image']
+ height, width = img.shape[0:2]
+ ratio = self.max_len / (max(height, width) * 1.0)
+ resize_h = int(height * ratio)
+ resize_w = int(width * ratio)
+ resize_img = cv2.resize(img, (resize_w, resize_h))
+ if self.resize_bboxes and not self.infer_mode:
+ data['bboxes'] = data['bboxes'] * ratio
+ data['image'] = resize_img
+ data['src_img'] = img
+ data['shape'] = np.array([height, width, ratio, ratio])
+ data['max_len'] = self.max_len
+ return data
+
+
+class PaddingTableImage(object):
+ def __init__(self, size, **kwargs):
+ super(PaddingTableImage, self).__init__()
+ self.size = size
+
+ def __call__(self, data):
+ img = data['image']
+ pad_h, pad_w = self.size
+ padding_img = np.zeros((pad_h, pad_w, 3), dtype=np.float32)
+ height, width = img.shape[0:2]
+ padding_img[0:height, 0:width, :] = img.copy()
+ data['image'] = padding_img
+ shape = data['shape'].tolist()
+ shape.extend([pad_h, pad_w])
+ data['shape'] = np.array(shape)
+ return data
+
+
+class NormalizeImage(object):
+ """ normalize image such as substract mean, divide std
+ """
+
+ def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs):
+ if isinstance(scale, str):
+ scale = eval(scale)
+ self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
+ mean = mean if mean is not None else [0.485, 0.456, 0.406]
+ std = std if std is not None else [0.229, 0.224, 0.225]
+
+ shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)
+ self.mean = np.array(mean).reshape(shape).astype('float32')
+ self.std = np.array(std).reshape(shape).astype('float32')
+
+ def __call__(self, data):
+ img = data['image']
+ from PIL import Image
+ if isinstance(img, Image.Image):
+ img = np.array(img)
+ assert isinstance(img,
+ np.ndarray), "invalid input 'img' in NormalizeImage"
+ data['image'] = (
+ img.astype('float32') * self.scale - self.mean) / self.std
+ return data
+
+
+class ToCHWImage(object):
+ """ convert hwc image to chw image
+ """
+
+ def __init__(self, **kwargs):
+ pass
+
+ def __call__(self, data):
+ img = data['image']
+ from PIL import Image
+ if isinstance(img, Image.Image):
+ img = np.array(img)
+ data['image'] = img.transpose((2, 0, 1))
+ return data
+
+
+class KeepKeys(object):
+ def __init__(self, keep_keys, **kwargs):
+ self.keep_keys = keep_keys
+
+ def __call__(self, data):
+ data_list = []
+ for key in self.keep_keys:
+ data_list.append(data[key])
+ return data_list
diff --git a/python/rapid_structure/setup_layout.py b/python/rapid_structure/setup_layout.py
index e861e78..a45dd11 100644
--- a/python/rapid_structure/setup_layout.py
+++ b/python/rapid_structure/setup_layout.py
@@ -29,7 +29,7 @@ def version_add_one(version, add_loc=-1):
def get_readme():
root_dir = Path(__file__).resolve().parent.parent.parent
readme_path = str(root_dir / 'docs' / 'doc_whl_layout.md')
- with open(readme_path, 'r') as f:
+ with open(readme_path, 'r', encoding='utf-8') as f:
readme = f.read()
return readme
@@ -64,6 +64,6 @@ setuptools.setup(
'Programming Language :: Python :: 3.9',
],
entry_points={
- 'console_scripts': ['rapid_layout=rapid_layout.rapid_layout:main']
+ 'console_scripts': [f'{MODULE_NAME}={MODULE_NAME}.{MODULE_NAME}:main']
}
)
diff --git a/python/rapid_structure/setup_table.py b/python/rapid_structure/setup_table.py
new file mode 100644
index 0000000..563bb08
--- /dev/null
+++ b/python/rapid_structure/setup_table.py
@@ -0,0 +1,70 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+import setuptools
+import subprocess
+
+
+def get_latest_version(package_name):
+ output = subprocess.run(["pip", "index", "versions", package_name],
+ capture_output=True)
+ output = output.stdout.decode('utf-8')
+ if output:
+ output = list(filter(lambda x: len(x) > 0, output.split('\n')))
+ return output[0].split(' ')[-1][1:-1]
+ return None
+
+
+def version_add_one(version, add_loc=-1):
+ if version:
+ version_list = version.split('.')
+ mini_version = str(int(version_list[add_loc]) + 1)
+ version_list[add_loc] = mini_version
+ new_version = '.'.join(version_list)
+ return new_version
+ return '0.0.1'
+
+
+def get_readme():
+ root_dir = Path(__file__).resolve().parent.parent.parent
+ readme_path = str(root_dir / 'docs' / 'doc_whl_layout.md')
+ with open(readme_path, 'r', encoding='utf-8') as f:
+ readme = f.read()
+ return readme
+
+
+MODULE_NAME = 'rapid_table'
+latest_version = get_latest_version(MODULE_NAME)
+VERSION_NUM = version_add_one(latest_version)
+
+setuptools.setup(
+ name=MODULE_NAME,
+ version=VERSION_NUM,
+ platforms="Any",
+ description="RapidTable",
+ long_description=get_readme(),
+ long_description_content_type='text/markdown',
+ author="SWHL",
+ author_email="[email protected]",
+ url="https://github.com/RapidAI/RapidOCR",
+ license='Apache-2.0',
+ include_package_data=True,
+ install_requires=["onnxruntime>=1.7.0", "PyYAML>=6.0",
+ "opencv_python>=4.5.1.48", "numpy>=1.21.6",
+ "rapidocr_onnxruntime>=1.1.18"],
+ packages=[MODULE_NAME, f'{MODULE_NAME}.models'],
+ package_data={'': ['layout_cdla.onnx']},
+ keywords=[
+ 'ppstructure,table,rapidocr'
+ ],
+ classifiers=[
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ 'Programming Language :: Python :: 3.10',
+ ],
+ entry_points={
+ 'console_scripts': [f'{MODULE_NAME}={MODULE_NAME}.{MODULE_NAME}:main']
+ }
+)
diff --git a/python/rapid_structure/test_images/ch.png b/python/rapid_structure/test_images/layout.png
similarity index 100%
rename from python/rapid_structure/test_images/ch.png
rename to python/rapid_structure/test_images/layout.png
diff --git a/python/rapid_structure/test_images/table.jpg b/python/rapid_structure/test_images/table.jpg
new file mode 100644
index 0000000..95fdf84
Binary files /dev/null and b/python/rapid_structure/test_images/table.jpg differ
diff --git a/python/rapid_structure/tests/test_table.py b/python/rapid_structure/tests/test_table.py
new file mode 100644
index 0000000..34a1cd4
--- /dev/null
+++ b/python/rapid_structure/tests/test_table.py
@@ -0,0 +1,23 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import sys
+from pathlib import Path
+
+import cv2
+
+# rapid_structure路径
+root_dir = Path(__file__).resolve().parent.parent
+
+sys.path.append(str(root_dir))
+
+from rapid_table import RapidTable
+
+
+def test_table():
+ rapid_table = RapidTable()
+
+ img = cv2.imread('test_images/table.jpg')
+
+ table_html_str, elapse = rapid_table(img)
+ assert table_html_str.count('<tr>') == 16