"vscode:/vscode.git/clone" did not exist on "155cbb51f09c30a02ad576de380e268e25aa881a"
draw_bbox.py 17.1 KB
Newer Older
1
import fitz
2
from magic_pdf.config.constants import CROSS_PAGE
3
4
5
from magic_pdf.config.ocr_content_type import (BlockType, CategoryId,
                                               ContentType)
from magic_pdf.data.dataset import Dataset
6
from magic_pdf.model.magic_model import MagicModel
赵小蒙's avatar
赵小蒙 committed
7

赵小蒙's avatar
赵小蒙 committed
8

赵小蒙's avatar
赵小蒙 committed
9
def draw_bbox_without_number(i, bbox_list, page, rgb_config, fill_config):
10
11
12
13
14
15
16
    new_rgb = []
    for item in rgb_config:
        item = float(item) / 255
        new_rgb.append(item)
    page_data = bbox_list[i]
    for bbox in page_data:
        x0, y0, x1, y1 = bbox
赵小蒙's avatar
赵小蒙 committed
17
        rect_coords = fitz.Rect(x0, y0, x1, y1)  # Define the rectangle
赵小蒙's avatar
赵小蒙 committed
18
        if fill_config:
许瑞's avatar
许瑞 committed
19
20
21
22
23
24
25
26
            page.draw_rect(
                rect_coords,
                color=None,
                fill=new_rgb,
                fill_opacity=0.3,
                width=0.5,
                overlay=True,
            )  # Draw the rectangle
赵小蒙's avatar
赵小蒙 committed
27
        else:
许瑞's avatar
许瑞 committed
28
29
30
31
32
33
34
35
            page.draw_rect(
                rect_coords,
                color=new_rgb,
                fill=None,
                fill_opacity=1,
                width=0.5,
                overlay=True,
            )  # Draw the rectangle
赵小蒙's avatar
赵小蒙 committed
36

37

38
def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config, draw_bbox=True):
赵小蒙's avatar
赵小蒙 committed
39
40
41
42
43
44
45
46
    new_rgb = []
    for item in rgb_config:
        item = float(item) / 255
        new_rgb.append(item)
    page_data = bbox_list[i]
    for j, bbox in enumerate(page_data):
        x0, y0, x1, y1 = bbox
        rect_coords = fitz.Rect(x0, y0, x1, y1)  # Define the rectangle
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        if draw_bbox:
            if fill_config:
                page.draw_rect(
                    rect_coords,
                    color=None,
                    fill=new_rgb,
                    fill_opacity=0.3,
                    width=0.5,
                    overlay=True,
                )  # Draw the rectangle
            else:
                page.draw_rect(
                    rect_coords,
                    color=new_rgb,
                    fill=None,
                    fill_opacity=1,
                    width=0.5,
                    overlay=True,
                )  # Draw the rectangle
许瑞's avatar
许瑞 committed
66
        page.insert_text(
67
            (x1 + 2, y0 + 10), str(j + 1), fontsize=10, color=new_rgb
赵小蒙's avatar
赵小蒙 committed
68
        )  # Insert the index in the top left corner of the rectangle
赵小蒙's avatar
赵小蒙 committed
69
70


71
def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
赵小蒙's avatar
赵小蒙 committed
72
    dropped_bbox_list = []
73
74
    tables_list, tables_body_list = [], []
    tables_caption_list, tables_footnote_list = [], []
许瑞's avatar
许瑞 committed
75
    imgs_list, imgs_body_list, imgs_caption_list = [], [], []
76
    imgs_footnote_list = []
许瑞's avatar
许瑞 committed
77
78
79
    titles_list = []
    texts_list = []
    interequations_list = []
80
81
    lists_list = []
    indexs_list = []
赵小蒙's avatar
赵小蒙 committed
82
    for page in pdf_info:
83

赵小蒙's avatar
赵小蒙 committed
84
        page_dropped_list = []
