vlm_magic_model.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import re
  2. from typing import Literal
  3. from mineru.utils.boxbase import bbox_distance, is_in
  4. from mineru.utils.enum_class import BlockType
  5. from mineru.backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text
  6. def __reduct_overlap(bboxes):
  7. N = len(bboxes)
  8. keep = [True] * N
  9. for i in range(N):
  10. for j in range(N):
  11. if i == j:
  12. continue
  13. if is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):
  14. keep[i] = False
  15. return [bboxes[i] for i in range(N) if keep[i]]
  16. def __tie_up_category_by_distance_v3(
  17. blocks: list,
  18. subject_block_type: str,
  19. object_block_type: str,
  20. ):
  21. subjects = __reduct_overlap(
  22. list(
  23. map(
  24. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  25. filter(
  26. lambda x: x["type"] == subject_block_type,
  27. blocks,
  28. ),
  29. )
  30. )
  31. )
  32. objects = __reduct_overlap(
  33. list(
  34. map(
  35. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  36. filter(
  37. lambda x: x["type"] == object_block_type,
  38. blocks,
  39. ),
  40. )
  41. )
  42. )
  43. ret = []
  44. N, M = len(subjects), len(objects)
  45. subjects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  46. objects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  47. OBJ_IDX_OFFSET = 10000
  48. SUB_BIT_KIND, OBJ_BIT_KIND = 0, 1
  49. all_boxes_with_idx = [(i, SUB_BIT_KIND, sub["bbox"][0], sub["bbox"][1]) for i, sub in enumerate(subjects)] + [
  50. (i + OBJ_IDX_OFFSET, OBJ_BIT_KIND, obj["bbox"][0], obj["bbox"][1]) for i, obj in enumerate(objects)
  51. ]
  52. seen_idx = set()
  53. seen_sub_idx = set()
  54. while N > len(seen_sub_idx):
  55. candidates = []
  56. for idx, kind, x0, y0 in all_boxes_with_idx:
  57. if idx in seen_idx:
  58. continue
  59. candidates.append((idx, kind, x0, y0))
  60. if len(candidates) == 0:
  61. break
  62. left_x = min([v[2] for v in candidates])
  63. top_y = min([v[3] for v in candidates])
  64. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  65. fst_idx, fst_kind, left_x, top_y = candidates[0]
  66. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  67. nxt = None
  68. for i in range(1, len(candidates)):
  69. if candidates[i][1] ^ fst_kind == 1:
  70. nxt = candidates[i]
  71. break
  72. if nxt is None:
  73. break
  74. if fst_kind == SUB_BIT_KIND:
  75. sub_idx, obj_idx = fst_idx, nxt[0] - OBJ_IDX_OFFSET
  76. else:
  77. sub_idx, obj_idx = nxt[0], fst_idx - OBJ_IDX_OFFSET
  78. pair_dis = bbox_distance(subjects[sub_idx]["bbox"], objects[obj_idx]["bbox"])
  79. nearest_dis = float("inf")
  80. for i in range(N):
  81. if i in seen_idx or i == sub_idx:
  82. continue
  83. nearest_dis = min(nearest_dis, bbox_distance(subjects[i]["bbox"], objects[obj_idx]["bbox"]))
  84. if pair_dis >= 3 * nearest_dis:
  85. seen_idx.add(sub_idx)
  86. continue
  87. seen_idx.add(sub_idx)
  88. seen_idx.add(obj_idx + OBJ_IDX_OFFSET)
  89. seen_sub_idx.add(sub_idx)
  90. ret.append(
  91. {
  92. "sub_bbox": {
  93. "bbox": subjects[sub_idx]["bbox"],
  94. "lines": subjects[sub_idx]["lines"],
  95. "index": subjects[sub_idx]["index"],
  96. },
  97. "obj_bboxes": [
  98. {"bbox": objects[obj_idx]["bbox"], "lines": objects[obj_idx]["lines"], "index": objects[obj_idx]["index"]}
  99. ],
  100. "sub_idx": sub_idx,
  101. }
  102. )
  103. for i in range(len(objects)):
  104. j = i + OBJ_IDX_OFFSET
  105. if j in seen_idx:
  106. continue
  107. seen_idx.add(j)
  108. nearest_dis, nearest_sub_idx = float("inf"), -1
  109. for k in range(len(subjects)):
  110. dis = bbox_distance(objects[i]["bbox"], subjects[k]["bbox"])
  111. if dis < nearest_dis:
  112. nearest_dis = dis
  113. nearest_sub_idx = k
  114. for k in range(len(subjects)):
  115. if k != nearest_sub_idx:
  116. continue
  117. if k in seen_sub_idx:
  118. for kk in range(len(ret)):
  119. if ret[kk]["sub_idx"] == k:
  120. ret[kk]["obj_bboxes"].append(
  121. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  122. )
  123. break
  124. else:
  125. ret.append(
  126. {
  127. "sub_bbox": {
  128. "bbox": subjects[k]["bbox"],
  129. "lines": subjects[k]["lines"],
  130. "index": subjects[k]["index"],
  131. },
  132. "obj_bboxes": [
  133. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  134. ],
  135. "sub_idx": k,
  136. }
  137. )
  138. seen_sub_idx.add(k)
  139. seen_idx.add(k)
  140. for i in range(len(subjects)):
  141. if i in seen_sub_idx:
  142. continue
  143. ret.append(
  144. {
  145. "sub_bbox": {
  146. "bbox": subjects[i]["bbox"],
  147. "lines": subjects[i]["lines"],
  148. "index": subjects[i]["index"],
  149. },
  150. "obj_bboxes": [],
  151. "sub_idx": i,
  152. }
  153. )
  154. return ret
  155. def get_type_blocks(blocks, block_type: Literal["image", "table"]):
  156. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  157. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  158. ret = []
  159. for v in with_captions:
  160. record = {
  161. f"{block_type}_body": v["sub_bbox"],
  162. f"{block_type}_caption_list": v["obj_bboxes"],
  163. }
  164. filter_idx = v["sub_idx"]
  165. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  166. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  167. ret.append(record)
  168. return ret
  169. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
  170. need_fix_blocks = get_type_blocks(blocks, fix_type)
  171. fixed_blocks = []
  172. for block in need_fix_blocks:
  173. body = block[f"{fix_type}_body"]
  174. caption_list = block[f"{fix_type}_caption_list"]
  175. footnote_list = block[f"{fix_type}_footnote_list"]
  176. body["type"] = f"{fix_type}_body"
  177. for caption in caption_list:
  178. caption["type"] = f"{fix_type}_caption"
  179. for footnote in footnote_list:
  180. footnote["type"] = f"{fix_type}_footnote"
  181. two_layer_block = {
  182. "type": fix_type,
  183. "bbox": body["bbox"],
  184. "blocks": [
  185. body,
  186. ],
  187. "index": body["index"],
  188. }
  189. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  190. fixed_blocks.append(two_layer_block)
  191. return fixed_blocks
  192. def fix_title_blocks(blocks):
  193. for block in blocks:
  194. if block["type"] == BlockType.TITLE:
  195. title_content = merge_para_with_text(block)
  196. title_level = count_leading_hashes(title_content)
  197. block['level'] = title_level
  198. for line in block['lines']:
  199. for span in line['spans']:
  200. span['content'] = strip_leading_hashes(span['content'])
  201. break
  202. break
  203. return blocks
  204. def count_leading_hashes(text):
  205. match = re.match(r'^(#+)', text)
  206. return len(match.group(1)) if match else 0
  207. def strip_leading_hashes(text):
  208. # 去除开头的#和紧随其后的空格
  209. return re.sub(r'^#+\s*', '', text)