batch_analyze.py 6.89 KB
Newer Older
1
2
3
4
5
6
7
8
9
import time

import cv2
import torch
from loguru import logger

from magic_pdf.config.constants import MODEL_NAME
from magic_pdf.model.pdf_extract_kit import CustomPEKModel
from magic_pdf.model.sub_modules.model_utils import (
icecraft's avatar
icecraft committed
10
    clean_vram, crop_img, get_res_list_from_layout_res)
11
from magic_pdf.model.sub_modules.ocr.paddleocr.ocr_utils import (
icecraft's avatar
icecraft committed
12
    get_adjusted_mfdetrec_res, get_ocr_result_list)
13

14
YOLO_LAYOUT_BASE_BATCH_SIZE = 1
15
16
17
18
19
20
21
22
23
24
MFD_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16


class BatchAnalyze:
    def __init__(self, model: CustomPEKModel, batch_ratio: int):
        self.model = model
        self.batch_ratio = batch_ratio

    def __call__(self, images: list) -> list:
25
        images_layout_res = []
26
        layout_start_time = time.time()
27
28
29
30
31
32
33
        if self.model.layout_model_name == MODEL_NAME.LAYOUTLMv3:
            # layoutlmv3
            for image in images:
                layout_res = self.model.layout_model(image, ignore_catids=[])
                images_layout_res.append(layout_res)
        elif self.model.layout_model_name == MODEL_NAME.DocLayout_YOLO:
            # doclayout_yolo
34
35
            layout_images = []
            for image_index, image in enumerate(images):
36
                layout_images.append(image)
37

38
            images_layout_res += self.model.layout_model.batch_predict(
39
40
                # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
                layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
41
42
            )

43
        logger.info(
icecraft's avatar
icecraft committed
44
            f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
45
46
        )

47
48
        if self.model.apply_formula:
            # 公式检测
49
            mfd_start_time = time.time()
50
            images_mfd_res = self.model.mfd_model.batch_predict(
51
52
                # images, self.batch_ratio * MFD_BASE_BATCH_SIZE
                images, MFD_BASE_BATCH_SIZE
53
            )
54
            logger.info(
icecraft's avatar
icecraft committed
55
                f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
56
            )
57
58

            # 公式识别
59
            mfr_start_time = time.time()
60
61
62
63
64
            images_formula_list = self.model.mfr_model.batch_predict(
                images_mfd_res,
                images,
                batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
            )
65
            mfr_count = 0
66
67
            for image_index in range(len(images)):
                images_layout_res[image_index] += images_formula_list[image_index]
68
                mfr_count += len(images_formula_list[image_index])
69
            logger.info(
70
                f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {mfr_count}'
71
            )
72
73
74
75

        # 清理显存
        clean_vram(self.model.device, vram_threshold=8)

76
77
78
79
        ocr_time = 0
        ocr_count = 0
        table_time = 0
        table_count = 0
80
81
82
        # reference: magic_pdf/model/doc_analyze_by_custom_model.py:doc_analyze
        for index in range(len(images)):
            layout_res = images_layout_res[index]
83
            np_array_img = images[index]
84
85
86
87
88
89
90
91
92

            ocr_res_list, table_res_list, single_page_mfdetrec_res = (
                get_res_list_from_layout_res(layout_res)
            )
            # ocr识别
            ocr_start = time.time()
            # Process each area that requires OCR processing
            for res in ocr_res_list:
                new_image, useful_list = crop_img(
93
                    res, np_array_img, crop_paste_x=50, crop_paste_y=50
94
95
96
97
98
99
                )
                adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
                    single_page_mfdetrec_res, useful_list
                )

                # OCR recognition
100
                new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
101
102
103
104
105
106
107
108
109
110
111
112
113
114

                if self.model.apply_ocr:
                    ocr_res = self.model.ocr_model.ocr(
                        new_image, mfd_res=adjusted_mfdetrec_res
                    )[0]
                else:
                    ocr_res = self.model.ocr_model.ocr(
                        new_image, mfd_res=adjusted_mfdetrec_res, rec=False
                    )[0]

                # Integration results
                if ocr_res:
                    ocr_result_list = get_ocr_result_list(ocr_res, useful_list)
                    layout_res.extend(ocr_result_list)
115
116
            ocr_time += time.time() - ocr_start
            ocr_count += len(ocr_res_list)
117
118
119
120
121

            # 表格识别 table recognition
            if self.model.apply_table:
                table_start = time.time()
                for res in table_res_list:
122
                    new_image, _ = crop_img(res, np_array_img)
123
124
125
126
127
                    single_table_start_time = time.time()
                    html_code = None
                    if self.model.table_model_name == MODEL_NAME.STRUCT_EQTABLE:
                        with torch.no_grad():
                            table_result = self.model.table_model.predict(
icecraft's avatar
icecraft committed
128
                                new_image, 'html'
129
130
131
132
133
134
                            )
                            if len(table_result) > 0:
                                html_code = table_result[0]
                    elif self.model.table_model_name == MODEL_NAME.TABLE_MASTER:
                        html_code = self.model.table_model.img2html(new_image)
                    elif self.model.table_model_name == MODEL_NAME.RAPID_TABLE:
135
                        html_code, table_cell_bboxes, logic_points, elapse = (
136
137
138
139
140
                            self.model.table_model.predict(new_image)
                        )
                    run_time = time.time() - single_table_start_time
                    if run_time > self.model.table_max_time:
                        logger.warning(
icecraft's avatar
icecraft committed
141
                            f'table recognition processing exceeds max time {self.model.table_max_time}s'
142
143
144
145
                        )
                    # 判断是否返回正常
                    if html_code:
                        expected_ending = html_code.strip().endswith(
icecraft's avatar
icecraft committed
146
147
                            '</html>'
                        ) or html_code.strip().endswith('</table>')
148
                        if expected_ending:
icecraft's avatar
icecraft committed
149
                            res['html'] = html_code
150
151
                        else:
                            logger.warning(
icecraft's avatar
icecraft committed
152
                                'table recognition processing fails, not found expected HTML table end'
153
154
155
                            )
                    else:
                        logger.warning(
icecraft's avatar
icecraft committed
156
                            'table recognition processing fails, not get html return'
157
                        )
158
159
160
161
                table_time += time.time() - table_start
                table_count += len(table_res_list)

        if self.model.apply_ocr:
icecraft's avatar
icecraft committed
162
            logger.info(f'ocr time: {round(ocr_time, 2)}, image num: {ocr_count}')
163
        else:
icecraft's avatar
icecraft committed
164
            logger.info(f'det time: {round(ocr_time, 2)}, image num: {ocr_count}')
165
        if self.model.apply_table:
icecraft's avatar
icecraft committed
166
            logger.info(f'table time: {round(table_time, 2)}, image num: {table_count}')
167

168
        return images_layout_res