batch_analyze.py 10.3 KB
Newer Older
1
2
3
4
5
6
7
import time

import cv2
import torch
from loguru import logger

from magic_pdf.config.constants import MODEL_NAME
8
from magic_pdf.model.sub_modules.model_init import AtomModelSingleton
9
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.paddleocr2pytorch.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
MFD_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16


class BatchAnalyze:
20
21
    def __init__(self, model_manager, batch_ratio: int, show_log, layout_model, formula_enable, table_enable):
        self.model_manager = model_manager
22
        self.batch_ratio = batch_ratio
23
24
25
26
27
28
29
30
31
        self.show_log = show_log
        self.layout_model = layout_model
        self.formula_enable = formula_enable
        self.table_enable = table_enable

    def __call__(self, images_with_extra_info: list) -> list:
        if len(images_with_extra_info) == 0:
            return []
    
32
        images_layout_res = []
33
        layout_start_time = time.time()
34
35
36
37
38
        _, fst_ocr, fst_lang = images_with_extra_info[0]
        self.model = self.model_manager.get_model(fst_ocr, self.show_log, fst_lang, self.layout_model, self.formula_enable, self.table_enable)

        images = [image for image, _, _ in images_with_extra_info]

39
40
41
42
43
44
45
        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
46
47
            layout_images = []
            for image_index, image in enumerate(images):
48
                layout_images.append(image)
49

50
            images_layout_res += self.model.layout_model.batch_predict(
51
52
                # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
                layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
53
54
            )

55
        logger.info(
icecraft's avatar
icecraft committed
56
            f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
57
58
        )

59
60
        if self.model.apply_formula:
            # 公式检测
61
            mfd_start_time = time.time()
62
            images_mfd_res = self.model.mfd_model.batch_predict(
63
64
                # images, self.batch_ratio * MFD_BASE_BATCH_SIZE
                images, MFD_BASE_BATCH_SIZE
65
            )
66
            logger.info(
icecraft's avatar
icecraft committed
67
                f'mfd time: {round(time.time() - mfd_start_time, 2)}, image num: {len(images)}'
68
            )
69
70

            # 公式识别
71
            mfr_start_time = time.time()
72
73
74
75
76
            images_formula_list = self.model.mfr_model.batch_predict(
                images_mfd_res,
                images,
                batch_size=self.batch_ratio * MFR_BASE_BATCH_SIZE,
            )
77
            mfr_count = 0
78
79
            for image_index in range(len(images)):
                images_layout_res[image_index] += images_formula_list[image_index]
80
                mfr_count += len(images_formula_list[image_index])
81
            logger.info(
82
                f'mfr time: {round(time.time() - mfr_start_time, 2)}, image num: {mfr_count}'
83
            )
84
85
86
87

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

88
89
        det_time = 0
        det_count = 0
90
91
        table_time = 0
        table_count = 0
92
93
        # reference: magic_pdf/model/doc_analyze_by_custom_model.py:doc_analyze
        for index in range(len(images)):
94
95
            _, ocr_enable, _lang = images_with_extra_info[index]
            self.model = self.model_manager.get_model(ocr_enable, self.show_log, _lang, self.layout_model, self.formula_enable, self.table_enable)
96
            layout_res = images_layout_res[index]
97
            np_array_img = images[index]
98
99
100
101
102

            ocr_res_list, table_res_list, single_page_mfdetrec_res = (
                get_res_list_from_layout_res(layout_res)
            )
            # ocr识别
103
            det_start = time.time()
104
105
106
            # Process each area that requires OCR processing
            for res in ocr_res_list:
                new_image, useful_list = crop_img(
107
                    res, np_array_img, crop_paste_x=50, crop_paste_y=50
108
109
110
111
112
113
                )
                adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
                    single_page_mfdetrec_res, useful_list
                )

                # OCR recognition
114
                new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
115

116
117
118
119
120
121
122
123
                # if ocr_enable:
                #     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]
124
125
126

                # Integration results
                if ocr_res:
127
                    ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_enable, new_image, _lang)
128
                    layout_res.extend(ocr_result_list)
129
130
            det_time += time.time() - det_start
            det_count += len(ocr_res_list)
