"src/targets/vscode:/vscode.git/clone" did not exist on "8fced808ca6143e3a20815bbe572e2306a0a0fda"
batch_analyze.py 11.2 KB
Newer Older
1
2
3
4
5
import time

import cv2
import torch
from loguru import logger
6
from tqdm import tqdm
7
8

from magic_pdf.config.constants import MODEL_NAME
9
from magic_pdf.libs.config_reader import get_table_recog_config
10
from magic_pdf.model.sub_modules.model_init import AtomModelSingleton
11
from magic_pdf.model.sub_modules.model_utils import (
icecraft's avatar
icecraft committed
12
    clean_vram, crop_img, get_res_list_from_layout_res)
13
from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.ocr_utils import (
icecraft's avatar
icecraft committed
14
    get_adjusted_mfdetrec_res, get_ocr_result_list)
15
from magic_pdf.model.sub_modules.table.rapidtable.rapid_table import RapidTableModel
16

17
YOLO_LAYOUT_BASE_BATCH_SIZE = 1
18
19
20
21
22
MFD_BASE_BATCH_SIZE = 1
MFR_BASE_BATCH_SIZE = 16


class BatchAnalyze:
23
24
    def __init__(self, model_manager, batch_ratio: int, show_log, layout_model, formula_enable, table_enable):
        self.model_manager = model_manager
25
        self.batch_ratio = batch_ratio
26
27
28
29
30
31
32
33
34
        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 []
    
35
        images_layout_res = []
36
        layout_start_time = time.time()
37
38
39
40
41
        _, 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]

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

53
            images_layout_res += self.model.layout_model.batch_predict(
54
55
                # layout_images, self.batch_ratio * YOLO_LAYOUT_BASE_BATCH_SIZE
                layout_images, YOLO_LAYOUT_BASE_BATCH_SIZE
56
57
            )

58
59
60
        # logger.info(
        #     f'layout time: {round(time.time() - layout_start_time, 2)}, image num: {len(images)}'
        # )
61

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

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

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

91
92
        ocr_res_list_all_page = []
        table_res_list_all_page = []
93
        for index in range(len(images)):
94
            _, ocr_enable, _lang = images_with_extra_info[index]
95
            layout_res = images_layout_res[index]
96
            np_array_img = images[index]
97
98
99
100

            ocr_res_list, table_res_list, single_page_mfdetrec_res = (
                get_res_list_from_layout_res(layout_res)
            )
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

            ocr_res_list_all_page.append({'ocr_res_list':ocr_res_list,
                                          'lang':_lang,
                                          'ocr_enable':ocr_enable,
                                          'np_array_img':np_array_img,
                                          'single_page_mfdetrec_res':single_page_mfdetrec_res,
                                          'layout_res':layout_res,
                                          })
            table_res_list_all_page.append({'table_res_list':table_res_list,
                                            'lang':_lang,
                                            'np_array_img':np_array_img,
                                          })

        # 文本框检测
        det_start = time.time()
        det_count = 0
        # for ocr_res_list_dict in ocr_res_list_all_page:
        for ocr_res_list_dict in tqdm(ocr_res_list_all_page, desc="OCR-det Predict"):
119
            # Process each area that requires OCR processing
120
121
122
123
124
125
126
127
128
129
            _lang = ocr_res_list_dict['lang']
            # Get OCR results for this language's images
            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
            )
            for res in ocr_res_list_dict['ocr_res_list']:
130
                new_image, useful_list = crop_img(
131
                    res, ocr_res_list_dict['np_array_img'], crop_paste_x=50, crop_paste_y=50
132
133
                )
                adjusted_mfdetrec_res = get_adjusted_mfdetrec_res(
134
                    ocr_res_list_dict['single_page_mfdetrec_res'], useful_list
135
136
                )

137
                # OCR-det
138
                new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)
139
                ocr_res = ocr_model.ocr(
140
141
                    new_image, mfd_res=adjusted_mfdetrec_res, rec=False
                )[0]
142
143
144

                # Integration results
                if ocr_res:
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
                    ocr_result_list = get_ocr_result_list(ocr_res, useful_list, ocr_res_list_dict['ocr_enable'], new_image, _lang)
                    ocr_res_list_dict['layout_res'].extend(ocr_result_list)
            det_count += len(ocr_res_list_dict['ocr_res_list'])
        # logger.info(f'ocr-det time: {round(time.time()-det_start, 2)}, image num: {det_count}')


        # 表格识别 table recognition
        if self.model.apply_table:
            table_start = time.time()
            table_count = 0
            # for table_res_list_dict in table_res_list_all_page:
            for table_res_list_dict in tqdm(table_res_list_all_page, desc="Table Predict"):
                _lang = table_res_list_dict['lang']
                atom_model_manager = AtomModelSingleton()
                ocr_engine = atom_model_manager.get_atom_model(
                    atom_model_name='ocr',
                    ocr_show_log=False,
                    det_db_box_thresh=0.5,
                    det_db_unclip_ratio=1.6,
                    lang=_lang
                )
                table_model = atom_model_manager.get_atom_model(
                    atom_model_name='table',
                    table_model_name='rapid_table',
                    table_model_path='',
                    table_max_time=400,
                    device='cpu',
                    ocr_engine=ocr_engine,
                    table_sub_model_name='slanet_plus'
                )
                for res in table_res_list_dict['table_res_list']:
                    new_image, _ = crop_img(res, table_res_list_dict['np_array_img'])
                    html_code, table_cell_bboxes, logic_points, elapse = table_model.predict(new_image)
178
179
180
                    # 判断是否返回正常
                    if html_code:
                        expected_ending = html_code.strip().endswith(
icecraft's avatar
icecraft committed
181
182
                            '</html>'
                        ) or html_code.strip().endswith('</table>')
183
                        if expected_ending:
icecraft's avatar
icecraft committed
184
                            res['html'] = html_code
185
186
                        else:
                            logger.warning(
icecraft's avatar
icecraft committed
187
                                'table recognition processing fails, not found expected HTML table end'
188
189
190
                            )
                    else:
                        logger.warning(
icecraft's avatar
icecraft committed
191
                            'table recognition processing fails, not get html return'
192
                        )
193
194
                table_count += len(table_res_list_dict['table_res_list'])
            # logger.info(f'table time: {round(time.time() - table_start, 2)}, image num: {table_count}')
195

196
197
198
199
        # 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

200
201
202
        for layout_res in images_layout_res:
            for layout_res_item in layout_res:
                if layout_res_item['category_id'] in [15]:
203
204
205
206
207
208
209
210
211
212
213
214
215
                    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
216
                        layout_res_item.pop('np_img')
217
218
219
220
221
222
223
224
225
226
227
228
229
230
                        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
231
232
233
234
235
236
237
                    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
                    )
238
                    ocr_res_list = ocr_model.ocr(img_crop_list, det=False, tqdm_enable=True)[0]
239
240
241

                    # Verify we have matching counts
                    assert len(ocr_res_list) == len(
242
                        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}'
243
244

                    # Process OCR results for this language
245
                    for index, layout_res_item in enumerate(need_ocr_lists_by_lang[lang]):
246
247
248
249
250
                        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)
251

252
            rec_time += time.time() - rec_start
253
            # logger.info(f'ocr-rec time: {round(rec_time, 2)}, total images processed: {total_processed}')
254
255
256



257
        return images_layout_res