vlm_magic_model.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. latex = latex_fix(latex.strip())
  179. return latex
  180. def latex_fix(latex):
  181. # valid pairs:
  182. # \left\{ ... \right\}
  183. # \left( ... \right)
  184. # \left| ... \right|
  185. # \left\| ... \right\|
  186. # \left[ ... \right]
  187. LEFT_COUNT_PATTERN = re.compile(r'\\left(?![a-zA-Z])')
  188. RIGHT_COUNT_PATTERN = re.compile(r'\\right(?![a-zA-Z])')
  189. left_count = len(LEFT_COUNT_PATTERN.findall(latex)) # 不匹配\lefteqn等
  190. right_count = len(RIGHT_COUNT_PATTERN.findall(latex)) # 不匹配\rightarrow
  191. if left_count != right_count:
  192. for _ in range(2):
  193. # replace valid pairs
  194. latex = re.sub(r'\\left\\\{', "{", latex) # \left\{
  195. latex = re.sub(r"\\left\|", "|", latex) # \left|
  196. latex = re.sub(r"\\left\\\|", "|", latex) # \left\|
  197. latex = re.sub(r"\\left\(", "(", latex) # \left(
  198. latex = re.sub(r"\\left\[", "[", latex) # \left[
  199. latex = re.sub(r"\\right\\\}", "}", latex) # \right\}
  200. latex = re.sub(r"\\right\|", "|", latex) # \right|
  201. latex = re.sub(r"\\right\\\|", "|", latex) # \right\|
  202. latex = re.sub(r"\\right\)", ")", latex) # \right)
  203. latex = re.sub(r"\\right\]", "]", latex) # \right]
  204. latex = re.sub(r"\\right\.", "", latex) # \right.
  205. # replace invalid pairs first
  206. latex = re.sub(r'\\left\{', "{", latex)
  207. latex = re.sub(r'\\right\}', "}", latex) # \left{ ... \right}
  208. latex = re.sub(r'\\left\\\(', "(", latex)
  209. latex = re.sub(r'\\right\\\)', ")", latex) # \left\( ... \right\)
  210. latex = re.sub(r'\\left\\\[', "[", latex)
  211. latex = re.sub(r'\\right\\\]', "]", latex) # \left\[ ... \right\]
  212. return latex
  213. def __reduct_overlap(bboxes):
  214. N = len(bboxes)
  215. keep = [True] * N
  216. for i in range(N):
  217. for j in range(N):
  218. if i == j:
  219. continue
  220. if is_in(bboxes[i]["bbox"], bboxes[j]["bbox"]):
  221. keep[i] = False
  222. return [bboxes[i] for i in range(N) if keep[i]]
  223. def __tie_up_category_by_distance_v3(
  224. blocks: list,
  225. subject_block_type: str,
  226. object_block_type: str,
  227. ):
  228. subjects = __reduct_overlap(
  229. list(
  230. map(
  231. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  232. filter(
  233. lambda x: x["type"] == subject_block_type,
  234. blocks,
  235. ),
  236. )
  237. )
  238. )
  239. objects = __reduct_overlap(
  240. list(
  241. map(
  242. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  243. filter(
  244. lambda x: x["type"] == object_block_type,
  245. blocks,
  246. ),
  247. )
  248. )
  249. )
  250. ret = []
  251. N, M = len(subjects), len(objects)
  252. subjects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  253. objects.sort(key=lambda x: x["bbox"][0] ** 2 + x["bbox"][1] ** 2)
  254. OBJ_IDX_OFFSET = 10000
  255. SUB_BIT_KIND, OBJ_BIT_KIND = 0, 1
  256. all_boxes_with_idx = [(i, SUB_BIT_KIND, sub["bbox"][0], sub["bbox"][1]) for i, sub in enumerate(subjects)] + [
  257. (i + OBJ_IDX_OFFSET, OBJ_BIT_KIND, obj["bbox"][0], obj["bbox"][1]) for i, obj in enumerate(objects)
  258. ]
  259. seen_idx = set()
  260. seen_sub_idx = set()
  261. while N > len(seen_sub_idx):
  262. candidates = []
  263. for idx, kind, x0, y0 in all_boxes_with_idx:
  264. if idx in seen_idx:
  265. continue
  266. candidates.append((idx, kind, x0, y0))
  267. if len(candidates) == 0:
  268. break
  269. left_x = min([v[2] for v in candidates])
  270. top_y = min([v[3] for v in candidates])
  271. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  272. fst_idx, fst_kind, left_x, top_y = candidates[0]
  273. candidates.sort(key=lambda x: (x[2] - left_x) ** 2 + (x[3] - top_y) ** 2)
  274. nxt = None
  275. for i in range(1, len(candidates)):
  276. if candidates[i][1] ^ fst_kind == 1:
  277. nxt = candidates[i]
  278. break
  279. if nxt is None:
  280. break
  281. if fst_kind == SUB_BIT_KIND:
  282. sub_idx, obj_idx = fst_idx, nxt[0] - OBJ_IDX_OFFSET
  283. else:
  284. sub_idx, obj_idx = nxt[0], fst_idx - OBJ_IDX_OFFSET
  285. pair_dis = bbox_distance(subjects[sub_idx]["bbox"], objects[obj_idx]["bbox"])
  286. nearest_dis = float("inf")
  287. for i in range(N):
  288. if i in seen_idx or i == sub_idx:
  289. continue
  290. nearest_dis = min(nearest_dis, bbox_distance(subjects[i]["bbox"], objects[obj_idx]["bbox"]))
  291. if pair_dis >= 3 * nearest_dis:
  292. seen_idx.add(sub_idx)
  293. continue
  294. seen_idx.add(sub_idx)
  295. seen_idx.add(obj_idx + OBJ_IDX_OFFSET)
  296. seen_sub_idx.add(sub_idx)
  297. ret.append(
  298. {
  299. "sub_bbox": {
  300. "bbox": subjects[sub_idx]["bbox"],
  301. "lines": subjects[sub_idx]["lines"],
  302. "index": subjects[sub_idx]["index"],
  303. },
  304. "obj_bboxes": [
  305. {"bbox": objects[obj_idx]["bbox"], "lines": objects[obj_idx]["lines"], "index": objects[obj_idx]["index"]}
  306. ],
  307. "sub_idx": sub_idx,
  308. }
  309. )
  310. for i in range(len(objects)):
  311. j = i + OBJ_IDX_OFFSET
  312. if j in seen_idx:
  313. continue
  314. seen_idx.add(j)
  315. nearest_dis, nearest_sub_idx = float("inf"), -1
  316. for k in range(len(subjects)):
  317. dis = bbox_distance(objects[i]["bbox"], subjects[k]["bbox"])
  318. if dis < nearest_dis:
  319. nearest_dis = dis
  320. nearest_sub_idx = k
  321. for k in range(len(subjects)):
  322. if k != nearest_sub_idx:
  323. continue
  324. if k in seen_sub_idx:
  325. for kk in range(len(ret)):
  326. if ret[kk]["sub_idx"] == k:
  327. ret[kk]["obj_bboxes"].append(
  328. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  329. )
  330. break
  331. else:
  332. ret.append(
  333. {
  334. "sub_bbox": {
  335. "bbox": subjects[k]["bbox"],
  336. "lines": subjects[k]["lines"],
  337. "index": subjects[k]["index"],
  338. },
  339. "obj_bboxes": [
  340. {"bbox": objects[i]["bbox"], "lines": objects[i]["lines"], "index": objects[i]["index"]}
  341. ],
  342. "sub_idx": k,
  343. }
  344. )
  345. seen_sub_idx.add(k)
  346. seen_idx.add(k)
  347. for i in range(len(subjects)):
  348. if i in seen_sub_idx:
  349. continue
  350. ret.append(
  351. {
  352. "sub_bbox": {
  353. "bbox": subjects[i]["bbox"],
  354. "lines": subjects[i]["lines"],
  355. "index": subjects[i]["index"],
  356. },
  357. "obj_bboxes": [],
  358. "sub_idx": i,
  359. }
  360. )
  361. return ret
  362. def get_type_blocks(blocks, block_type: Literal["image", "table"]):
  363. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  364. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  365. ret = []
  366. for v in with_captions:
  367. record = {
  368. f"{block_type}_body": v["sub_bbox"],
  369. f"{block_type}_caption_list": v["obj_bboxes"],
  370. }
  371. filter_idx = v["sub_idx"]
  372. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  373. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  374. ret.append(record)
  375. return ret
  376. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
  377. need_fix_blocks = get_type_blocks(blocks, fix_type)
  378. fixed_blocks = []
  379. for block in need_fix_blocks:
  380. body = block[f"{fix_type}_body"]
  381. caption_list = block[f"{fix_type}_caption_list"]
  382. footnote_list = block[f"{fix_type}_footnote_list"]
  383. body["type"] = f"{fix_type}_body"
  384. for caption in caption_list:
  385. caption["type"] = f"{fix_type}_caption"
  386. for footnote in footnote_list:
  387. footnote["type"] = f"{fix_type}_footnote"
  388. two_layer_block = {
  389. "type": fix_type,
  390. "bbox": body["bbox"],
  391. "blocks": [
  392. body,
  393. ],
  394. "index": body["index"],
  395. }
  396. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  397. fixed_blocks.append(two_layer_block)
  398. return fixed_blocks
  399. def fix_title_blocks(blocks):
  400. for block in blocks:
  401. if block["type"] == BlockType.TITLE:
  402. title_content = merge_para_with_text(block)
  403. title_level = count_leading_hashes(title_content)
  404. block['level'] = title_level
  405. for line in block['lines']:
  406. for span in line['spans']:
  407. span['content'] = strip_leading_hashes(span['content'])
  408. break
  409. break
  410. return blocks
  411. def count_leading_hashes(text):
  412. match = re.match(r'^(#+)', text)
  413. return len(match.group(1)) if match else 0
  414. def strip_leading_hashes(text):
  415. # 去除开头的#和紧随其后的空格
  416. return re.sub(r'^#+\s*', '', text)
  417. def fix_text_blocks(blocks):
  418. i = 0
  419. while i < len(blocks):
  420. block = blocks[i]
  421. last_line = block["lines"][-1]if block["lines"] else None
  422. if last_line:
  423. last_span = last_line["spans"][-1] if last_line["spans"] else None
  424. if last_span and last_span['content'].endswith('<|txt_contd|>'):
  425. last_span['content'] = last_span['content'][:-len('<|txt_contd|>')]
  426. # 查找下一个未被清空的块
  427. next_idx = i + 1
  428. while next_idx < len(blocks) and blocks[next_idx].get(SplitFlag.LINES_DELETED, False):
  429. next_idx += 1
  430. # 如果找到下一个有效块,则合并
  431. if next_idx < len(blocks):
  432. next_block = blocks[next_idx]
  433. # 将下一个块的lines扩展到当前块的lines中
  434. block["lines"].extend(next_block["lines"])
  435. # 清空下一个块的lines
  436. next_block["lines"] = []
  437. # 在下一个块中添加标志
  438. next_block[SplitFlag.LINES_DELETED] = True
  439. # 不增加i,继续检查当前块(现在已包含下一个块的内容)
  440. continue
  441. i += 1
  442. return blocks