许瑞's avatar
许瑞 committed
85
        tables, tables_body, tables_caption, tables_footnote = [], [], [], []
86
        imgs, imgs_body, imgs_caption, imgs_footnote = [], [], [], []
许瑞's avatar
许瑞 committed
87
88
89
        titles = []
        texts = []
        interequations = []
90
        lists = []
91
        indices = []
92

93
94
        for dropped_bbox in page['discarded_blocks']:
            page_dropped_list.append(dropped_bbox['bbox'])
赵小蒙's avatar
赵小蒙 committed
95
        dropped_bbox_list.append(page_dropped_list)
96
97
98
        for block in page['para_blocks']:
            bbox = block['bbox']
            if block['type'] == BlockType.Table:
许瑞's avatar
许瑞 committed
99
                tables.append(bbox)
100
101
102
                for nested_block in block['blocks']:
                    bbox = nested_block['bbox']
                    if nested_block['type'] == BlockType.TableBody:
许瑞's avatar
许瑞 committed
103
                        tables_body.append(bbox)
104
                    elif nested_block['type'] == BlockType.TableCaption:
许瑞's avatar
许瑞 committed
105
                        tables_caption.append(bbox)
106
                    elif nested_block['type'] == BlockType.TableFootnote:
许瑞's avatar
许瑞 committed
107
                        tables_footnote.append(bbox)
108
            elif block['type'] == BlockType.Image:
许瑞's avatar
许瑞 committed
109
                imgs.append(bbox)
110
111
112
                for nested_block in block['blocks']:
                    bbox = nested_block['bbox']
                    if nested_block['type'] == BlockType.ImageBody:
许瑞's avatar
许瑞 committed
113
                        imgs_body.append(bbox)
114
                    elif nested_block['type'] == BlockType.ImageCaption:
许瑞's avatar
许瑞 committed
115
                        imgs_caption.append(bbox)
116
117
                    elif nested_block['type'] == BlockType.ImageFootnote:
                        imgs_footnote.append(bbox)
118
            elif block['type'] == BlockType.Title:
许瑞's avatar
许瑞 committed
119
                titles.append(bbox)
120
            elif block['type'] == BlockType.Text:
许瑞's avatar
许瑞 committed
121
                texts.append(bbox)
122
            elif block['type'] == BlockType.InterlineEquation:
许瑞's avatar
许瑞 committed
123
                interequations.append(bbox)
124
125
126
            elif block['type'] == BlockType.List:
                lists.append(bbox)
            elif block['type'] == BlockType.Index:
127
                indices.append(bbox)
128

许瑞's avatar
许瑞 committed
129
130
131
132
133
134
135
        tables_list.append(tables)
        tables_body_list.append(tables_body)
        tables_caption_list.append(tables_caption)
        tables_footnote_list.append(tables_footnote)
        imgs_list.append(imgs)
        imgs_body_list.append(imgs_body)
        imgs_caption_list.append(imgs_caption)
136
        imgs_footnote_list.append(imgs_footnote)
许瑞's avatar
许瑞 committed
137
138
139
        titles_list.append(titles)
        texts_list.append(texts)
        interequations_list.append(interequations)
140
        lists_list.append(lists)
141
        indexs_list.append(indices)
许瑞's avatar
许瑞 committed
142

143
144
    layout_bbox_list = []

145
146
147
148
149
    table_type_order = {
        'table_caption': 1,
        'table_body': 2,
        'table_footnote': 3
    }
150
151
152
    for page in pdf_info:
        page_block_list = []
        for block in page['para_blocks']:
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
            if block['type'] in [
                BlockType.Text,
                BlockType.Title,
                BlockType.InterlineEquation,
                BlockType.List,
                BlockType.Index,
            ]:
                bbox = block['bbox']
                page_block_list.append(bbox)
            elif block['type'] in [BlockType.Image]:
                for sub_block in block['blocks']:
                    bbox = sub_block['bbox']
                    page_block_list.append(bbox)
            elif block['type'] in [BlockType.Table]:
                sorted_blocks = sorted(block['blocks'], key=lambda x: table_type_order[x['type']])
                for sub_block in sorted_blocks:
                    bbox = sub_block['bbox']
                    page_block_list.append(bbox)

