draw_bbox.py 15.3 KB
Newer Older
1
2
import time

3
4
import torch

5
from magic_pdf.libs.commons import fitz  # PyMuPDF
6
7
from magic_pdf.libs.Constants import CROSS_PAGE
from magic_pdf.libs.ocr_content_type import BlockType, CategoryId, ContentType
8
from magic_pdf.model.magic_model import MagicModel
赵小蒙's avatar
赵小蒙 committed
9

赵小蒙's avatar
赵小蒙 committed
10

赵小蒙's avatar
赵小蒙 committed
11
def draw_bbox_without_number(i, bbox_list, page, rgb_config, fill_config):
12
13
14
15
16
17
18
    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
19
        rect_coords = fitz.Rect(x0, y0, x1, y1)  # Define the rectangle
赵小蒙's avatar
赵小蒙 committed
20
        if fill_config:
许瑞's avatar
许瑞 committed
21
22
23
24
25
26
27
28
            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
29
        else:
许瑞's avatar
许瑞 committed
30
31
32
33
34
35
36
37
            page.draw_rect(
                rect_coords,
                color=new_rgb,
                fill=None,
                fill_opacity=1,
                width=0.5,
                overlay=True,
            )  # Draw the rectangle
赵小蒙's avatar
赵小蒙 committed
38

39

40
def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config, width=0.5):
赵小蒙's avatar
赵小蒙 committed
41
42
43
44
45
46
47
48
    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
赵小蒙's avatar
赵小蒙 committed
49
        if fill_config:
许瑞's avatar
许瑞 committed
50
51
52
53
54
            page.draw_rect(
                rect_coords,
                color=None,
                fill=new_rgb,
                fill_opacity=0.3,
55
                width=width,
许瑞's avatar
许瑞 committed
56
57
                overlay=True,
            )  # Draw the rectangle
赵小蒙's avatar
赵小蒙 committed
58
        else:
许瑞's avatar
许瑞 committed
59
60
61
62
63
            page.draw_rect(
                rect_coords,
                color=new_rgb,
                fill=None,
                fill_opacity=1,
64
                width=width,
许瑞's avatar
许瑞 committed
65
66
67
                overlay=True,
            )  # Draw the rectangle
        page.insert_text(
68
            (x1+2, y0 + 10), str(j + 1), fontsize=10, color=new_rgb
赵小蒙's avatar
赵小蒙 committed
69
        )  # Insert the index in the top left corner of the rectangle
赵小蒙's avatar
赵小蒙 committed
70
71


72
def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
73
    # layout_bbox_list = []
赵小蒙's avatar
赵小蒙 committed
74
    dropped_bbox_list = []
75
76
    tables_list, tables_body_list = [], []
    tables_caption_list, tables_footnote_list = [], []
许瑞's avatar
许瑞 committed
77
    imgs_list, imgs_body_list, imgs_caption_list = [], [], []
78
    imgs_footnote_list = []
许瑞's avatar
许瑞 committed
79
80
81
    titles_list = []
    texts_list = []
    interequations_list = []
赵小蒙's avatar
赵小蒙 committed
82
    for page in pdf_info:
83
        # page_layout_list = []
赵小蒙'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
91
92
        # for layout in page['layout_bboxes']:
        #     page_layout_list.append(layout['layout_bbox'])
        # layout_bbox_list.append(page_layout_list)
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
124
125
126
127
128
129
130
                interequations.append(bbox)
        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)
131
        imgs_footnote_list.append(imgs_footnote)
许瑞's avatar
许瑞 committed
132
133
134
135
        titles_list.append(titles)
        texts_list.append(texts)
        interequations_list.append(interequations)

136
137
138
139
140
141
142
143
144
    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)

145
    pdf_docs = fitz.open('pdf', pdf_bytes)
146
    for i, page in enumerate(pdf_docs):
147
        # draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
148
149
150
151
152
153
154
155
156
157
        draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158],
                                 True)
        draw_bbox_without_number(i, tables_list, page, [153, 153, 0],
                                 True)  # color !
        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)
许瑞's avatar
许瑞 committed
158
159
        draw_bbox_without_number(i, imgs_list, page, [51, 102, 0], True)
        draw_bbox_without_number(i, imgs_body_list, page, [153, 255, 51], True)
160
161
        draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255],
                                 True)
162
        draw_bbox_without_number(i, imgs_footnote_list, page, [255, 178, 102],
163
                              True),
许瑞's avatar
许瑞 committed
164
165
        draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)
        draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)
166
167
        draw_bbox_without_number(i, interequations_list, page, [0, 255, 0],
                                 True)
168
169
    for i, page in enumerate(pdf_docs):
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False, width=0)
许瑞's avatar
许瑞 committed
170

171
    # Save the PDF
172
    pdf_docs.save(f'{out_path}/{filename}_layout.pdf')
173

许瑞's avatar
许瑞 committed
174

175
def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
176
177
    text_list = []
    inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
178
    interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
179
180
    image_list = []
    table_list = []
赵小蒙's avatar
赵小蒙 committed
181
    dropped_list = []
182
183
    next_page_text_list = []
    next_page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
184
185

    def get_span_info(span):
186
        if span['type'] == ContentType.Text:
赵小蒙's avatar
赵小蒙 committed
187
            if span.get(CROSS_PAGE, False):
188
                next_page_text_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
189
            else:
190
191
                page_text_list.append(span['bbox'])
        elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
192
            if span.get(CROSS_PAGE, False):
193
                next_page_inline_equation_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
194
            else:
195
196
197
198
199
200
201
                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
202

赵小蒙's avatar
赵小蒙 committed
203
    for page in pdf_info:
