draw_bbox.py 15.7 KB
Newer Older
1
from magic_pdf.libs.commons import fitz  # PyMuPDF
2
3
from magic_pdf.libs.Constants import CROSS_PAGE
from magic_pdf.libs.ocr_content_type import BlockType, CategoryId, ContentType
4
from magic_pdf.model.magic_model import MagicModel
赵小蒙's avatar
赵小蒙 committed
5

赵小蒙's avatar
赵小蒙 committed
6

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

35

36
def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config, draw_bbox=True):
赵小蒙's avatar
赵小蒙 committed
37
38
39
40
41
42
43
44
    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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        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
64
        page.insert_text(
65
            (x1+2, y0 + 10), str(j + 1), fontsize=10, color=new_rgb
赵小蒙's avatar
赵小蒙 committed
66
        )  # Insert the index in the top left corner of the rectangle
赵小蒙's avatar
赵小蒙 committed
67
68


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

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

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

许瑞's avatar
许瑞 committed
127
128
129
130
131
132
133
        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)
134
        imgs_footnote_list.append(imgs_footnote)
许瑞's avatar
许瑞 committed
135
136
137
        titles_list.append(titles)
        texts_list.append(texts)
        interequations_list.append(interequations)
138
139
        lists_list.append(lists)
        indexs_list.append(indexs)
许瑞's avatar
许瑞 committed
140

141
142
143
144
145
146
147
148
149
    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)

150
    pdf_docs = fitz.open('pdf', pdf_bytes)
151

152
    for i, page in enumerate(pdf_docs):
153

154
155
156
157
158
159
160
161
162
163
        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
164
165
        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)
166
167
        draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255],
                                 True)
168
        draw_bbox_without_number(i, imgs_footnote_list, page, [255, 178, 102],
169
                              True),
许瑞's avatar
许瑞 committed
170
171
        draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)
        draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)
172
173
        draw_bbox_without_number(i, interequations_list, page, [0, 255, 0],
                                 True)
174
175
        draw_bbox_without_number(i, lists_list, page, [40, 169, 92], True)
        draw_bbox_without_number(i, indexs_list, page, [40, 169, 92], True)
176

177
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False, draw_bbox=False)
许瑞's avatar
许瑞 committed
178

179
    # Save the PDF
180
    pdf_docs.save(f'{out_path}/{filename}_layout.pdf')
181

许瑞's avatar
许瑞 committed
182

183
def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
184
185
    text_list = []
    inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
186
    interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
187
188
    image_list = []
    table_list = []
赵小蒙's avatar
赵小蒙 committed
189
    dropped_list = []
190
191
    next_page_text_list = []
    next_page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
192
193

    def get_span_info(span):
194
        if span['type'] == ContentType.Text:
赵小蒙's avatar
赵小蒙 committed
195
            if span.get(CROSS_PAGE, False):
196
                next_page_text_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
197
            else:
198
199
                page_text_list.append(span['bbox'])
        elif span['type'] == ContentType.InlineEquation:
赵小蒙's avatar
赵小蒙 committed
200
            if span.get(CROSS_PAGE, False):
201
                next_page_inline_equation_list.append(span['bbox'])
赵小蒙's avatar
赵小蒙 committed
202
            else:
203
204
205
206
207
208
209
                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
210

赵小蒙's avatar
赵小蒙 committed
211
    for page in pdf_info:
212
213
        page_text_list = []
        page_inline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
214
        page_interline_equation_list = []
赵小蒙's avatar
赵小蒙 committed
215
216
        page_image_list = []
        page_table_list = []
赵小蒙's avatar
赵小蒙 committed
217
        page_dropped_list = []
218
219
220
221

        # 将跨页的span放到移动到下一页的列表中
        if len(next_page_text_list) > 0:
            page_text_list.extend(next_page_text_list)
赵小蒙's avatar
赵小蒙 committed
222
            next_page_text_list.clear()
223
224
        if len(next_page_inline_equation_list) > 0:
            page_inline_equation_list.extend(next_page_inline_equation_list)
赵小蒙's avatar
赵小蒙 committed
225
            next_page_inline_equation_list.clear()
226

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

    # Save the PDF
267
    pdf_docs.save(f'{out_path}/{filename}_spans.pdf')
268
269


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

        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)
321
        imgs_footnote_list.append(imgs_footnote)
322
323

    for i, page in enumerate(pdf_docs):
324
325
        draw_bbox_with_number(i, dropped_bbox_list, page, [158, 158, 158],
                              True)  # color !
326
        draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)
327
328
329
330
        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)
331
        draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)
332
333
        draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255],
                              True)
334
335
        draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102],
                              True)
336
337
338
339
340
        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
341
    pdf_docs.save(f'{out_path}/{filename}_model.pdf')
342
343


344
def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
345
346
347
    layout_bbox_list = []

    for page in pdf_info:
348
349
        page_line_list = []
        for block in page['preproc_blocks']:
350
            if block['type'] in ['text', 'title', 'interline_equation']:
351
                for line in block['lines']:
352
                    bbox = line['bbox']
353
354
                    index = line['index']
                    page_line_list.append({'index': index, 'bbox': bbox})
355
            if block['type'] in ['table', 'image']:
356
                bbox = block['bbox']
357
358
                index = block['index']
                page_line_list.append({'index': index, 'bbox': bbox})
359
360
361
362
            # for line in block['lines']:
            #     bbox = line['bbox']
            #     index = line['index']
            #     page_line_list.append({'index': index, 'bbox': bbox})
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
        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)
381
382
    pdf_docs = fitz.open('pdf', pdf_bytes)
    for i, page in enumerate(pdf_docs):
383
        draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
384
385

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