vlm_magic_model.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 ContentType, BlockType, SplitFlag
  5. from mineru.backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text
  6. from mineru.utils.format_utils import convert_otsl_to_html
  7. class MagicModel:
  8. def __init__(self, token: str, width, height):
  9. self.token = token
  10. # 使用正则表达式查找所有块
  11. pattern = (
  12. r"<\|box_start\|>(.*?)<\|box_end\|><\|ref_start\|>(.*?)<\|ref_end\|><\|md_start\|>(.*?)(?:<\|md_end\|>|<\|im_end\|>)"
  13. )
  14. block_infos = re.findall(pattern, token, re.DOTALL)
  15. blocks = []
  16. self.all_spans = []
  17. # 解析每个块
  18. for index, block_info in enumerate(block_infos):
  19. block_bbox = block_info[0].strip()
  20. x1, y1, x2, y2 = map(int, block_bbox.split())
  21. x_1, y_1, x_2, y_2 = (
  22. int(x1 * width / 1000),
  23. int(y1 * height / 1000),
  24. int(x2 * width / 1000),
  25. int(y2 * height / 1000),
  26. )
  27. if x_2 < x_1:
  28. x_1, x_2 = x_2, x_1
  29. if y_2 < y_1:
  30. y_1, y_2 = y_2, y_1
  31. block_bbox = (x_1, y_1, x_2, y_2)
  32. block_type = block_info[1].strip()
  33. block_content = block_info[2].strip()
  34. # print(f"坐标: {block_bbox}")
  35. # print(f"类型: {block_type}")
  36. # print(f"内容: {block_content}")
  37. # print("-" * 50)
  38. span_type = "unknown"
  39. if block_type in [
  40. "text",
  41. "title",
  42. "image_caption",
  43. "image_footnote",
  44. "table_caption",
  45. "table_footnote",
  46. "list",
  47. "index",
  48. ]:
  49. span_type = ContentType.TEXT
  50. elif block_type in ["image"]:
  51. block_type = BlockType.IMAGE_BODY
  52. span_type = ContentType.IMAGE
  53. elif block_type in ["table"]:
  54. block_type = BlockType.TABLE_BODY
  55. span_type = ContentType.TABLE
  56. elif block_type in ["equation"]:
  57. block_type = BlockType.INTERLINE_EQUATION
  58. span_type = ContentType.INTERLINE_EQUATION
  59. if span_type in ["image", "table"]:
  60. span = {
  61. "bbox": block_bbox,
  62. "type": span_type,
  63. }
  64. if span_type == ContentType.TABLE:
  65. if "<fcel>" in block_content or "<ecel>" in block_content:
  66. lines = block_content.split("\n\n")
  67. new_lines = []
  68. for line in lines:
  69. if "<fcel>" in line or "<ecel>" in line:
  70. line = convert_otsl_to_html(line)
  71. new_lines.append(line)
  72. span["html"] = "\n\n".join(new_lines)
  73. else:
  74. span["html"] = block_content
  75. elif span_type in [ContentType.INTERLINE_EQUATION]:
  76. span = {
  77. "bbox": block_bbox,
  78. "type": span_type,
  79. "content": isolated_formula_clean(block_content),
  80. }
  81. else:
  82. if block_content.count("\\(") == block_content.count("\\)") and block_content.count("\\(") > 0:
  83. # 生成包含文本和公式的span列表
  84. spans = []
  85. last_end = 0
  86. # 查找所有公式
  87. for match in re.finditer(r'\\\((.+?)\\\)', block_content):
  88. start, end = match.span()
  89. # 添加公式前的文本
  90. if start > last_end:
  91. text_before = block_content[last_end:start]
  92. if text_before.strip():
  93. spans.append({
  94. "bbox": block_bbox,
  95. "type": ContentType.TEXT,
  96. "content": text_before
  97. })
  98. # 添加公式(去除\(和\))
  99. formula = match.group(1)
  100. spans.append({
  101. "bbox": block_bbox,
  102. "type": ContentType.INLINE_EQUATION,
  103. "content": formula.strip()
  104. })
  105. last_end = end
  106. # 添加最后一个公式后的文本
  107. if last_end < len(block_content):
  108. text_after = block_content[last_end:]
  109. if text_after.strip():
  110. spans.append({
  111. "bbox": block_bbox,
  112. "type": ContentType.TEXT,
  113. "content": text_after
  114. })
  115. span = spans
  116. else:
  117. span = {
  118. "bbox": block_bbox,
  119. "type": span_type,
  120. "content": block_content,
  121. }
  122. if isinstance(span, dict) and "bbox" in span:
  123. self.all_spans.append(span)
  124. line = {
  125. "bbox": block_bbox,
  126. "spans": [span],
  127. }
  128. elif isinstance(span, list):
  129. self.all_spans.extend(span)
  130. line = {
  131. "bbox": block_bbox,
  132. "spans": span,
  133. }
  134. else:
  135. raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")
  136. blocks.append(
  137. {
  138. "bbox": block_bbox,
  139. "type": block_type,
  140. "lines": [line],
  141. "index": index,
  142. }
  143. )
  144. self.image_blocks = []
  145. self.table_blocks = []
  146. self.interline_equation_blocks = []
  147. self.text_blocks = []
  148. self.title_blocks = []
  149. for block in blocks:
  150. if block["type"] in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:
  151. self.image_blocks.append(block)
  152. elif block["type"] in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:
  153. self.table_blocks.append(block)
  154. elif block["type"] == BlockType.INTERLINE_EQUATION:
  155. self.interline_equation_blocks.append(block)
  156. elif block["type"] == BlockType.TEXT:
  157. self.text_blocks.append(block)
  158. elif block["type"] == BlockType.TITLE:
  159. self.title_blocks.append(block)
  160. else:
  161. continue
  162. def get_image_blocks(self):
  163. return fix_two_layer_blocks(self.image_blocks, BlockType.IMAGE)
  164. def get_table_blocks(self):
  165. return fix_two_layer_blocks(self.table_blocks, BlockType.TABLE)
  166. def get_title_blocks(self):
  167. return fix_title_blocks(self.title_blocks)
  168. def get_text_blocks(self):
  169. return fix_text_blocks(self.text_blocks)
  170. def get_interline_equation_blocks(self):
  171. return self.interline_equation_blocks
  172. def get_all_spans(self):
  173. return self.all_spans
  174. def isolated_formula_clean(txt):
  175. latex = txt[:]
  176. if latex.startswith("\\["): latex = latex[2:]
  177. if latex.endswith("\\]"): latex = latex[:-2]
  178. return latex.strip()
  179. def __reduct_overlap(bboxes):
  180. N = len(bboxes)
  181. keep = [True] * N
  182. for i in range(N):
  183. for j in range(N):
  184. if i == j:
  185. continue
  186. if is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):
  187. keep[i] = False
  188. return [bboxes[i] for i in range(N) if keep[i]]
  189. def __tie_up_category_by_distance_v3(
  190. blocks: list,
  191. subject_block_type: str,
  192. object_block_type: str,
  193. ):
  194. subjects = __reduct_overlap(
  195. list(
  196. map(
  197. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  198. filter(
  199. lambda x: x["type"] == subject_block_type,
  200. blocks,
  201. ),
  202. )
  203. )
  204. )
  205. objects = __reduct_overlap(
  206. list(
  207. map(
  208. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  209. filter(
  210. lambda x: x["type"] == object_block_type,
  211. blocks,
  212. ),
  213. )
  214. )
  215. )
  216. ret = []
  217. N, M = len(subjects), len(objects)
  218. subjects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  219. objects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  220. OBJ_IDX_OFFSET = 10000
  221. SUB_BIT_KIND, OBJ_BIT_KIND = 0, 1
  222. all_boxes_with_idx = [(i, SUB_BIT_KIND, sub["bbox"][0], sub["bbox"][1]) for i, sub in enumerate(subjects)] + [
  223. (i + OBJ_IDX_OFFSET, OBJ_BIT_KIND, obj["bbox"][0], obj["bbox"][1]) for i, obj in enumerate(objects)
  224. ]
  225. seen_idx = set()
  226. seen_sub_idx = set()
  227. while N > len(seen_sub_idx):
  228. candidates = []
  229. for idx, kind, x0, y0 in all_boxes_with_idx:
  230. if idx in seen_idx:
  231. continue
  232. candidates.append((idx, kind, x0, y0))
  233. if len(candidates) == 0:
  234. break
  235. left_x = min([v[2] for v in candidates])
  236. top_y = min([v[3] for v in candidates])
  237. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  238. fst_idx, fst_kind, left_x, top_y = candidates[0]
  239. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  240. nxt = None
  241. for i in range(1, len(candidates)):
  242. if candidates[i][1] ^ fst_kind == 1:
  243. nxt = candidates[i]
  244. break
  245. if nxt is None:
  246. break
  247. if fst_kind == SUB_BIT_KIND:
  248. sub_idx, obj_idx = fst_idx, nxt[0] - OBJ_IDX_OFFSET
  249. else:
  250. sub_idx, obj_idx = nxt[0], fst_idx - OBJ_IDX_OFFSET
  251. pair_dis = bbox_distance(subjects[sub_idx]["bbox"], objects[obj_idx]["bbox"])
  252. nearest_dis = float("inf")
  253. for i in range(N):
  254. if i in seen_idx or i == sub_idx:
  255. continue
  256. nearest_dis = min(nearest_dis, bbox_distance(subjects[i]["bbox"], objects[obj_idx]["bbox"]))
  257. if pair_dis >= 3 * nearest_dis:
  258. seen_idx.add(sub_idx)
  259. continue
  260. seen_idx.add(sub_idx)
  261. seen_idx.add(obj_idx + OBJ_IDX_OFFSET)
  262. seen_sub_idx.add(sub_idx)
  263. ret.append(
  264. {
  265. "sub_bbox": {
  266. "bbox": subjects[sub_idx]["bbox"],
  267. "lines": subjects[sub_idx]["lines"],
  268. "index": subjects[sub_idx]["index"],
  269. },
  270. "obj_bboxes": [
  271. {"bbox": objects[obj_idx]["bbox"], "lines": objects[obj_idx]["lines"], "index": objects[obj_idx]["index"]}
  272. ],
  273. "sub_idx": sub_idx,
  274. }
  275. )
  276. for i in range(len(objects)):
  277. j = i + OBJ_IDX_OFFSET
  278. if j in seen_idx:
  279. continue
  280. seen_idx.add(j)
  281. nearest_dis, nearest_sub_idx = float("inf"), -1
  282. for k in range(len(subjects)):
  283. dis = bbox_distance(objects[i]["bbox"], subjects[k]["bbox"])
  284. if dis < nearest_dis:
  285. nearest_dis = dis
  286. nearest_sub_idx = k
  287. for k in range(len(subjects)):
  288. if k != nearest_sub_idx:
  289. continue
  290. if k in seen_sub_idx:
  291. for kk in range(len(ret)):
  292. if ret[kk]["sub_idx"] == k:
  293. ret[kk]["obj_bboxes"].append(
  294. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  295. )
  296. break
  297. else:
  298. ret.append(
  299. {
  300. "sub_bbox": {
  301. "bbox": subjects[k]["bbox"],
  302. "lines": subjects[k]["lines"],
  303. "index": subjects[k]["index"],
  304. },
  305. "obj_bboxes": [
  306. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  307. ],
  308. "sub_idx": k,
  309. }
  310. )
  311. seen_sub_idx.add(k)
  312. seen_idx.add(k)
  313. for i in range(len(subjects)):
  314. if i in seen_sub_idx:
  315. continue
  316. ret.append(
  317. {
  318. "sub_bbox": {
  319. "bbox": subjects[i]["bbox"],
  320. "lines": subjects[i]["lines"],
  321. "index": subjects[i]["index"],
  322. },
  323. "obj_bboxes": [],
  324. "sub_idx": i,
  325. }
  326. )
  327. return ret
  328. def get_type_blocks(blocks, block_type: Literal["image", "table"]):
  329. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  330. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  331. ret = []
  332. for v in with_captions:
  333. record = {
  334. f"{block_type}_body": v["sub_bbox"],
  335. f"{block_type}_caption_list": v["obj_bboxes"],
  336. }
  337. filter_idx = v["sub_idx"]
  338. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  339. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  340. ret.append(record)
  341. return ret
  342. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
  343. need_fix_blocks = get_type_blocks(blocks, fix_type)
  344. fixed_blocks = []
  345. for block in need_fix_blocks:
  346. body = block[f"{fix_type}_body"]
  347. caption_list = block[f"{fix_type}_caption_list"]
  348. footnote_list = block[f"{fix_type}_footnote_list"]
  349. body["type"] = f"{fix_type}_body"
  350. for caption in caption_list:
  351. caption["type"] = f"{fix_type}_caption"
  352. for footnote in footnote_list:
  353. footnote["type"] = f"{fix_type}_footnote"
  354. two_layer_block = {
  355. "type": fix_type,
  356. "bbox": body["bbox"],
  357. "blocks": [
  358. body,
  359. ],
  360. "index": body["index"],
  361. }
  362. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  363. fixed_blocks.append(two_layer_block)
  364. return fixed_blocks
  365. def fix_title_blocks(blocks):
  366. for block in blocks:
  367. if block["type"] == BlockType.TITLE:
  368. title_content = merge_para_with_text(block)
  369. title_level = count_leading_hashes(title_content)
  370. block['level'] = title_level
  371. for line in block['lines']:
  372. for span in line['spans']:
  373. span['content'] = strip_leading_hashes(span['content'])
  374. break
  375. break
  376. return blocks
  377. def count_leading_hashes(text):
  378. match = re.match(r'^(#+)', text)
  379. return len(match.group(1)) if match else 0
  380. def strip_leading_hashes(text):
  381. # 去除开头的#和紧随其后的空格
  382. return re.sub(r'^#+\s*', '', text)
  383. def fix_text_blocks(blocks):
  384. i = 0
  385. while i < len(blocks):
  386. block = blocks[i]
  387. last_line = block["lines"][-1]if block["lines"] else None
  388. if last_line:
  389. last_span = last_line["spans"][-1] if last_line["spans"] else None
  390. if last_span and last_span['content'].endswith('<|txt_contd|>'):
  391. last_span['content'] = last_span['content'][:-len('<|txt_contd|>')]
  392. # 查找下一个未被清空的块
  393. next_idx = i + 1
  394. while next_idx < len(blocks) and blocks[next_idx].get(SplitFlag.LINES_DELETED, False):
  395. next_idx += 1
  396. # 如果找到下一个有效块,则合并
  397. if next_idx < len(blocks):
  398. next_block = blocks[next_idx]
  399. # 将下一个块的lines扩展到当前块的lines中
  400. block["lines"].extend(next_block["lines"])
  401. # 清空下一个块的lines
  402. next_block["lines"] = []
  403. # 在下一个块中添加标志
  404. next_block[SplitFlag.LINES_DELETED] = True
  405. # 不增加i,继续检查当前块(现在已包含下一个块的内容)
  406. continue
  407. i += 1
  408. return blocks