vlm_magic_model.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 convert_otsl_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. # 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 __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):
  220. # 定义获取主体和客体对象的函数
  221. def get_subjects():
  222. return reduct_overlap(
  223. list(
  224. map(
  225. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"]},
  226. filter(
  227. lambda x: x["type"] == subject_block_type,
  228. blocks,
  229. ),
  230. )
  231. )
  232. )
  233. def get_objects():
  234. return 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"] == object_block_type,
  240. blocks,
  241. ),
  242. )
  243. )
  244. )
  245. # 调用通用方法
  246. return tie_up_category_by_distance_v3(
  247. get_subjects,
  248. get_objects
  249. )
  250. def get_type_blocks(blocks, block_type: Literal["image", "table"]):
  251. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  252. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  253. ret = []
  254. for v in with_captions:
  255. record = {
  256. f"{block_type}_body": v["sub_bbox"],
  257. f"{block_type}_caption_list": v["obj_bboxes"],
  258. }
  259. filter_idx = v["sub_idx"]
  260. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  261. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  262. ret.append(record)
  263. return ret
  264. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table"]):
  265. need_fix_blocks = get_type_blocks(blocks, fix_type)
  266. fixed_blocks = []
  267. for block in need_fix_blocks:
  268. body = block[f"{fix_type}_body"]
  269. caption_list = block[f"{fix_type}_caption_list"]
  270. footnote_list = block[f"{fix_type}_footnote_list"]
  271. body["type"] = f"{fix_type}_body"
  272. for caption in caption_list:
  273. caption["type"] = f"{fix_type}_caption"
  274. for footnote in footnote_list:
  275. footnote["type"] = f"{fix_type}_footnote"
  276. two_layer_block = {
  277. "type": fix_type,
  278. "bbox": body["bbox"],
  279. "blocks": [
  280. body,
  281. ],
  282. "index": body["index"],
  283. }
  284. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  285. fixed_blocks.append(two_layer_block)
  286. return fixed_blocks
  287. def fix_title_blocks(blocks):
  288. for block in blocks:
  289. if block["type"] == BlockType.TITLE:
  290. title_content = merge_para_with_text(block)
  291. title_level = count_leading_hashes(title_content)
  292. block['level'] = title_level
  293. for line in block['lines']:
  294. for span in line['spans']:
  295. span['content'] = strip_leading_hashes(span['content'])
  296. break
  297. break
  298. return blocks
  299. def count_leading_hashes(text):
  300. match = re.match(r'^(#+)', text)
  301. return len(match.group(1)) if match else 0
  302. def strip_leading_hashes(text):
  303. # 去除开头的#和紧随其后的空格
  304. return re.sub(r'^#+\s*', '', text)
  305. def fix_text_blocks(blocks):
  306. i = 0
  307. while i < len(blocks):
  308. block = blocks[i]
  309. last_line = block["lines"][-1]if block["lines"] else None
  310. if last_line:
  311. last_span = last_line["spans"][-1] if last_line["spans"] else None
  312. if last_span and last_span['content'].endswith('<|txt_contd|>'):
  313. last_span['content'] = last_span['content'][:-len('<|txt_contd|>')]
  314. # 查找下一个未被清空的块
  315. next_idx = i + 1
  316. while next_idx < len(blocks) and blocks[next_idx].get(SplitFlag.LINES_DELETED, False):
  317. next_idx += 1
  318. # 如果找到下一个有效块,则合并
  319. if next_idx < len(blocks):
  320. next_block = blocks[next_idx]
  321. # 将下一个块的lines扩展到当前块的lines中
  322. block["lines"].extend(next_block["lines"])
  323. # 清空下一个块的lines
  324. next_block["lines"] = []
  325. # 在下一个块中添加标志
  326. next_block[SplitFlag.LINES_DELETED] = True
  327. # 不增加i,继续检查当前块(现在已包含下一个块的内容)
  328. continue
  329. i += 1
  330. return blocks