equations_replace.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. """
  2. 对pymupdf返回的结构里的公式进行替换,替换为模型识别的公式结果
  3. """
  4. from magic_pdf.libs.commons import fitz
  5. import json
  6. import os
  7. from pathlib import Path
  8. from loguru import logger
  9. TYPE_INLINE_EQUATION = "inline-equation"
  10. TYPE_INTERLINE_EQUATION = "interline-equation"
  11. def combine_chars_to_pymudict(block_dict, char_dict):
  12. """
  13. 把block级别的pymupdf 结构里加入char结构
  14. """
  15. # 因为block_dict 被裁剪过,因此先把他和char_dict文字块对齐,才能进行补充
  16. char_map = {tuple(item['bbox']):item for item in char_dict}
  17. for i in range(len(block_dict)): # blcok
  18. block = block_dict[i]
  19. key = block['bbox']
  20. char_dict_item = char_map[tuple(key)]
  21. char_dict_map = {tuple(item['bbox']):item for item in char_dict_item['lines']}
  22. for j in range(len(block['lines'])):
  23. lines = block['lines'][j]
  24. with_char_lines = char_dict_map[lines['bbox']]
  25. for k in range(len(lines['spans'])):
  26. spans = lines['spans'][k]
  27. try:
  28. chars = with_char_lines['spans'][k]['chars']
  29. except Exception as e:
  30. logger.error(char_dict[i]['lines'][j])
  31. spans['chars'] = chars
  32. return block_dict
  33. def calculate_overlap_area_2_minbox_area_ratio(bbox1, min_bbox):
  34. """
  35. 计算box1和box2的重叠面积占最小面积的box的比例
  36. """
  37. # Determine the coordinates of the intersection rectangle
  38. x_left = max(bbox1[0], min_bbox[0])
  39. y_top = max(bbox1[1], min_bbox[1])
  40. x_right = min(bbox1[2], min_bbox[2])
  41. y_bottom = min(bbox1[3], min_bbox[3])
  42. if x_right < x_left or y_bottom < y_top:
  43. return 0.0
  44. # The area of overlap area
  45. intersection_area = (x_right - x_left) * (y_bottom - y_top)
  46. min_box_area = (min_bbox[3]-min_bbox[1])*(min_bbox[2]-min_bbox[0])
  47. if min_box_area==0:
  48. return 0
  49. else:
  50. return intersection_area / min_box_area
  51. def _is_xin(bbox1, bbox2):
  52. area1 = abs(bbox1[2]-bbox1[0])*abs(bbox1[3]-bbox1[1])
  53. area2 = abs(bbox2[2]-bbox2[0])*abs(bbox2[3]-bbox2[1])
  54. if area1<area2:
  55. ratio = calculate_overlap_area_2_minbox_area_ratio(bbox2, bbox1)
  56. else:
  57. ratio = calculate_overlap_area_2_minbox_area_ratio(bbox1, bbox2)
  58. return ratio>0.6
  59. def remove_text_block_in_interline_equation_bbox(interline_bboxes, text_blocks):
  60. """消除掉整个块都在行间公式块内部的文本块"""
  61. for eq_bbox in interline_bboxes:
  62. removed_txt_blk = []
  63. for text_blk in text_blocks:
  64. text_bbox = text_blk['bbox']
  65. if calculate_overlap_area_2_minbox_area_ratio(eq_bbox['bbox'], text_bbox)>=0.7:
  66. removed_txt_blk.append(text_blk)
  67. for blk in removed_txt_blk:
  68. text_blocks.remove(blk)
  69. return text_blocks
  70. def _is_in_or_part_overlap(box1, box2) -> bool:
  71. """
  72. 两个bbox是否有部分重叠或者包含
  73. """
  74. if box1 is None or box2 is None:
  75. return False
  76. x0_1, y0_1, x1_1, y1_1 = box1
  77. x0_2, y0_2, x1_2, y1_2 = box2
  78. return not (x1_1 < x0_2 or # box1在box2的左边
  79. x0_1 > x1_2 or # box1在box2的右边
  80. y1_1 < y0_2 or # box1在box2的上边
  81. y0_1 > y1_2) # box1在box2的下边
  82. def remove_text_block_overlap_interline_equation_bbox(interline_eq_bboxes, pymu_block_list):
  83. """消除掉行行内公式有部分重叠的文本块的内容。
  84. 同时重新计算消除重叠之后文本块的大小"""
  85. deleted_block = []
  86. for text_block in pymu_block_list:
  87. deleted_line = []
  88. for line in text_block['lines']:
  89. deleted_span = []
  90. for span in line['spans']:
  91. deleted_chars = []
  92. for char in span['chars']:
  93. if any([_is_in_or_part_overlap(char['bbox'], eq_bbox['bbox']) for eq_bbox in interline_eq_bboxes]):
  94. deleted_chars.append(char)
  95. # 检查span里没有char则删除这个span
  96. for char in deleted_chars:
  97. span['chars'].remove(char)
  98. # 重新计算这个span的大小
  99. if len(span['chars'])==0: # 删除这个span
  100. deleted_span.append(span)
  101. else:
  102. span['bbox'] = min([b['bbox'][0] for b in span['chars']]),min([b['bbox'][1] for b in span['chars']]),max([b['bbox'][2] for b in span['chars']]), max([b['bbox'][3] for b in span['chars']])
  103. # 检查这个span
  104. for span in deleted_span:
  105. line['spans'].remove(span)
  106. if len(line['spans'])==0: #删除这个line
  107. deleted_line.append(line)
  108. else:
  109. line['bbox'] = min([b['bbox'][0] for b in line['spans']]),min([b['bbox'][1] for b in line['spans']]),max([b['bbox'][2] for b in line['spans']]), max([b['bbox'][3] for b in line['spans']])
  110. # 检查这个block是否可以删除
  111. for line in deleted_line:
  112. text_block['lines'].remove(line)
  113. if len(text_block['lines'])==0: # 删除block
  114. deleted_block.append(text_block)
  115. else:
  116. text_block['bbox'] = min([b['bbox'][0] for b in text_block['lines']]),min([b['bbox'][1] for b in text_block['lines']]),max([b['bbox'][2] for b in text_block['lines']]), max([b['bbox'][3] for b in text_block['lines']])
  117. # 检查text block删除
  118. for block in deleted_block:
  119. pymu_block_list.remove(block)
  120. if len(pymu_block_list)==0:
  121. return []
  122. return pymu_block_list
  123. def insert_interline_equations_textblock(interline_eq_bboxes, pymu_block_list):
  124. """在行间公式对应的地方插上一个伪造的block"""
  125. for eq in interline_eq_bboxes:
  126. bbox = eq['bbox']
  127. latex_content = eq['latex_text']
  128. text_block = {
  129. "number": len(pymu_block_list),
  130. "type": 0,
  131. "bbox": bbox,
  132. "lines": [
  133. {
  134. "spans": [
  135. {
  136. "size": 9.962599754333496,
  137. "_type": TYPE_INTERLINE_EQUATION,
  138. "flags": 4,
  139. "font": TYPE_INTERLINE_EQUATION,
  140. "color": 0,
  141. "ascender": 0.9409999847412109,
  142. "descender": -0.3050000071525574,
  143. "text": f"\n$$\n{latex_content}\n$$\n",
  144. "origin": [
  145. bbox[0],
  146. bbox[1]
  147. ],
  148. "bbox": bbox
  149. }
  150. ],
  151. "wmode": 0,
  152. "dir": [
  153. 1.0,
  154. 0.0
  155. ],
  156. "bbox": bbox
  157. }
  158. ]
  159. }
  160. pymu_block_list.append(text_block)
  161. def x_overlap_ratio(box1, box2):
  162. a, _, c, _ = box1
  163. e, _, g, _ = box2
  164. # 计算重叠宽度
  165. overlap_x = max(min(c, g) - max(a, e), 0)
  166. # 计算box1的宽度
  167. width1 = g - e
  168. # 计算重叠比例
  169. overlap_ratio = overlap_x / width1 if width1 != 0 else 0
  170. return overlap_ratio
  171. def __is_x_dir_overlap(bbox1, bbox2):
  172. return not (bbox1[2]<bbox2[0] or bbox1[0]>bbox2[2])
  173. def __y_overlap_ratio(box1, box2):
  174. """"""
  175. _, b, _, d = box1
  176. _, f, _, h = box2
  177. # 计算重叠高度
  178. overlap_y = max(min(d, h) - max(b, f), 0)
  179. # 计算box1的高度
  180. height1 = d - b
  181. # 计算重叠比例
  182. overlap_ratio = overlap_y / height1 if height1 != 0 else 0
  183. return overlap_ratio
  184. def replace_line_v2(eqinfo, line):
  185. """
  186. 扫描这一行所有的和公式框X方向重叠的char,然后计算char的左、右x0, x1,位于这个区间内的span删除掉。
  187. 最后与这个x0,x1有相交的span0, span1内部进行分割。
  188. """
  189. first_overlap_span = -1
  190. first_overlap_span_idx = -1
  191. last_overlap_span = -1
  192. delete_chars = []
  193. for i in range(0, len(line['spans'])):
  194. if line['spans'][i].get("_type", None) is not None:
  195. continue # 忽略,因为已经是插入的伪造span公式了
  196. for char in line['spans'][i]['chars']:
  197. if __is_x_dir_overlap(eqinfo['bbox'], char['bbox']):
  198. line_txt = ""
  199. for span in line['spans']:
  200. span_txt = "<span>"
  201. for ch in span['chars']:
  202. span_txt = span_txt + ch['c']
  203. span_txt = span_txt + "</span>"
  204. line_txt = line_txt + span_txt
  205. if first_overlap_span_idx == -1:
  206. first_overlap_span = line['spans'][i]
  207. first_overlap_span_idx = i
  208. last_overlap_span = line['spans'][i]
  209. delete_chars.append(char)
  210. # 第一个和最后一个char要进行检查,到底属于公式多还是属于正常span多
  211. if len(delete_chars)>0:
  212. ch0_bbox = delete_chars[0]['bbox']
  213. if x_overlap_ratio(eqinfo['bbox'], ch0_bbox)<0.51:
  214. delete_chars.remove(delete_chars[0])
  215. if len(delete_chars)>0:
  216. ch0_bbox = delete_chars[-1]['bbox']
  217. if x_overlap_ratio(eqinfo['bbox'], ch0_bbox)<0.51:
  218. delete_chars.remove(delete_chars[-1])
  219. # 计算x方向上被删除区间内的char的真实x0, x1
  220. if len(delete_chars):
  221. x0, x1 = min([b['bbox'][0] for b in delete_chars]), max([b['bbox'][2] for b in delete_chars])
  222. else:
  223. logger.debug(f"行内公式替换没有发生,尝试下一行匹配, eqinfo={eqinfo}")
  224. return False
  225. # 删除位于x0, x1这两个中间的span
  226. delete_span = []
  227. for span in line['spans']:
  228. span_box = span['bbox']
  229. if x0<=span_box[0] and span_box[2]<=x1:
  230. delete_span.append(span)
  231. for span in delete_span:
  232. line['spans'].remove(span)
  233. equation_span = {
  234. "size": 9.962599754333496,
  235. "_type": TYPE_INLINE_EQUATION,
  236. "flags": 4,
  237. "font": TYPE_INLINE_EQUATION,
  238. "color": 0,
  239. "ascender": 0.9409999847412109,
  240. "descender": -0.3050000071525574,
  241. "text": "",
  242. "origin": [
  243. 337.1410153102337,
  244. 216.0205245153934
  245. ],
  246. "bbox": [
  247. 337.1410153102337,
  248. 216.0205245153934,
  249. 390.4496373892022,
  250. 228.50171037628277
  251. ]
  252. }
  253. #equation_span = line['spans'][0].copy()
  254. equation_span['text'] = f" ${eqinfo['latex_text']}$ "
  255. equation_span['bbox'] = [x0, equation_span['bbox'][1], x1, equation_span['bbox'][3]]
  256. equation_span['origin'] = [equation_span['bbox'][0], equation_span['bbox'][1]]
  257. equation_span['chars'] = delete_chars
  258. equation_span['_type'] = TYPE_INLINE_EQUATION
  259. equation_span['_eq_bbox'] = eqinfo['bbox']
  260. line['spans'].insert(first_overlap_span_idx+1, equation_span) # 放入公式
  261. # logger.info(f"==>text is 【{line_txt}】, equation is 【{eqinfo['latex_text']}】")
  262. # 第一个、和最后一个有overlap的span进行分割,然后插入对应的位置
  263. first_span_chars = [char for char in first_overlap_span['chars'] if (char['bbox'][2]+char['bbox'][0])/2<x0]
  264. tail_span_chars = [char for char in last_overlap_span['chars'] if (char['bbox'][0]+char['bbox'][2])/2>x1]
  265. if len(first_span_chars)>0:
  266. first_overlap_span['chars'] = first_span_chars
  267. first_overlap_span['text'] = ''.join([char['c'] for char in first_span_chars])
  268. first_overlap_span['bbox'] = (first_overlap_span['bbox'][0], first_overlap_span['bbox'][1], max([chr['bbox'][2] for chr in first_span_chars]), first_overlap_span['bbox'][3])
  269. # first_overlap_span['_type'] = "first"
  270. else:
  271. # 删掉
  272. if first_overlap_span not in delete_span:
  273. line['spans'].remove(first_overlap_span)
  274. if len(tail_span_chars)>0:
  275. if last_overlap_span==first_overlap_span: # 这个时候应该插入一个新的
  276. tail_span_txt = ''.join([char['c'] for char in tail_span_chars])
  277. last_span_to_insert = last_overlap_span.copy()
  278. last_span_to_insert['chars'] = tail_span_chars
  279. last_span_to_insert['text'] = ''.join([char['c'] for char in tail_span_chars])
  280. last_span_to_insert['bbox'] = (min([chr['bbox'][0] for chr in tail_span_chars]), last_overlap_span['bbox'][1], last_overlap_span['bbox'][2], last_overlap_span['bbox'][3])
  281. # 插入到公式对象之后
  282. equation_idx = line['spans'].index(equation_span)
  283. line['spans'].insert(equation_idx+1, last_span_to_insert) # 放入公式
  284. else: # 直接修改原来的span
  285. last_overlap_span['chars'] = tail_span_chars
  286. last_overlap_span['text'] = ''.join([char['c'] for char in tail_span_chars])
  287. last_overlap_span['bbox'] = (min([chr['bbox'][0] for chr in tail_span_chars]), last_overlap_span['bbox'][1], last_overlap_span['bbox'][2], last_overlap_span['bbox'][3])
  288. else:
  289. # 删掉
  290. if last_overlap_span not in delete_span and last_overlap_span!=first_overlap_span:
  291. line['spans'].remove(last_overlap_span)
  292. remain_txt = ""
  293. for span in line['spans']:
  294. span_txt = "<span>"
  295. for char in span['chars']:
  296. span_txt = span_txt + char['c']
  297. span_txt = span_txt + "</span>"
  298. remain_txt = remain_txt + span_txt
  299. # logger.info(f"<== succ replace, text is 【{remain_txt}】, equation is 【{eqinfo['latex_text']}】")
  300. return True
  301. def replace_eq_blk(eqinfo, text_block):
  302. """替换行内公式"""
  303. for line in text_block['lines']:
  304. line_bbox = line['bbox']
  305. if _is_xin(eqinfo['bbox'], line_bbox) or __y_overlap_ratio(eqinfo['bbox'], line_bbox)>0.6: # 定位到行, 使用y方向重合率是因为有的时候,一个行的宽度会小于公式位置宽度:行很高,公式很窄,
  306. replace_succ = replace_line_v2(eqinfo, line)
  307. if not replace_succ: # 有的时候,一个pdf的line高度从API里会计算的有问题,因此在行内span级别会替换不成功,这就需要继续重试下一行
  308. continue
  309. else:
  310. break
  311. else:
  312. return False
  313. return True
  314. def replace_inline_equations(inline_equation_bboxes, raw_text_blocks):
  315. """替换行内公式"""
  316. for eqinfo in inline_equation_bboxes:
  317. eqbox = eqinfo['bbox']
  318. for blk in raw_text_blocks:
  319. if _is_xin(eqbox, blk['bbox']):
  320. if not replace_eq_blk(eqinfo, blk):
  321. logger.error(f"行内公式没有替换成功:{eqinfo} ")
  322. else:
  323. break
  324. return raw_text_blocks
  325. def remove_chars_in_text_blocks(text_blocks):
  326. """删除text_blocks里的char"""
  327. for blk in text_blocks:
  328. for line in blk['lines']:
  329. for span in line['spans']:
  330. _ = span.pop("chars", "no such key")
  331. return text_blocks
  332. def replace_equations_in_textblock(raw_text_blocks, inline_equation_bboxes, interline_equation_bboxes):
  333. """
  334. 替换行间和和行内公式为latex
  335. """
  336. raw_text_blocks = remove_text_block_in_interline_equation_bbox(interline_equation_bboxes, raw_text_blocks) # 消除重叠:第一步,在公式内部的
  337. raw_text_blocks = remove_text_block_overlap_interline_equation_bbox(interline_equation_bboxes, raw_text_blocks) # 消重,第二步,和公式覆盖的
  338. insert_interline_equations_textblock(interline_equation_bboxes, raw_text_blocks)
  339. raw_text_blocks = replace_inline_equations(inline_equation_bboxes, raw_text_blocks)
  340. return raw_text_blocks
  341. def draw_block_on_pdf_with_txt_replace_eq_bbox(json_path, pdf_path):
  342. """
  343. """
  344. new_pdf = f"{Path(pdf_path).parent}/{Path(pdf_path).stem}.step3-消除行内公式text_block.pdf"
  345. with open(json_path, "r", encoding='utf-8') as f:
  346. obj = json.loads(f.read())
  347. if os.path.exists(new_pdf):
  348. os.remove(new_pdf)
  349. new_doc = fitz.open('')
  350. doc = fitz.open(pdf_path)
  351. new_doc = fitz.open(pdf_path)
  352. for i in range(len(new_doc)):
  353. page = new_doc[i]
  354. inline_equation_bboxes = obj[f"page_{i}"]['inline_equations']
  355. interline_equation_bboxes = obj[f"page_{i}"]['interline_equations']
  356. raw_text_blocks = obj[f'page_{i}']['preproc_blocks']
  357. raw_text_blocks = remove_text_block_in_interline_equation_bbox(interline_equation_bboxes, raw_text_blocks) # 消除重叠:第一步,在公式内部的
  358. raw_text_blocks = remove_text_block_overlap_interline_equation_bbox(interline_equation_bboxes, raw_text_blocks) # 消重,第二步,和公式覆盖的
  359. insert_interline_equations_textblock(interline_equation_bboxes, raw_text_blocks)
  360. raw_text_blocks = replace_inline_equations(inline_equation_bboxes, raw_text_blocks)
  361. # 为了检验公式是否重复,把每一行里,含有公式的span背景改成黄色的
  362. color_map = [fitz.pdfcolor['blue'],fitz.pdfcolor['green']]
  363. j = 0
  364. for blk in raw_text_blocks:
  365. for i,line in enumerate(blk['lines']):
  366. # line_box = line['bbox']
  367. # shape = page.new_shape()
  368. # shape.draw_rect(line_box)
  369. # shape.finish(color=fitz.pdfcolor['red'], fill=color_map[j%2], fill_opacity=0.3)
  370. # shape.commit()
  371. # j = j+1
  372. for i, span in enumerate(line['spans']):
  373. shape_page = page.new_shape()
  374. span_type = span.get('_type')
  375. color = fitz.pdfcolor['blue']
  376. if span_type=='first':
  377. color = fitz.pdfcolor['blue']
  378. elif span_type=='tail':
  379. color = fitz.pdfcolor['green']
  380. elif span_type==TYPE_INLINE_EQUATION:
  381. color = fitz.pdfcolor['black']
  382. else:
  383. color = None
  384. b = span['bbox']
  385. shape_page.draw_rect(b)
  386. shape_page.finish(color=None, fill=color, fill_opacity=0.3)
  387. shape_page.commit()
  388. new_doc.save(new_pdf)
  389. logger.info(f"save ok {new_pdf}")
  390. final_json = json.dumps(obj, ensure_ascii=False,indent=2)
  391. with open("equations_test/final_json.json", "w") as f:
  392. f.write(final_json)
  393. return new_pdf
  394. if __name__=="__main__":
  395. # draw_block_on_pdf_with_txt_replace_eq_bbox(new_json_path, equation_color_pdf)
  396. pass