vlm_magic_model.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import re
  2. from typing import Literal
  3. from loguru import logger
  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 block_content_to_html
  7. from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3
  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. # 如果bbox是0,0,999,999,且type为text,按notes增加表格处理
  37. if x1 == 0 and y1 == 0 and x2 == 999 and y2 == 999 and block_type == "text":
  38. block_content = block_content_to_html(block_content)
  39. # print(f"坐标: {block_bbox}")
  40. # print(f"类型: {block_type}")
  41. # print(f"内容: {block_content}")
  42. # print("-" * 50)
  43. except Exception as e:
  44. # 如果解析失败,可能是因为格式不正确,跳过这个块
  45. logger.warning(f"Invalid block format: {block_info}, error: {e}")
  46. continue
  47. span_type = "unknown"
  48. if block_type in [
  49. "text",
  50. "title",
  51. "image_caption",
  52. "image_footnote",
  53. "table_caption",
  54. "table_footnote",
  55. "list",
  56. "index",
  57. ]:
  58. span_type = ContentType.TEXT
  59. elif block_type in ["image"]:
  60. block_type = BlockType.IMAGE_BODY
  61. span_type = ContentType.IMAGE
  62. elif block_type in ["table"]:
  63. block_type = BlockType.TABLE_BODY
  64. span_type = ContentType.TABLE
  65. elif block_type in ["equation"]:
  66. block_type = BlockType.INTERLINE_EQUATION
  67. span_type = ContentType.INTERLINE_EQUATION
  68. if span_type in ["image", "table"]:
  69. span = {
  70. "bbox": block_bbox,
  71. "type": span_type,
  72. }
  73. if span_type == ContentType.TABLE:
  74. span["html"] = block_content_to_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 __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):
  214. # 定义获取主体和客体对象的函数
  215. def get_subjects():
  216. return reduct_overlap(
  217. list(
  218. map(
  219. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  220. filter(
  221. lambda x: x["type"] == subject_block_type,
  222. blocks,
  223. ),
  224. )
  225. )
  226. )
  227. def get_objects():
  228. return 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"] == object_block_type,
  234. blocks,
  235. ),
  236. )
  237. )
  238. )
  239. # 调用通用方法
  240. return tie_up_category_by_distance_v3(
  241. get_subjects,
  242. get_objects
  243. )
  244. def get_type_blocks(blocks, block_type: Literal["image", "table"]):
  245. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  246. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  247. ret = []
  248. for v in with_captions:
  249. record = {
  250. f"{block_type}_body": v["sub_bbox"],
  251. f"{block_type}_caption_list": v["obj_bboxes"],
  252. }
  253. filter_idx = v["sub_idx"]
  254. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  255. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  256. ret.append(record)
  257. return ret
  258. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
  259. need_fix_blocks = get_type_blocks(blocks, fix_type)
  260. fixed_blocks = []
  261. for block in need_fix_blocks:
  262. body = block[f"{fix_type}_body"]
  263. caption_list = block[f"{fix_type}_caption_list"]
  264. footnote_list = block[f"{fix_type}_footnote_list"]
  265. body["type"] = f"{fix_type}_body"
  266. for caption in caption_list:
  267. caption["type"] = f"{fix_type}_caption"
  268. for footnote in footnote_list:
  269. footnote["type"] = f"{fix_type}_footnote"
  270. two_layer_block = {
  271. "type": fix_type,
  272. "bbox": body["bbox"],
  273. "blocks": [
  274. body,
  275. ],
  276. "index": body["index"],
  277. }
  278. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  279. fixed_blocks.append(two_layer_block)
  280. return fixed_blocks
  281. def fix_title_blocks(blocks):
  282. for block in blocks:
  283. if block["type"] == BlockType.TITLE:
  284. title_content = merge_para_with_text(block)
  285. title_level = count_leading_hashes(title_content)
  286. block['level'] = title_level
  287. for line in block['lines']:
  288. for span in line['spans']:
  289. span['content'] = strip_leading_hashes(span['content'])
  290. break
  291. break
  292. return blocks
  293. def count_leading_hashes(text):
  294. match = re.match(r'^(#+)', text)
  295. return len(match.group(1)) if match else 0
  296. def strip_leading_hashes(text):
  297. # 去除开头的#和紧随其后的空格
  298. return re.sub(r'^#+\s*', '', text)
  299. def fix_text_blocks(blocks):
  300. i = 0
  301. while i < len(blocks):
  302. block = blocks[i]
  303. last_line = block["lines"][-1]if block["lines"] else None
  304. if last_line:
  305. last_span = last_line["spans"][-1] if last_line["spans"] else None
  306. if last_span and last_span['content'].endswith('<|txt_contd|>'):
  307. last_span['content'] = last_span['content'][:-len('<|txt_contd|>')]
  308. # 查找下一个未被清空的块
  309. next_idx = i + 1
  310. while next_idx < len(blocks) and blocks[next_idx].get(SplitFlag.LINES_DELETED, False):
  311. next_idx += 1
  312. # 如果找到下一个有效块,则合并
  313. if next_idx < len(blocks):
  314. next_block = blocks[next_idx]
  315. # 将下一个块的lines扩展到当前块的lines中
  316. block["lines"].extend(next_block["lines"])
  317. # 清空下一个块的lines
  318. next_block["lines"] = []
  319. # 在下一个块中添加标志
  320. next_block[SplitFlag.LINES_DELETED] = True
  321. # 不增加i,继续检查当前块(现在已包含下一个块的内容)
  322. continue
  323. i += 1
  324. return blocks