172
173
        layout_bbox_list.append(page_block_list)

174
    pdf_docs = fitz.open('pdf', pdf_bytes)
175

176
    for i, page in enumerate(pdf_docs):
177

178
        draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158], True)
179
        # draw_bbox_without_number(i, tables_list, page, [153, 153, 0], True)  # color !
180
181
182
        draw_bbox_without_number(i, tables_body_list, page, [204, 204, 0], True)
        draw_bbox_without_number(i, tables_caption_list, page, [255, 255, 102], True)
        draw_bbox_without_number(i, tables_footnote_list, page, [229, 255, 204], True)
183
        # draw_bbox_without_number(i, imgs_list, page, [51, 102, 0], True)
许瑞's avatar
许瑞 committed
184
        draw_bbox_without_number(i, imgs_body_list, page, [153, 255, 51], True)
185
186
        draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255], True)
        draw_bbox_without_number(i, imgs_footnote_list, page, [255, 178, 102], True),
许瑞's avatar
许瑞 committed
187
188
        draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)
        draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)
189
        draw_bbox_without_number(i, interequations_list, page, [0, 255, 0], True)
190
191
        draw_bbox_without_number(i, lists_list, page, [40, 169, 92], True)
        draw_bbox_without_number(i, indexs_list, page, [40, 169, 92], True)
192

193
194
195
        draw_bbox_with_number(
            i, layout_bbox_list, page, [255, 0, 0], False, draw_bbox=False
        )
许瑞's avatar
许瑞 committed
196

197
    # Save the PDF
198
    pdf_docs.save(f'{out_path}/{filename}')
199

许瑞's avatar
许瑞 committed
200

201
def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
202
203
    text_list = []
    inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
204
    interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
205
206
    image_list = []
    table_list = []
赵小蒙's avatar
赵小蒙 committed
207
    dropped_list = []
208
209
    next_page_text_list = []
    next_page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
210
211

    def get_span_info(span):
212
        if span['type'] == ContentType.Text:
赵小蒙's avatar
赵小蒙 committed
213
            if span.get(CROSS_PAGE, False):
214
                next_page_text_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
215
            else:
216
217
                page_text_list.append(span['bbox'])
        elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
218
            if span.get(CROSS_PAGE, False):
219
                next_page_inline_equation_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
220
            else:
221
222
223
224
225
226
227
                page_inline_equation_list.append(span['bbox'])
        elif span['type'] == ContentType.InterlineEquation:
            page_interline_equation_list.append(span['bbox'])
        elif span['type'] == ContentType.Image:
            page_image_list.append(span['bbox'])
        elif span['type'] == ContentType.Table:
            page_table_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
228

赵小蒙's avatar
赵小蒙 committed
229
    for page in pdf_info:
230
231
        page_text_list = []
        page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
232
        page_interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
233
234
        page_image_list = []
        page_table_list = []
赵小蒙's avatar
赵小蒙 committed
235
        page_dropped_list = []
236
237
238
239

        # 将跨页的span放到移动到下一页的列表中
        if len(next_page_text_list) > 0:
            page_text_list.extend(next_page_text_list)
赵小蒙's avatar
赵小蒙 committed
240
            next_page_text_list.clear()
241
242
        if len(next_page_inline_equation_list) > 0:
            page_inline_equation_list.extend(next_page_inline_equation_list)
赵小蒙's avatar
赵小蒙 committed
243
            next_page_inline_equation_list.clear()
244

赵小蒙's avatar
赵小蒙 committed
245
        # 构造dropped_list
246
247
248
249
250
        for block in page['discarded_blocks']:
            if block['type'] == BlockType.Discarded:
                for line in block['lines']:
                    for span in line['spans']:
                        page_dropped_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
