vlm_magic_model.py 18 KB

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