pdf_extract_kit.py 10.6 KB
Newer Older
1
# flake8: noqa
myhloli's avatar
myhloli committed
2
import os
3
import time
4

5
import cv2
6
import torch
7
import yaml
8
from loguru import logger
9
10

os.environ['NO_ALBUMENTATIONS_UPDATE'] = '1'  # 禁止albumentations检查更新
11

12
from magic_pdf.config.constants import *
13
from magic_pdf.model.model_list import AtomicModel
14
from magic_pdf.model.sub_modules.model_init import AtomModelSingleton
15
16
from magic_pdf.model.sub_modules.model_utils import (
    clean_vram, crop_img, get_res_list_from_layout_res)
17
from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.ocr_utils import (
18
    get_adjusted_mfdetrec_res, get_ocr_result_list)
19
20


21
class CustomPEKModel:
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
    def __init__(self, ocr: bool = False, show_log: bool = False, **kwargs):
        """
        ======== model init ========
        """
        # 获取当前文件(即 pdf_extract_kit.py)的绝对路径
        current_file_path = os.path.abspath(__file__)
        # 获取当前文件所在的目录(model)
        current_dir = os.path.dirname(current_file_path)
        # 上一级目录(magic_pdf)
        root_dir = os.path.dirname(current_dir)
        # model_config目录
        model_config_dir = os.path.join(root_dir, 'resources', 'model_config')
        # 构建 model_configs.yaml 文件的完整路径
        config_path = os.path.join(model_config_dir, 'model_configs.yaml')
37
        with open(config_path, 'r', encoding='utf-8') as f:
38
39
            self.configs = yaml.load(f, Loader=yaml.FullLoader)
        # 初始化解析配置
40
41

        # layout config
42
43
44
45
        self.layout_config = kwargs.get('layout_config')
        self.layout_model_name = self.layout_config.get(
            'model', MODEL_NAME.DocLayout_YOLO
        )
46
47

        # formula config
48
49
50
51
52
53
54
55
        self.formula_config = kwargs.get('formula_config')
        self.mfd_model_name = self.formula_config.get(
            'mfd_model', MODEL_NAME.YOLO_V8_MFD
        )
        self.mfr_model_name = self.formula_config.get(
            'mfr_model', MODEL_NAME.UniMerNet_v2_Small
        )
        self.apply_formula = self.formula_config.get('enable', True)
56

57
        # table config
58
59
60
61
        self.table_config = kwargs.get('table_config')
        self.apply_table = self.table_config.get('enable', False)
        self.table_max_time = self.table_config.get('max_time', TABLE_MAX_TIME_VALUE)
        self.table_model_name = self.table_config.get('model', MODEL_NAME.RAPID_TABLE)
62
        self.table_sub_model_name = self.table_config.get('sub_model', None)
63
64

        # ocr config
65
        self.apply_ocr = ocr
66
        self.lang = kwargs.get('lang', None)
67

68
        logger.info(
69
70
71
72
73
74
75
76
            'DocAnalysis init, this may take some times, layout_model: {}, apply_formula: {}, apply_ocr: {}, '
            'apply_table: {}, table_model: {}, lang: {}'.format(
                self.layout_model_name,
                self.apply_formula,
                self.apply_ocr,
                self.apply_table,
                self.table_model_name,
                self.lang,
赵小蒙's avatar
update:  
赵小蒙 committed
77
            )
78
79
        )
        # 初始化解析方案
80
        self.device = kwargs.get('device', 'cpu')
81

82
83
84
85
86
        logger.info('using device: {}'.format(self.device))
        models_dir = kwargs.get(
            'models_dir', os.path.join(root_dir, 'resources', 'models')
        )
        logger.info('using models_dir: {}'.format(models_dir))
87

88
89
        atom_model_manager = AtomModelSingleton()

90
91
92
        # 初始化公式识别
        if self.apply_formula:
            # 初始化公式检测模型
93
94
            self.mfd_model = atom_model_manager.get_atom_model(
                atom_model_name=AtomicModel.MFD,
95
96
97
98
99
100
                mfd_weights=str(
                    os.path.join(
                        models_dir, self.configs['weights'][self.mfd_model_name]
                    )
                ),
                device=self.device,
101
            )
102

103
            # 初始化公式解析模型
104
105
106
107
            mfr_weight_dir = str(
                os.path.join(models_dir, self.configs['weights'][self.mfr_model_name])
            )
            mfr_cfg_path = str(os.path.join(model_config_dir, 'UniMERNet', 'demo.yaml'))
108

109
            self.mfr_model = atom_model_manager.get_atom_model(
110
111
112
                atom_model_name=AtomicModel.MFR,
                mfr_weight_dir=mfr_weight_dir,
                mfr_cfg_path=mfr_cfg_path,
113
                device=self.device,
114
            )
115
116

        # 初始化layout模型
117
118
119
120
        if self.layout_model_name == MODEL_NAME.LAYOUTLMv3:
            self.layout_model = atom_model_manager.get_atom_model(
                atom_model_name=AtomicModel.Layout,
                layout_model_name=MODEL_NAME.LAYOUTLMv3,
121
122
123
124
125
126
127
128
129
130
                layout_weights=str(
                    os.path.join(
                        models_dir, self.configs['weights'][self.layout_model_name]
                    )
                ),
                layout_config_file=str(
                    os.path.join(
                        model_config_dir, 'layoutlmv3', 'layoutlmv3_base_inference.yaml'
                    )
                ),
131
                device='cpu' if str(self.device).startswith("mps") else self.device,
132
133
134
135
136
            )
        elif self.layout_model_name == MODEL_NAME.DocLayout_YOLO:
            self.layout_model = atom_model_manager.get_atom_model(
                atom_model_name=AtomicModel.Layout,
                layout_model_name=MODEL_NAME.DocLayout_YOLO,
137
138
139
140
141
142
                doclayout_yolo_weights=str(
                    os.path.join(
                        models_dir, self.configs['weights'][self.layout_model_name]
                    )
                ),
                device=self.device,
143
            )