251
252
        dropped_list.append(page_dropped_list)
        # 构造其余useful_list
253
254
        # for block in page['para_blocks']:  # span直接用分段合并前的结果就可以
        for block in page['preproc_blocks']:
255
            if block['type'] in [
256
257
258
                BlockType.Text,
                BlockType.Title,
                BlockType.InterlineEquation,
259
260
                BlockType.List,
                BlockType.Index,
许瑞's avatar
许瑞 committed
261
            ]:
262
263
                for line in block['lines']:
                    for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
264
                        get_span_info(span)
265
266
267
268
            elif block['type'] in [BlockType.Image, BlockType.Table]:
                for sub_block in block['blocks']:
                    for line in sub_block['lines']:
                        for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
269
                            get_span_info(span)
270
271
        text_list.append(page_text_list)
        inline_equation_list.append(page_inline_equation_list)
赵小蒙's avatar
赵小蒙 committed
272
        interline_equation_list.append(page_interline_equation_list)
赵小蒙's avatar
赵小蒙 committed
273
274
        image_list.append(page_image_list)
        table_list.append(page_table_list)
275
    pdf_docs = fitz.open('pdf', pdf_bytes)
276
    for i, page in enumerate(pdf_docs):
277
        # 获取当前页面的数据
赵小蒙's avatar
赵小蒙 committed
278
        draw_bbox_without_number(i, text_list, page, [255, 0, 0], False)
279
280
        draw_bbox_without_number(i, inline_equation_list, page, [0, 255, 0], False)
        draw_bbox_without_number(i, interline_equation_list, page, [0, 0, 255], False)
赵小蒙's avatar
赵小蒙 committed
281
282
        draw_bbox_without_number(i, image_list, page, [255, 204, 0], False)
        draw_bbox_without_number(i, table_list, page, [204, 0, 255], False)
赵小蒙's avatar
赵小蒙 committed
283
        draw_bbox_without_number(i, dropped_list, page, [158, 158, 158], False)
284
285

    # Save the PDF
286
    pdf_docs.save(f'{out_path}/{filename}')
287
288


289
def draw_model_bbox(model_list, dataset: Dataset, out_path, filename):
290
291
    dropped_bbox_list = []
    tables_body_list, tables_caption_list, tables_footnote_list = [], [], []
292
    imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []
293
294
295
    titles_list = []
    texts_list = []
    interequations_list = []
296
    magic_model = MagicModel(model_list, dataset)
297
298
299
    for i in range(len(model_list)):
        page_dropped_list = []
        tables_body, tables_caption, tables_footnote = [], [], []
300
        imgs_body, imgs_caption, imgs_footnote = [], [], []
301
302
303
304
        titles = []
        texts = []
        interequations = []
        page_info = magic_model.get_model_list(i)
305
        layout_dets = page_info['layout_dets']
306
        for layout_det in layout_dets:
307
308
            bbox = layout_det['bbox']
            if layout_det['category_id'] == CategoryId.Text:
309
                texts.append(bbox)
310
            elif layout_det['category_id'] == CategoryId.Title:
311
                titles.append(bbox)
312
            elif layout_det['category_id'] == CategoryId.TableBody:
313
                tables_body.append(bbox)
314
            elif layout_det['category_id'] == CategoryId.TableCaption:
315
                tables_caption.append(bbox)
316
            elif layout_det['category_id'] == CategoryId.TableFootnote:
317
                tables_footnote.append(bbox)
318
            elif layout_det['category_id'] == CategoryId.ImageBody:
319
                imgs_body.append(bbox)
320
            elif layout_det['category_id'] == CategoryId.ImageCaption:
321
                imgs_caption.append(bbox)
322
            elif layout_det['category_id'] == CategoryId.InterlineEquation_YOLO:
323
                interequations.append(bbox)
324
            elif layout_det['category_id'] == CategoryId.Abandon:
325
                page_dropped_list.append(bbox)
