ocr_detect_all_bboxes.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from magic_pdf.libs.boxbase import get_minbox_if_overlap_by_ratio
  2. from magic_pdf.libs.drop_tag import DropTag
  3. from magic_pdf.libs.ocr_content_type import BlockType
  4. def ocr_prepare_bboxes_for_layout_split(img_blocks, table_blocks, discarded_blocks, text_blocks,
  5. title_blocks, interline_equation_blocks, page_w, page_h):
  6. all_bboxes = []
  7. for image in img_blocks:
  8. x0, y0, x1, y1 = image['bbox']
  9. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.Image, None, None, None, None])
  10. for table in table_blocks:
  11. x0, y0, x1, y1 = table['bbox']
  12. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.Table, None, None, None, None])
  13. for text in text_blocks:
  14. x0, y0, x1, y1 = text['bbox']
  15. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.Text, None, None, None, None])
  16. for title in title_blocks:
  17. x0, y0, x1, y1 = title['bbox']
  18. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.Title, None, None, None, None])
  19. for interline_equation in interline_equation_blocks:
  20. x0, y0, x1, y1 = interline_equation['bbox']
  21. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.InterlineEquation, None, None, None, None])
  22. '''discarded_blocks中只保留宽度超过1/3页面宽度的,高度超过10的,处于页面下半50%区域的(限定footnote)'''
  23. for discarded in discarded_blocks:
  24. x0, y0, x1, y1 = discarded['bbox']
  25. if (x1 - x0) > (page_w / 3) and (y1 - y0) > 10 and y0 > (page_h / 2):
  26. all_bboxes.append([x0, y0, x1, y1, None, None, None, BlockType.Footnote, None, None, None, None])
  27. '''block嵌套问题解决'''
  28. # @todo 1. text block大框套小框,删除小框 2. 图片或文本框与舍弃框重叠,优先信任舍弃框 3. 文本框与标题框重叠,优先信任文本框
  29. all_bboxes, dropped_blocks = remove_overlaps_min_blocks(all_bboxes)
  30. return all_bboxes
  31. def remove_overlaps_min_blocks(all_bboxes):
  32. dropped_blocks = []
  33. # 删除重叠blocks中较小的那些
  34. for block1 in all_bboxes.copy():
  35. for block2 in all_bboxes.copy():
  36. if block1 != block2:
  37. block1_box = block1[0], block1[1], block1[2], block1[3]
  38. block2_box = block2[0], block2[1], block2[2], block2[3]
  39. overlap_box = get_minbox_if_overlap_by_ratio(block1_box, block2_box, 0.8)
  40. if overlap_box is not None:
  41. bbox_to_remove = next(
  42. (block for block in all_bboxes if [block[0], block[1], block[2], block[3]] == overlap_box),
  43. None)
  44. if bbox_to_remove is not None:
  45. all_bboxes.remove(bbox_to_remove)
  46. bbox_to_remove['tag'] = DropTag.BLOCK_OVERLAP
  47. dropped_blocks.append(bbox_to_remove)
  48. return all_bboxes, dropped_blocks