ocr_span_list_modify.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from loguru import logger
  2. from magic_pdf.libs.boxbase import calculate_overlap_area_in_bbox1_area_ratio, get_minbox_if_overlap_by_ratio, \
  3. __is_overlaps_y_exceeds_threshold, calculate_iou
  4. from magic_pdf.libs.drop_tag import DropTag
  5. from magic_pdf.libs.ocr_content_type import ContentType, BlockType
  6. def remove_overlaps_low_confidence_spans(spans):
  7. dropped_spans = []
  8. # 删除重叠spans中置信度低的的那些
  9. for span1 in spans:
  10. for span2 in spans:
  11. if span1 != span2:
  12. if calculate_iou(span1['bbox'], span2['bbox']) > 0.9:
  13. if span1['score'] < span2['score']:
  14. span_need_remove = span1
  15. else:
  16. span_need_remove = span2
  17. if span_need_remove is not None and span_need_remove not in dropped_spans:
  18. dropped_spans.append(span_need_remove)
  19. if len(dropped_spans) > 0:
  20. for span_need_remove in dropped_spans:
  21. spans.remove(span_need_remove)
  22. span_need_remove['tag'] = DropTag.SPAN_OVERLAP
  23. return spans, dropped_spans
  24. def remove_overlaps_min_spans(spans):
  25. dropped_spans = []
  26. # 删除重叠spans中较小的那些
  27. for span1 in spans:
  28. for span2 in spans:
  29. if span1 != span2:
  30. overlap_box = get_minbox_if_overlap_by_ratio(span1['bbox'], span2['bbox'], 0.65)
  31. if overlap_box is not None:
  32. span_need_remove = next((span for span in spans if span['bbox'] == overlap_box), None)
  33. if span_need_remove is not None and span_need_remove not in dropped_spans:
  34. dropped_spans.append(span_need_remove)
  35. if len(dropped_spans) > 0:
  36. for span_need_remove in dropped_spans:
  37. spans.remove(span_need_remove)
  38. span_need_remove['tag'] = DropTag.SPAN_OVERLAP
  39. return spans, dropped_spans
  40. def remove_spans_by_bboxes(spans, need_remove_spans_bboxes):
  41. # 遍历spans, 判断是否在removed_span_block_bboxes中
  42. # 如果是, 则删除该span 否则, 保留该span
  43. need_remove_spans = []
  44. for span in spans:
  45. for removed_bbox in need_remove_spans_bboxes:
  46. if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], removed_bbox) > 0.5:
  47. if span not in need_remove_spans:
  48. need_remove_spans.append(span)
  49. break
  50. if len(need_remove_spans) > 0:
  51. for span in need_remove_spans:
  52. spans.remove(span)
  53. return spans
  54. def remove_spans_by_bboxes_dict(spans, need_remove_spans_bboxes_dict):
  55. dropped_spans = []
  56. for drop_tag, removed_bboxes in need_remove_spans_bboxes_dict.items():
  57. # logger.info(f"remove spans by bbox dict, drop_tag: {drop_tag}, removed_bboxes: {removed_bboxes}")
  58. need_remove_spans = []
  59. for span in spans:
  60. # 通过判断span的bbox是否在removed_bboxes中, 判断是否需要删除该span
  61. for removed_bbox in removed_bboxes:
  62. if calculate_overlap_area_in_bbox1_area_ratio(span['bbox'], removed_bbox) > 0.5:
  63. need_remove_spans.append(span)
  64. break
  65. # 当drop_tag为DropTag.FOOTNOTE时, 判断span是否在removed_bboxes中任意一个的下方,如果是,则删除该span
  66. elif drop_tag == DropTag.FOOTNOTE and (span['bbox'][1] + span['bbox'][3]) / 2 > removed_bbox[3] and \
  67. removed_bbox[0] < (span['bbox'][0] + span['bbox'][2]) / 2 < removed_bbox[2]:
  68. need_remove_spans.append(span)
  69. break
  70. for span in need_remove_spans:
  71. spans.remove(span)
  72. span['tag'] = drop_tag
  73. dropped_spans.append(span)
  74. return spans, dropped_spans
  75. def adjust_bbox_for_standalone_block(spans):
  76. # 对tpye=["interline_equation", "image", "table"]进行额外处理,如果左边有字的话,将该span的bbox中y0调整至不高于文字的y0
  77. for sb_span in spans:
  78. if sb_span['type'] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table]:
  79. for text_span in spans:
  80. if text_span['type'] in [ContentType.Text, ContentType.InlineEquation]:
  81. # 判断span2的纵向高度是否被span所覆盖
  82. if sb_span['bbox'][1] < text_span['bbox'][1] and sb_span['bbox'][3] > text_span['bbox'][3]:
  83. # 判断span2是否在span左边
  84. if text_span['bbox'][0] < sb_span['bbox'][0]:
  85. # 调整span的y0和span2的y0一致
  86. sb_span['bbox'][1] = text_span['bbox'][1]
  87. return spans
  88. def modify_y_axis(spans: list, displayed_list: list, text_inline_lines: list):
  89. # displayed_list = []
  90. # 如果spans为空,则不处理
  91. if len(spans) == 0:
  92. pass
  93. else:
  94. spans.sort(key=lambda span: span['bbox'][1])
  95. lines = []
  96. current_line = [spans[0]]
  97. if spans[0]["type"] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table]:
  98. displayed_list.append(spans[0])
  99. line_first_y0 = spans[0]["bbox"][1]
  100. line_first_y = spans[0]["bbox"][3]
  101. # 用于给行间公式搜索
  102. # text_inline_lines = []
  103. for span in spans[1:]:
  104. # if span.get("content","") == "78.":
  105. # print("debug")
  106. # 如果当前的span类型为"interline_equation" 或者 当前行中已经有"interline_equation"
  107. # image和table类型,同上
  108. if span['type'] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table] or any(
  109. s['type'] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table] for s in
  110. current_line):
  111. # 传入
  112. if span["type"] in [ContentType.InterlineEquation, ContentType.Image, ContentType.Table]:
  113. displayed_list.append(span)
  114. # 则开始新行
  115. lines.append(current_line)
  116. if len(current_line) > 1 or current_line[0]["type"] in [ContentType.Text, ContentType.InlineEquation]:
  117. text_inline_lines.append((current_line, (line_first_y0, line_first_y)))
  118. current_line = [span]
  119. line_first_y0 = span["bbox"][1]
  120. line_first_y = span["bbox"][3]
  121. continue
  122. # 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行
  123. if __is_overlaps_y_exceeds_threshold(span['bbox'], current_line[-1]['bbox']):
  124. if span["type"] == "text":
  125. line_first_y0 = span["bbox"][1]
  126. line_first_y = span["bbox"][3]
  127. current_line.append(span)
  128. else:
  129. # 否则,开始新行
  130. lines.append(current_line)
  131. text_inline_lines.append((current_line, (line_first_y0, line_first_y)))
  132. current_line = [span]
  133. line_first_y0 = span["bbox"][1]
  134. line_first_y = span["bbox"][3]
  135. # 添加最后一行
  136. if current_line:
  137. lines.append(current_line)
  138. if len(current_line) > 1 or current_line[0]["type"] in [ContentType.Text, ContentType.InlineEquation]:
  139. text_inline_lines.append((current_line, (line_first_y0, line_first_y)))
  140. for line in text_inline_lines:
  141. # 按照x0坐标排序
  142. current_line = line[0]
  143. current_line.sort(key=lambda span: span['bbox'][0])
  144. # 调整每一个文字行内bbox统一
  145. for line in text_inline_lines:
  146. current_line, (line_first_y0, line_first_y) = line
  147. for span in current_line:
  148. span["bbox"][1] = line_first_y0
  149. span["bbox"][3] = line_first_y
  150. # return spans, displayed_list, text_inline_lines
  151. def modify_inline_equation(spans: list, displayed_list: list, text_inline_lines: list):
  152. # 错误行间公式转行内公式
  153. j = 0
  154. for i in range(len(displayed_list)):
  155. # if i == 8:
  156. # print("debug")
  157. span = displayed_list[i]
  158. span_y0, span_y = span["bbox"][1], span["bbox"][3]
  159. while j < len(text_inline_lines):
  160. text_line = text_inline_lines[j]
  161. y0, y1 = text_line[1]
  162. if (
  163. span_y0 < y0 < span_y or span_y0 < y1 < span_y or span_y0 < y0 and span_y > y1
  164. ) and __is_overlaps_y_exceeds_threshold(
  165. span['bbox'], (0, y0, 0, y1)
  166. ):
  167. # 调整公式类型
  168. if span["type"] == ContentType.InterlineEquation:
  169. # 最后一行是行间公式
  170. if j + 1 >= len(text_inline_lines):
  171. span["type"] = ContentType.InlineEquation
  172. span["bbox"][1] = y0
  173. span["bbox"][3] = y1
  174. else:
  175. # 行间公式旁边有多行文字或者行间公式比文字高3倍则不转换
  176. y0_next, y1_next = text_inline_lines[j + 1][1]
  177. if not __is_overlaps_y_exceeds_threshold(span['bbox'], (0, y0_next, 0, y1_next)) and 3 * (
  178. y1 - y0) > span_y - span_y0:
  179. span["type"] = ContentType.InlineEquation
  180. span["bbox"][1] = y0
  181. span["bbox"][3] = y1
  182. break
  183. elif span_y < y0 or span_y0 < y0 < span_y and not __is_overlaps_y_exceeds_threshold(span['bbox'],
  184. (0, y0, 0, y1)):
  185. break
  186. else:
  187. j += 1
  188. return spans
  189. def get_qa_need_list(blocks):
  190. # 创建 images, tables, interline_equations, inline_equations 的副本
  191. images = []
  192. tables = []
  193. interline_equations = []
  194. inline_equations = []
  195. for block in blocks:
  196. for line in block["lines"]:
  197. for span in line["spans"]:
  198. if span["type"] == ContentType.Image:
  199. images.append(span)
  200. elif span["type"] == ContentType.Table:
  201. tables.append(span)
  202. elif span["type"] == ContentType.InlineEquation:
  203. inline_equations.append(span)
  204. elif span["type"] == ContentType.InterlineEquation:
  205. interline_equations.append(span)
  206. else:
  207. continue
  208. return images, tables, interline_equations, inline_equations
  209. def get_qa_need_list_v2(blocks):
  210. # 创建 images, tables, interline_equations, inline_equations 的副本
  211. images = []
  212. tables = []
  213. interline_equations = []
  214. for block in blocks:
  215. if block["type"] == BlockType.Image:
  216. images.append(block)
  217. elif block["type"] == BlockType.Table:
  218. tables.append(block)
  219. elif block["type"] == BlockType.InterlineEquation:
  220. interline_equations.append(block)
  221. return images, tables, interline_equations