vlm_magic_model.py 15 KB

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