326
327
            elif layout_det['category_id'] == CategoryId.ImageFootnote:
                imgs_footnote.append(bbox)
328
329
330
331
332
333
334
335
336
337

        tables_body_list.append(tables_body)
        tables_caption_list.append(tables_caption)
        tables_footnote_list.append(tables_footnote)
        imgs_body_list.append(imgs_body)
        imgs_caption_list.append(imgs_caption)
        titles_list.append(titles)
        texts_list.append(texts)
        interequations_list.append(interequations)
        dropped_bbox_list.append(page_dropped_list)
338
        imgs_footnote_list.append(imgs_footnote)
339

340
341
    for i in range(len(dataset)):
        page = dataset.get_page(i)
342
343
344
        draw_bbox_with_number(
            i, dropped_bbox_list, page, [158, 158, 158], True
        )  # color !
345
        draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)
346
347
        draw_bbox_with_number(i, tables_caption_list, page, [255, 255, 102], True)
        draw_bbox_with_number(i, tables_footnote_list, page, [229, 255, 204], True)
348
        draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)
349
350
        draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255], True)
        draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102], True)
351
352
353
354
355
        draw_bbox_with_number(i, titles_list, page, [102, 102, 255], True)
        draw_bbox_with_number(i, texts_list, page, [153, 0, 76], True)
        draw_bbox_with_number(i, interequations_list, page, [0, 255, 0], True)

    # Save the PDF
356
    dataset.dump_to_file(f'{out_path}/{filename}')
357
358


359
def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
360
361
362
    layout_bbox_list = []

    for page in pdf_info:
363
364
        page_line_list = []
        for block in page['preproc_blocks']:
365
            if block['type'] in [BlockType.Text, BlockType.Title, BlockType.InterlineEquation]:
366
                for line in block['lines']:
367
                    bbox = line['bbox']
368
369
                    index = line['index']
                    page_line_list.append({'index': index, 'bbox': bbox})
370
371
372
            if block['type'] in [BlockType.Image, BlockType.Table]:
                for sub_block in block['blocks']:
                    if sub_block['type'] in [BlockType.ImageBody, BlockType.TableBody]:
373
374
375
376
377
378
379
380
381
382
                        if len(sub_block['virtual_lines']) > 0 and sub_block['virtual_lines'][0].get('index', None) is not None:
                            for line in sub_block['virtual_lines']:
                                bbox = line['bbox']
                                index = line['index']
                                page_line_list.append({'index': index, 'bbox': bbox})
                        else:
                            for line in sub_block['lines']:
                                bbox = line['bbox']
                                index = line['index']
                                page_line_list.append({'index': index, 'bbox': bbox})
383
384
385
386
387
                    elif sub_block['type'] in [BlockType.ImageCaption, BlockType.TableCaption, BlockType.ImageFootnote, BlockType.TableFootnote]:
                        for line in sub_block['lines']:
                            bbox = line['bbox']
                            index = line['index']
                            page_line_list.append({'index': index, 'bbox': bbox})
388
389
390
391
392
393
        sorted_bboxes = sorted(page_line_list, key=lambda x: x['index'])
        layout_bbox_list.append(sorted_bbox['bbox'] for sorted_bbox in sorted_bboxes)
    pdf_docs = fitz.open('pdf', pdf_bytes)
    for i, page in enumerate(pdf_docs):
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)

394
    pdf_docs.save(f'{out_path}/{filename}')
395
396
397
398
399
400
401
402
403
404
405


def draw_layout_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
    layout_bbox_list = []

    for page in pdf_info:
        page_block_list = []
        for block in page['para_blocks']:
            bbox = block['bbox']
            page_block_list.append(bbox)
        layout_bbox_list.append(page_block_list)
406
407
    pdf_docs = fitz.open('pdf', pdf_bytes)
    for i, page in enumerate(pdf_docs):
408
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
409
410

    pdf_docs.save(f'{out_path}/{filename}_layout_sort.pdf')