131
132
133
134
135

            # 表格识别 table recognition
            if self.model.apply_table:
                table_start = time.time()
                for res in table_res_list:
136
                    new_image, _ = crop_img(res, np_array_img)
137
138
139
140
141
                    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
142
                                new_image, 'html'
143
144
145
146
147
148
                            )
                            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:
149
                        html_code, table_cell_bboxes, logic_points, elapse = (
150
151
152
153
154
                            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
155
                            f'table recognition processing exceeds max time {self.model.table_max_time}s'
156
157
158
159
                        )
                    # 判断是否返回正常
                    if html_code:
                        expected_ending = html_code.strip().endswith(
icecraft's avatar
icecraft committed
160
161
                            '</html>'
                        ) or html_code.strip().endswith('</table>')
162
                        if expected_ending:
icecraft's avatar
icecraft committed
163
                            res['html'] = html_code
164
165
                        else:
                            logger.warning(
icecraft's avatar
icecraft committed
166
                                'table recognition processing fails, not found expected HTML table end'
167
168
169
                            )
                    else:
                        logger.warning(
icecraft's avatar
icecraft committed
170
                            'table recognition processing fails, not get html return'
171
                        )
172
173
174
                table_time += time.time() - table_start
                table_count += len(table_res_list)

175
176

        logger.info(f'ocr-det time: {round(det_time, 2)}, image num: {det_count}')
177
        if self.model.apply_table:
icecraft's avatar
icecraft committed
178
            logger.info(f'table time: {round(table_time, 2)}, image num: {table_count}')
179

180
181
182
183
        # Create dictionaries to store items by language
        need_ocr_lists_by_lang = {}  # Dict of lists for each language
        img_crop_lists_by_lang = {}  # Dict of lists for each language

184
185
186
        for layout_res in images_layout_res:
            for layout_res_item in layout_res:
                if layout_res_item['category_id'] in [15]:
187
188
189
190
191
192
193
194
195
196
197
198
199
                    if 'np_img' in layout_res_item and 'lang' in layout_res_item:
                        lang = layout_res_item['lang']

                        # Initialize lists for this language if not exist
                        if lang not in need_ocr_lists_by_lang:
                            need_ocr_lists_by_lang[lang] = []
                            img_crop_lists_by_lang[lang] = []

                        # Add to the appropriate language-specific lists
                        need_ocr_lists_by_lang[lang].append(layout_res_item)
                        img_crop_lists_by_lang[lang].append(layout_res_item['np_img'])

                        # Remove the fields after adding to lists
200
                        layout_res_item.pop('np_img')
201
202
203
204
205
206
207
208
209
210
211
212
213
214
                        layout_res_item.pop('lang')


        if len(img_crop_lists_by_lang) > 0:

            # Process OCR by language
            rec_time = 0
            rec_start = time.time()
            total_processed = 0

            # Process each language separately
            for lang, img_crop_list in img_crop_lists_by_lang.items():
                if len(img_crop_list) > 0:
                    # Get OCR results for this language's images
215
216
217
218
219
220
221
222
                    atom_model_manager = AtomModelSingleton()
                    ocr_model = atom_model_manager.get_atom_model(
                        atom_model_name='ocr',
                        ocr_show_log=False,
                        det_db_box_thresh=0.3,
                        lang=lang
                    )
                    ocr_res_list = ocr_model.ocr(img_crop_list, det=False)[0]
223
224
225

                    # Verify we have matching counts
                    assert len(ocr_res_list) == len(
226
                        need_ocr_lists_by_lang[lang]), f'ocr_res_list: {len(ocr_res_list)}, need_ocr_list: {len(need_ocr_lists_by_lang[lang])} for lang: {lang}'
227
228

                    # Process OCR results for this language
229
                    for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
230
231
232
233
234
                        ocr_text, ocr_score = ocr_res_list[index]
                        layout_res_item['text'] = ocr_text
                        layout_res_item['score'] = float(round(ocr_score, 2))

                    total_processed += len(img_crop_list)
235

236
237
            rec_time += time.time() - rec_start
            logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
238
239
240



241
        return images_layout_res