vlm_magic_model.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import re
  2. from typing import Literal
  3. from loguru import logger
  4. from pygments.lexers import guess_lexer
  5. from mineru.backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text
  6. from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
  7. from mineru.utils.enum_class import ContentType, BlockType
  8. from mineru.utils.magic_model_utils import reduct_overlap, tie_up_category_by_distance_v3
  9. class MagicModel:
  10. def __init__(self, page_blocks: list, width, height):
  11. self.page_blocks = page_blocks
  12. blocks = []
  13. self.all_spans = []
  14. # 解析每个块
  15. for index, block_info in enumerate(page_blocks):
  16. block_bbox = block_info["bbox"]
  17. try:
  18. x1, y1, x2, y2 = block_bbox
  19. x_1, y_1, x_2, y_2 = (
  20. int(x1 * width),
  21. int(y1 * height),
  22. int(x2 * width),
  23. int(y2 * height),
  24. )
  25. if x_2 < x_1:
  26. x_1, x_2 = x_2, x_1
  27. if y_2 < y_1:
  28. y_1, y_2 = y_2, y_1
  29. block_bbox = (x_1, y_1, x_2, y_2)
  30. block_type = block_info["type"]
  31. block_content = block_info["content"]
  32. block_angle = block_info["angle"]
  33. # print(f"坐标: {block_bbox}")
  34. # print(f"类型: {block_type}")
  35. # print(f"内容: {block_content}")
  36. # print("-" * 50)
  37. except Exception as e:
  38. # 如果解析失败,可能是因为格式不正确,跳过这个块
  39. logger.warning(f"Invalid block format: {block_info}, error: {e}")
  40. continue
  41. span_type = "unknown"
  42. if block_type in [
  43. "text",
  44. "title",
  45. "image_caption",
  46. "image_footnote",
  47. "table_caption",
  48. "table_footnote",
  49. "code_caption",
  50. "ref_text",
  51. "phonetic",
  52. "header",
  53. "footer",
  54. "page_number",
  55. "aside_text",
  56. "page_footnote",
  57. "list"
  58. ]:
  59. span_type = ContentType.TEXT
  60. elif block_type in ["image"]:
  61. block_type = BlockType.IMAGE_BODY
  62. span_type = ContentType.IMAGE
  63. elif block_type in ["table"]:
  64. block_type = BlockType.TABLE_BODY
  65. span_type = ContentType.TABLE
  66. elif block_type in ["code", "algorithm"]:
  67. line_type = block_type
  68. block_type = BlockType.CODE_BODY
  69. span_type = ContentType.TEXT
  70. elif block_type in ["equation"]:
  71. block_type = BlockType.INTERLINE_EQUATION
  72. span_type = ContentType.INTERLINE_EQUATION
  73. if span_type in ["image", "table"]:
  74. span = {
  75. "bbox": block_bbox,
  76. "type": span_type,
  77. }
  78. if span_type == ContentType.TABLE:
  79. span["html"] = block_content
  80. elif span_type in [ContentType.INTERLINE_EQUATION]:
  81. span = {
  82. "bbox": block_bbox,
  83. "type": span_type,
  84. "content": isolated_formula_clean(block_content),
  85. }
  86. else:
  87. if block_content:
  88. block_content = clean_content(block_content)
  89. if block_content and block_content.count("\\(") == block_content.count("\\)") and block_content.count("\\(") > 0:
  90. # 生成包含文本和公式的span列表
  91. spans = []
  92. last_end = 0
  93. # 查找所有公式
  94. for match in re.finditer(r'\\\((.+?)\\\)', block_content):
  95. start, end = match.span()
  96. # 添加公式前的文本
  97. if start > last_end:
  98. text_before = block_content[last_end:start]
  99. if text_before.strip():
  100. spans.append({
  101. "bbox": block_bbox,
  102. "type": ContentType.TEXT,
  103. "content": text_before
  104. })
  105. # 添加公式(去除\(和\))
  106. formula = match.group(1)
  107. spans.append({
  108. "bbox": block_bbox,
  109. "type": ContentType.INLINE_EQUATION,
  110. "content": formula.strip()
  111. })
  112. last_end = end
  113. # 添加最后一个公式后的文本
  114. if last_end < len(block_content):
  115. text_after = block_content[last_end:]
  116. if text_after.strip():
  117. spans.append({
  118. "bbox": block_bbox,
  119. "type": ContentType.TEXT,
  120. "content": text_after
  121. })
  122. span = spans
  123. else:
  124. span = {
  125. "bbox": block_bbox,
  126. "type": span_type,
  127. "content": block_content,
  128. }
  129. if isinstance(span, dict) and "bbox" in span:
  130. self.all_spans.append(span)
  131. if block_type == BlockType.CODE_BODY:
  132. line = {
  133. "bbox": block_bbox,
  134. "spans": [span],
  135. "type": line_type
  136. }
  137. else:
  138. line = {
  139. "bbox": block_bbox,
  140. "spans": [span],
  141. }
  142. elif isinstance(span, list):
  143. self.all_spans.extend(span)
  144. if block_type == BlockType.CODE_BODY:
  145. line = {
  146. "bbox": block_bbox,
  147. "spans": span,
  148. "type": line_type
  149. }
  150. else:
  151. line = {
  152. "bbox": block_bbox,
  153. "spans": span,
  154. }
  155. else:
  156. raise ValueError(f"Invalid span type: {span_type}, expected dict or list, got {type(span)}")
  157. blocks.append(
  158. {
  159. "bbox": block_bbox,
  160. "type": block_type,
  161. "angle": block_angle,
  162. "lines": [line],
  163. "index": index,
  164. }
  165. )
  166. self.image_blocks = []
  167. self.table_blocks = []
  168. self.interline_equation_blocks = []
  169. self.text_blocks = []
  170. self.title_blocks = []
  171. self.code_blocks = []
  172. self.discarded_blocks = []
  173. self.ref_text_blocks = []
  174. self.phonetic_blocks = []
  175. self.list_blocks = []
  176. for block in blocks:
  177. if block["type"] in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:
  178. self.image_blocks.append(block)
  179. elif block["type"] in [BlockType.TABLE_BODY, BlockType.TABLE_CAPTION, BlockType.TABLE_FOOTNOTE]:
  180. self.table_blocks.append(block)
  181. elif block["type"] in [BlockType.CODE_BODY, BlockType.CODE_CAPTION]:
  182. self.code_blocks.append(block)
  183. elif block["type"] == BlockType.INTERLINE_EQUATION:
  184. self.interline_equation_blocks.append(block)
  185. elif block["type"] == BlockType.TEXT:
  186. self.text_blocks.append(block)
  187. elif block["type"] == BlockType.TITLE:
  188. self.title_blocks.append(block)
  189. elif block["type"] in [BlockType.REF_TEXT]:
  190. self.ref_text_blocks.append(block)
  191. elif block["type"] in [BlockType.PHONETIC]:
  192. self.phonetic_blocks.append(block)
  193. elif block["type"] in [BlockType.HEADER, BlockType.FOOTER, BlockType.PAGE_NUMBER, BlockType.ASIDE_TEXT, BlockType.PAGE_FOOTNOTE]:
  194. self.discarded_blocks.append(block)
  195. elif block["type"] == BlockType.LIST:
  196. self.list_blocks.append(block)
  197. else:
  198. continue
  199. self.list_blocks, self.text_blocks, self.ref_text_blocks = fix_list_blocks(self.list_blocks, self.text_blocks, self.ref_text_blocks)
  200. self.image_blocks, not_include_image_blocks = fix_two_layer_blocks(self.image_blocks, BlockType.IMAGE)
  201. self.table_blocks, not_include_table_blocks = fix_two_layer_blocks(self.table_blocks, BlockType.TABLE)
  202. self.code_blocks, not_include_code_blocks = fix_two_layer_blocks(self.code_blocks, BlockType.CODE)
  203. for code_block in self.code_blocks:
  204. for block in code_block['blocks']:
  205. if block['type'] == BlockType.CODE_BODY:
  206. for line in block["lines"]:
  207. if "type" in line:
  208. code_block["sub_type"] = line["type"]
  209. del line["type"]
  210. else:
  211. code_block["sub_type"] = "code"
  212. if code_block["sub_type"] in ["code"]:
  213. content_text = merge_para_with_text(block)
  214. lexer = guess_lexer(content_text)
  215. code_block["guess_lang"] = lexer.aliases[0]
  216. for block in not_include_image_blocks + not_include_table_blocks + not_include_code_blocks:
  217. block["type"] = BlockType.TEXT
  218. self.text_blocks.append(block)
  219. def get_list_blocks(self):
  220. return self.list_blocks
  221. def get_image_blocks(self):
  222. return self.image_blocks
  223. def get_table_blocks(self):
  224. return self.table_blocks
  225. def get_code_blocks(self):
  226. return self.code_blocks
  227. def get_ref_text_blocks(self):
  228. return self.ref_text_blocks
  229. def get_phonetic_blocks(self):
  230. return self.phonetic_blocks
  231. def get_title_blocks(self):
  232. return self.title_blocks
  233. def get_text_blocks(self):
  234. return self.text_blocks
  235. def get_interline_equation_blocks(self):
  236. return self.interline_equation_blocks
  237. def get_discarded_blocks(self):
  238. return self.discarded_blocks
  239. def get_all_spans(self):
  240. return self.all_spans
  241. def isolated_formula_clean(txt):
  242. latex = txt[:]
  243. if latex.startswith("\\["): latex = latex[2:]
  244. if latex.endswith("\\]"): latex = latex[:-2]
  245. latex = latex.strip()
  246. return latex
  247. def clean_content(content):
  248. if content and content.count("\\[") == content.count("\\]") and content.count("\\[") > 0:
  249. # Function to handle each match
  250. def replace_pattern(match):
  251. # Extract content between \[ and \]
  252. inner_content = match.group(1)
  253. return f"[{inner_content}]"
  254. # Find all patterns of \[x\] and apply replacement
  255. pattern = r'\\\[(.*?)\\\]'
  256. content = re.sub(pattern, replace_pattern, content)
  257. return content
  258. def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):
  259. # 定义获取主体和客体对象的函数
  260. def get_subjects():
  261. return reduct_overlap(
  262. list(
  263. map(
  264. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},
  265. filter(
  266. lambda x: x["type"] == subject_block_type,
  267. blocks,
  268. ),
  269. )
  270. )
  271. )
  272. def get_objects():
  273. return reduct_overlap(
  274. list(
  275. map(
  276. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},
  277. filter(
  278. lambda x: x["type"] == object_block_type,
  279. blocks,
  280. ),
  281. )
  282. )
  283. )
  284. # 调用通用方法
  285. return tie_up_category_by_distance_v3(
  286. get_subjects,
  287. get_objects
  288. )
  289. def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):
  290. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  291. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  292. ret = []
  293. for v in with_captions:
  294. record = {
  295. f"{block_type}_body": v["sub_bbox"],
  296. f"{block_type}_caption_list": v["obj_bboxes"],
  297. }
  298. filter_idx = v["sub_idx"]
  299. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  300. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  301. ret.append(record)
  302. return ret
  303. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):
  304. need_fix_blocks = get_type_blocks(blocks, fix_type)
  305. fixed_blocks = []
  306. not_include_blocks = []
  307. processed_indices = set()
  308. # 处理需要组织成two_layer结构的blocks
  309. for block in need_fix_blocks:
  310. body = block[f"{fix_type}_body"]
  311. caption_list = block[f"{fix_type}_caption_list"]
  312. footnote_list = block[f"{fix_type}_footnote_list"]
  313. body["type"] = f"{fix_type}_body"
  314. for caption in caption_list:
  315. caption["type"] = f"{fix_type}_caption"
  316. processed_indices.add(caption["index"])
  317. for footnote in footnote_list:
  318. footnote["type"] = f"{fix_type}_footnote"
  319. processed_indices.add(footnote["index"])
  320. processed_indices.add(body["index"])
  321. two_layer_block = {
  322. "type": fix_type,
  323. "bbox": body["bbox"],
  324. "blocks": [
  325. body,
  326. ],
  327. "index": body["index"],
  328. }
  329. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  330. fixed_blocks.append(two_layer_block)
  331. # 添加未处理的blocks
  332. for block in blocks:
  333. if block["index"] not in processed_indices:
  334. # 直接添加未处理的block
  335. not_include_blocks.append(block)
  336. return fixed_blocks, not_include_blocks
  337. def fix_list_blocks(list_blocks, text_blocks, ref_text_blocks):
  338. for list_block in list_blocks:
  339. list_block["blocks"] = []
  340. if "lines" in list_block:
  341. del list_block["lines"]
  342. temp_text_blocks = text_blocks + ref_text_blocks
  343. need_remove_blocks = []
  344. for block in temp_text_blocks:
  345. for list_block in list_blocks:
  346. if calculate_overlap_area_in_bbox1_area_ratio(block["bbox"], list_block["bbox"]) >= 0.8:
  347. list_block["blocks"].append(block)
  348. need_remove_blocks.append(block)
  349. break
  350. for block in need_remove_blocks:
  351. if block in text_blocks:
  352. text_blocks.remove(block)
  353. elif block in ref_text_blocks:
  354. ref_text_blocks.remove(block)
  355. # 移除blocks为空的list_block
  356. list_blocks = [lb for lb in list_blocks if lb["blocks"]]
  357. for list_block in list_blocks:
  358. # 统计list_block["blocks"]中所有block的type,用众数作为list_block的sub_type
  359. type_count = {}
  360. line_content = []
  361. for sub_block in list_block["blocks"]:
  362. sub_block_type = sub_block["type"]
  363. if sub_block_type not in type_count:
  364. type_count[sub_block_type] = 0
  365. type_count[sub_block_type] += 1
  366. if type_count:
  367. list_block["sub_type"] = max(type_count, key=type_count.get)
  368. else:
  369. list_block["sub_type"] = "unknown"
  370. return list_blocks, text_blocks, ref_text_blocks