vlm_magic_model.py 15 KB

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