pp_structure_v2.py 2.41 KB
Newer Older
1
2
3
import random

from loguru import logger
赵小蒙's avatar
赵小蒙 committed
4
from paddleocr import PPStructure
5

blue's avatar
blue committed
6

7
8
9
10
11
12
13
14
def region_to_bbox(region):
    x0 = region[0][0]
    y0 = region[0][1]
    x1 = region[2][0]
    y1 = region[2][1]
    return [x0, y0, x1, y1]


blue's avatar
blue committed
15
class CustomPaddleModel:
赵小蒙's avatar
赵小蒙 committed
16
    def __init__(self, ocr: bool = False, show_log: bool = False):
blue's avatar
blue committed
17
18
19
20
        self.model = PPStructure(table=False, ocr=ocr, show_log=show_log)

    def __call__(self, img):
        result = self.model(img)
21
22
        spans = []
        for line in result:
blue's avatar
blue committed
23
24
            line.pop("img")
            """
25
26
27
28
29
30
31
32
33
34
35
36
            为paddle输出适配type no.    
            title: 0 # 标题
            text: 1 # 文本
            header: 2 # abandon
            footer: 2 # abandon
            reference: 1 # 文本 or abandon
            equation: 8 # 行间公式 block
            equation: 14 # 行间公式 text
            figure: 3 # 图片
            figure_caption: 4 # 图片描述
            table: 5 # 表格
            table_caption: 6 # 表格描述
blue's avatar
blue committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
            """
            if line["type"] == "title":
                line["category_id"] = 0
            elif line["type"] in ["text", "reference"]:
                line["category_id"] = 1
            elif line["type"] == "figure":
                line["category_id"] = 3
            elif line["type"] == "figure_caption":
                line["category_id"] = 4
            elif line["type"] == "table":
                line["category_id"] = 5
            elif line["type"] == "table_caption":
                line["category_id"] = 6
            elif line["type"] == "equation":
                line["category_id"] = 8
            elif line["type"] in ["header", "footer"]:
                line["category_id"] = 2
54
55
            else:
                logger.warning(f"unknown type: {line['type']}")
56
57
58

            # 兼容不输出score的paddleocr版本
            if line.get("score") is None:
blue's avatar
blue committed
59
                line["score"] = 0.5 + random.random() * 0.5
60

blue's avatar
blue committed
61
            res = line.pop("res", None)
62
63
            if res is not None and len(res) > 0:
                for span in res:
blue's avatar
blue committed
64
65
66
67
68
69
                    new_span = {
                        "category_id": 15,
                        "bbox": region_to_bbox(span["text_region"]),
                        "score": span["confidence"],
                        "text": span["text"],
                    }
70
71
72
73
74
                    spans.append(new_span)

        if len(spans) > 0:
            result.extend(spans)

blue's avatar
blue committed
75
        return result