vlm_magic_model.py 19 KB

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