144
        # 初始化ocr
145
146
147
        self.ocr_model = atom_model_manager.get_atom_model(
            atom_model_name=AtomicModel.OCR,
            ocr_show_log=show_log,
148
149
150
            det_db_box_thresh=0.3,
            lang=self.lang
        )
151
        # init table model
152
        if self.apply_table:
153
            table_model_dir = self.configs['weights'][self.table_model_name]
154
155
156
157
158
            self.table_model = atom_model_manager.get_atom_model(
                atom_model_name=AtomicModel.Table,
                table_model_name=self.table_model_name,
                table_model_path=str(os.path.join(models_dir, table_model_dir)),
                table_max_time=self.table_max_time,
159
                device=self.device,
160
                ocr_engine=self.ocr_model,
161
                table_sub_model_name=self.table_sub_model_name
162
            )
drunkpig's avatar
drunkpig committed
163

164
        logger.info('DocAnalysis init done!')
赵小蒙's avatar
update:  
赵小蒙 committed
165

166
167
168
    def __call__(self, image):
        # layout检测
        layout_start = time.time()
169
        layout_res = []
170
171
172
173
        if self.layout_model_name == MODEL_NAME.LAYOUTLMv3:
            # layoutlmv3
            layout_res = self.layout_model(image, ignore_catids=[])
        elif self.layout_model_name == MODEL_NAME.DocLayout_YOLO:
174
            layout_res = self.layout_model.predict(image)
175

176
        layout_cost = round(time.time() - layout_start, 2)
177
        logger.info(f'layout detection time: {layout_cost}')
178

179
180
        if self.apply_formula:
            # 公式检测
181
            mfd_start = time.time()
182
            mfd_res = self.mfd_model.predict(image)
183
            logger.info(f'mfd time: {round(time.time() - mfd_start, 2)}')
184
185
186

            # 公式识别
            mfr_start = time.time()
187
188
            formula_list = self.mfr_model.predict(mfd_res, image)
            layout_res.extend(formula_list)
189
            mfr_cost = round(time.time() - mfr_start, 2)
190
            logger.info(f'formula nums: {len(formula_list)}, mfr time: {mfr_cost}')
191
192

        # 清理显存
193
        clean_vram(self.device, vram_threshold=6)
194
195

        # 从layout_res中获取ocr区域、表格区域、公式区域
196
197
198
        ocr_res_list, table_res_list, single_page_mfdetrec_res = (
            get_res_list_from_layout_res(layout_res)
        )
199

myhloli's avatar
myhloli committed
200
        # ocr识别
201
202
203
        ocr_start = time.time()
        # Process each area that requires OCR processing
        for res in ocr_res_list:
204
            new_image, useful_list = crop_img(res, image, crop_paste_x=50, crop_paste_y=50)
205
206
207
            adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list)

            # OCR recognition
208
            new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
209

210
211
212
213
            if self.apply_ocr:
                ocr_res = self.ocr_model.ocr(new_image, mfd_res=adjusted_mfdetrec_res)[0]
            else:
                ocr_res = self.ocr_model.ocr(new_image, mfd_res=adjusted_mfdetrec_res, rec=False)[0]
214

215
216
217
218
            # Integration results
            if ocr_res:
                ocr_result_list = get_ocr_result_list(ocr_res, useful_list)
                layout_res.extend(ocr_result_list)
219

220
221
        ocr_cost = round(time.time() - ocr_start, 2)
        if self.apply_ocr:
222
            logger.info(f"ocr time: {ocr_cost}")
223
224
        else:
            logger.info(f"det time: {ocr_cost}")
225

226
227
        # 表格识别 table recognition
        if self.apply_table:
228
229
            table_start = time.time()
            for res in table_res_list:
230
                new_image, _ = crop_img(res, image)
231
                single_table_start_time = time.time()
232
                html_code = None
233
                if self.table_model_name == MODEL_NAME.STRUCT_EQTABLE:
234
                    with torch.no_grad():
235
                        table_result = self.table_model.predict(new_image, 'html')
236
237
                        if len(table_result) > 0:
                            html_code = table_result[0]
238
                elif self.table_model_name == MODEL_NAME.TABLE_MASTER:
239
                    html_code = self.table_model.img2html(new_image)
240
                elif self.table_model_name == MODEL_NAME.RAPID_TABLE:
241
                    html_code, table_cell_bboxes, logic_points, elapse = self.table_model.predict(
242
243
                        new_image
                    )
244
245
                run_time = time.time() - single_table_start_time
                if run_time > self.table_max_time:
246
247
248
                    logger.warning(
                        f'table recognition processing exceeds max time {self.table_max_time}s'
                    )
249
                # 判断是否返回正常
250
                if html_code:
251
252
253
                    expected_ending = html_code.strip().endswith(
                        '</html>'
                    ) or html_code.strip().endswith('</table>')
254
                    if expected_ending:
255
                        res['html'] = html_code
256
                    else:
257
258
259
                        logger.warning(
                            'table recognition processing fails, not found expected HTML table end'
                        )
260
                else:
261
262
263
264
                    logger.warning(
                        'table recognition processing fails, not get html return'
                    )
            logger.info(f'table time: {round(time.time() - table_start, 2)}')
265

266
        return layout_res