vlm_magic_model.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import re
  2. from typing import Literal
  3. from loguru import logger
  4. from mineru.backend.vlm.vlm_middle_json_mkcontent import merge_para_with_text
  5. from mineru.utils.boxbase import calculate_overlap_area_in_bbox1_area_ratio
  6. from mineru.utils.enum_class import ContentType, BlockType
  7. from mineru.utils.guess_suffix_or_lang import guess_language_by_text
  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. code_block["guess_lang"] = guess_language_by_text(content_text)
  215. for block in not_include_image_blocks + not_include_table_blocks + not_include_code_blocks:
  216. block["type"] = BlockType.TEXT
  217. self.text_blocks.append(block)
  218. def get_list_blocks(self):
  219. return self.list_blocks
  220. def get_image_blocks(self):
  221. return self.image_blocks
  222. def get_table_blocks(self):
  223. return self.table_blocks
  224. def get_code_blocks(self):
  225. return self.code_blocks
  226. def get_ref_text_blocks(self):
  227. return self.ref_text_blocks
  228. def get_phonetic_blocks(self):
  229. return self.phonetic_blocks
  230. def get_title_blocks(self):
  231. return self.title_blocks
  232. def get_text_blocks(self):
  233. return self.text_blocks
  234. def get_interline_equation_blocks(self):
  235. return self.interline_equation_blocks
  236. def get_discarded_blocks(self):
  237. return self.discarded_blocks
  238. def get_all_spans(self):
  239. return self.all_spans
  240. def isolated_formula_clean(txt):
  241. latex = txt[:]
  242. if latex.startswith("\\["): latex = latex[2:]
  243. if latex.endswith("\\]"): latex = latex[:-2]
  244. latex = latex.strip()
  245. return latex
  246. def clean_content(content):
  247. if content and content.count("\\[") == content.count("\\]") and content.count("\\[") > 0:
  248. # Function to handle each match
  249. def replace_pattern(match):
  250. # Extract content between \[ and \]
  251. inner_content = match.group(1)
  252. return f"[{inner_content}]"
  253. # Find all patterns of \[x\] and apply replacement
  254. pattern = r'\\\[(.*?)\\\]'
  255. content = re.sub(pattern, replace_pattern, content)
  256. return content
  257. def __tie_up_category_by_distance_v3(blocks, subject_block_type, object_block_type):
  258. # 定义获取主体和客体对象的函数
  259. def get_subjects():
  260. return reduct_overlap(
  261. list(
  262. map(
  263. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},
  264. filter(
  265. lambda x: x["type"] == subject_block_type,
  266. blocks,
  267. ),
  268. )
  269. )
  270. )
  271. def get_objects():
  272. return reduct_overlap(
  273. list(
  274. map(
  275. lambda x: {"bbox": x["bbox"], "lines": x["lines"], "index": x["index"], "angle":x["angle"]},
  276. filter(
  277. lambda x: x["type"] == object_block_type,
  278. blocks,
  279. ),
  280. )
  281. )
  282. )
  283. # 调用通用方法
  284. return tie_up_category_by_distance_v3(
  285. get_subjects,
  286. get_objects
  287. )
  288. def get_type_blocks(blocks, block_type: Literal["image", "table", "code"]):
  289. with_captions = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_caption")
  290. with_footnotes = __tie_up_category_by_distance_v3(blocks, f"{block_type}_body", f"{block_type}_footnote")
  291. ret = []
  292. for v in with_captions:
  293. record = {
  294. f"{block_type}_body": v["sub_bbox"],
  295. f"{block_type}_caption_list": v["obj_bboxes"],
  296. }
  297. filter_idx = v["sub_idx"]
  298. d = next(filter(lambda x: x["sub_idx"] == filter_idx, with_footnotes))
  299. record[f"{block_type}_footnote_list"] = d["obj_bboxes"]
  300. ret.append(record)
  301. return ret
  302. def fix_two_layer_blocks(blocks, fix_type: Literal["image", "table", "code"]):
  303. need_fix_blocks = get_type_blocks(blocks, fix_type)
  304. fixed_blocks = []
  305. not_include_blocks = []
  306. processed_indices = set()
  307. # 处理需要组织成two_layer结构的blocks
  308. for block in need_fix_blocks:
  309. body = block[f"{fix_type}_body"]
  310. caption_list = block[f"{fix_type}_caption_list"]
  311. footnote_list = block[f"{fix_type}_footnote_list"]
  312. body["type"] = f"{fix_type}_body"
  313. for caption in caption_list:
  314. caption["type"] = f"{fix_type}_caption"
  315. processed_indices.add(caption["index"])
  316. for footnote in footnote_list:
  317. footnote["type"] = f"{fix_type}_footnote"
  318. processed_indices.add(footnote["index"])
  319. processed_indices.add(body["index"])
  320. two_layer_block = {
  321. "type": fix_type,
  322. "bbox": body["bbox"],
  323. "blocks": [
  324. body,
  325. ],
  326. "index": body["index"],
  327. }
  328. two_layer_block["blocks"].extend([*caption_list, *footnote_list])
  329. fixed_blocks.append(two_layer_block)
  330. # 添加未处理的blocks
  331. for block in blocks:
  332. if block["index"] not in processed_indices:
  333. # 直接添加未处理的block
  334. not_include_blocks.append(block)
  335. return fixed_blocks, not_include_blocks
  336. def fix_list_blocks(list_blocks, text_blocks, ref_text_blocks):
  337. for list_block in list_blocks:
  338. list_block["blocks"] = []
  339. if "lines" in list_block:
  340. del list_block["lines"]
  341. temp_text_blocks = text_blocks + ref_text_blocks
  342. need_remove_blocks = []
  343. for block in temp_text_blocks:
  344. for list_block in list_blocks:
  345. if calculate_overlap_area_in_bbox1_area_ratio(block["bbox"], list_block["bbox"]) >= 0.8:
  346. list_block["blocks"].append(block)
  347. need_remove_blocks.append(block)
  348. break
  349. for block in need_remove_blocks:
  350. if block in text_blocks:
  351. text_blocks.remove(block)
  352. elif block in ref_text_blocks:
  353. ref_text_blocks.remove(block)
  354. # 移除blocks为空的list_block
  355. list_blocks = [lb for lb in list_blocks if lb["blocks"]]
  356. for list_block in list_blocks:
  357. # 统计list_block["blocks"]中所有block的type,用众数作为list_block的sub_type
  358. type_count = {}
  359. line_content = []
  360. for sub_block in list_block["blocks"]:
  361. sub_block_type = sub_block["type"]
  362. if sub_block_type not in type_count:
  363. type_count[sub_block_type] = 0
  364. type_count[sub_block_type] += 1
  365. if type_count:
  366. list_block["sub_type"] = max(type_count, key=type_count.get)
  367. else:
  368. list_block["sub_type"] = "unknown"
  369. return list_blocks, text_blocks, ref_text_blocks