204
205
        page_text_list = []
        page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
206
        page_interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
207
208
        page_image_list = []
        page_table_list = []
赵小蒙's avatar
赵小蒙 committed
209
        page_dropped_list = []
210
211
212
213

        # 将跨页的span放到移动到下一页的列表中
        if len(next_page_text_list) > 0:
            page_text_list.extend(next_page_text_list)
赵小蒙's avatar
赵小蒙 committed
214
            next_page_text_list.clear()
215
216
        if len(next_page_inline_equation_list) > 0:
            page_inline_equation_list.extend(next_page_inline_equation_list)
赵小蒙's avatar
赵小蒙 committed
217
            next_page_inline_equation_list.clear()
218

赵小蒙's avatar
赵小蒙 committed
219
        # 构造dropped_list
220
221
222
223
224
        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
225
226
        dropped_list.append(page_dropped_list)
        # 构造其余useful_list
227
228
        for block in page['para_blocks']:
            if block['type'] in [
229
230
231
                BlockType.Text,
                BlockType.Title,
                BlockType.InterlineEquation,
许瑞's avatar
许瑞 committed
232
            ]:
233
234
                for line in block['lines']:
                    for span in line['spans']:
赵小蒙's avatar
赵小蒙 committed
235
                        get_span_info(span)
236
237
238
239
            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
240
                            get_span_info(span)
241
242
        text_list.append(page_text_list)
        inline_equation_list.append(page_inline_equation_list)
赵小蒙's avatar
赵小蒙 committed
243
        interline_equation_list.append(page_interline_equation_list)
赵小蒙's avatar
赵小蒙 committed
244
245
        image_list.append(page_image_list)
        table_list.append(page_table_list)
246
    pdf_docs = fitz.open('pdf', pdf_bytes)
247
    for i, page in enumerate(pdf_docs):
248
        # 获取当前页面的数据
赵小蒙's avatar
赵小蒙 committed
249
        draw_bbox_without_number(i, text_list, page, [255, 0, 0], False)
250
251
        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
252
253
        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
254
        draw_bbox_without_number(i, dropped_list, page, [158, 158, 158], False)
255
256

    # Save the PDF
257
    pdf_docs.save(f'{out_path}/{filename}_spans.pdf')
258
259


260
def draw_model_bbox(model_list: list, pdf_bytes, out_path, filename):
261
262
    dropped_bbox_list = []
    tables_body_list, tables_caption_list, tables_footnote_list = [], [], []
263
    imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []
264
265
266
    titles_list = []
    texts_list = []
    interequations_list = []
267
    pdf_docs = fitz.open('pdf', pdf_bytes)
268
269
270
271
    magic_model = MagicModel(model_list, pdf_docs)
    for i in range(len(model_list)):
        page_dropped_list = []
        tables_body, tables_caption, tables_footnote = [], [], []
272
        imgs_body, imgs_caption, imgs_footnote = [], [], []
273
274
275
276
        titles = []
        texts = []
        interequations = []
        page_info = magic_model.get_model_list(i)
277
        layout_dets = page_info['layout_dets']
278
        for layout_det in layout_dets:
279
280
            bbox = layout_det['bbox']
            if layout_det['category_id'] == CategoryId.Text:
281
                texts.append(bbox)
282
            elif layout_det['category_id'] == CategoryId.Title:
283
                titles.append(bbox)
284
            elif layout_det['category_id'] == CategoryId.TableBody:
285
                tables_body.append(bbox)
286
            elif layout_det['category_id'] == CategoryId.TableCaption:
287
                tables_caption.append(bbox)
288
            elif layout_det['category_id'] == CategoryId.TableFootnote:
289
                tables_footnote.append(bbox)
290
            elif layout_det['category_id'] == CategoryId.ImageBody:
291
                imgs_body.append(bbox)
292
            elif layout_det['category_id'] == CategoryId.ImageCaption:
293
                imgs_caption.append(bbox)
294
            elif layout_det[
295
                'category_id'] == CategoryId.InterlineEquation_YOLO:
296
                interequations.append(bbox)
297
            elif layout_det['category_id'] == CategoryId.Abandon:
298
                page_dropped_list.append(bbox)
299
300
            elif layout_det['category_id'] == CategoryId.ImageFootnote:
                imgs_footnote.append(bbox)
301
302
303
304
305
306
307
308
309
310

        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)
311
        imgs_footnote_list.append(imgs_footnote)
312
313

    for i, page in enumerate(pdf_docs):
314
315
        draw_bbox_with_number(i, dropped_bbox_list, page, [158, 158, 158],
                              True)  # color !
316
        draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)
317
318
319
320
        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)
321
        draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)
322
323
        draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255],
                              True)
324
325
        draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102],
                              True)
326
327
328
329
330
        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
331
    pdf_docs.save(f'{out_path}/{filename}_model.pdf')
332
333


334
def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
335
336
337
338
    layout_bbox_list = []

    from loguru import logger
    for page in pdf_info:
339
340
        page_line_list = []
        for block in page['preproc_blocks']:
341
            if block['type'] == 'text' or block['type'] == 'title' or block['type'] == 'interline_equation':
342
                for line in block['lines']:
343
                    bbox = line['bbox']
344
345
                    index = line['index']
                    page_line_list.append({'index': index, 'bbox': bbox})
346
347
            if block['type'] == 'table' or block['type'] == 'image':
                bbox = block['bbox']
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
                index = block['index']
                page_line_list.append({'index': index, 'bbox': bbox})
        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)

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


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)
368
369
    pdf_docs = fitz.open('pdf', pdf_bytes)
    for i, page in enumerate(pdf_docs):
370
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
371
372

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