vlm_magic_model.py 14 KB

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