draw_bbox.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import json
  2. from io import BytesIO
  3. from loguru import logger
  4. from pypdf import PdfReader, PdfWriter, PageObject
  5. from reportlab.pdfgen import canvas
  6. from .enum_class import BlockType, ContentType, SplitFlag
  7. def cal_canvas_rect(page, bbox):
  8. """
  9. Calculate the rectangle coordinates on the canvas based on the original PDF page and bounding box.
  10. Args:
  11. page: A PyPDF2 Page object representing a single page in the PDF.
  12. bbox: [x0, y0, x1, y1] representing the bounding box coordinates.
  13. Returns:
  14. rect: [x0, y0, width, height] representing the rectangle coordinates on the canvas.
  15. """
  16. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  17. actual_width = page_width # The width of the final PDF display
  18. actual_height = page_height # The height of the final PDF display
  19. rotation_obj = page.get("/Rotate", 0)
  20. try:
  21. rotation = int(rotation_obj) % 360 # cast rotation to int to handle IndirectObject
  22. except (ValueError, TypeError) as e:
  23. logger.warning(f"Invalid /Rotate value {rotation_obj!r} on page; defaulting to 0. Error: {e}")
  24. rotation = 0
  25. if rotation in [90, 270]:
  26. # PDF is rotated 90 degrees or 270 degrees, and the width and height need to be swapped
  27. actual_width, actual_height = actual_height, actual_width
  28. x0, y0, x1, y1 = bbox
  29. rect_w = abs(x1 - x0)
  30. rect_h = abs(y1 - y0)
  31. if rotation == 270:
  32. rect_w, rect_h = rect_h, rect_w
  33. x0 = actual_height - y1
  34. y0 = actual_width - x1
  35. elif rotation == 180:
  36. x0 = page_width - x1
  37. # y0 stays the same
  38. elif rotation == 90:
  39. rect_w, rect_h = rect_h, rect_w
  40. x0, y0 = y0, x0
  41. else:
  42. # rotation == 0
  43. y0 = page_height - y1
  44. rect = [x0, y0, rect_w, rect_h]
  45. return rect
  46. def draw_bbox_without_number(i, bbox_list, page, c, rgb_config, fill_config):
  47. new_rgb = [float(color) / 255 for color in rgb_config]
  48. page_data = bbox_list[i]
  49. for bbox in page_data:
  50. rect = cal_canvas_rect(page, bbox) # Define the rectangle
  51. if fill_config: # filled rectangle
  52. c.setFillColorRGB(new_rgb[0], new_rgb[1], new_rgb[2], 0.3)
  53. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=0, fill=1)
  54. else: # bounding box
  55. c.setStrokeColorRGB(new_rgb[0], new_rgb[1], new_rgb[2])
  56. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=1, fill=0)
  57. return c
  58. def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_bbox=True):
  59. new_rgb = [float(color) / 255 for color in rgb_config]
  60. page_data = bbox_list[i]
  61. # 强制转换为 float
  62. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  63. for j, bbox in enumerate(page_data):
  64. # 确保bbox的每个元素都是float
  65. rect = cal_canvas_rect(page, bbox) # Define the rectangle
  66. if draw_bbox:
  67. if fill_config:
  68. c.setFillColorRGB(*new_rgb, 0.3)
  69. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=0, fill=1)
  70. else:
  71. c.setStrokeColorRGB(*new_rgb)
  72. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=1, fill=0)
  73. c.setFillColorRGB(*new_rgb, 1.0)
  74. c.setFontSize(size=10)
  75. c.saveState()
  76. rotation_obj = page.get("/Rotate", 0)
  77. try:
  78. rotation = int(rotation_obj) % 360 # cast rotation to int to handle IndirectObject
  79. except (ValueError, TypeError):
  80. logger.warning(f"Invalid /Rotate value: {rotation_obj!r}, defaulting to 0")
  81. rotation = 0
  82. if rotation == 0:
  83. c.translate(rect[0] + rect[2] + 2, rect[1] + rect[3] - 10)
  84. elif rotation == 90:
  85. c.translate(rect[0] + 10, rect[1] + rect[3] + 2)
  86. elif rotation == 180:
  87. c.translate(rect[0] - 2, rect[1] + 10)
  88. elif rotation == 270:
  89. c.translate(rect[0] + rect[2] - 10, rect[1] - 2)
  90. c.rotate(rotation)
  91. c.drawString(0, 0, str(j + 1))
  92. c.restoreState()
  93. return c
  94. def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
  95. dropped_bbox_list = []
  96. tables_body_list, tables_caption_list, tables_footnote_list = [], [], []
  97. imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []
  98. codes_body_list, codes_caption_list = [], []
  99. titles_list = []
  100. texts_list = []
  101. interequations_list = []
  102. lists_list = []
  103. indexs_list = []
  104. for page in pdf_info:
  105. page_dropped_list = []
  106. tables_body, tables_caption, tables_footnote = [], [], []
  107. imgs_body, imgs_caption, imgs_footnote = [], [], []
  108. codes_body, codes_caption = [], []
  109. titles = []
  110. texts = []
  111. interequations = []
  112. lists = []
  113. indices = []
  114. for dropped_bbox in page['discarded_blocks']:
  115. page_dropped_list.append(dropped_bbox['bbox'])
  116. dropped_bbox_list.append(page_dropped_list)
  117. for block in page["para_blocks"]:
  118. bbox = block["bbox"]
  119. if block["type"] == BlockType.TABLE:
  120. for nested_block in block["blocks"]:
  121. bbox = nested_block["bbox"]
  122. if nested_block["type"] == BlockType.TABLE_BODY:
  123. tables_body.append(bbox)
  124. elif nested_block["type"] == BlockType.TABLE_CAPTION:
  125. tables_caption.append(bbox)
  126. elif nested_block["type"] == BlockType.TABLE_FOOTNOTE:
  127. if nested_block.get(SplitFlag.CROSS_PAGE, False):
  128. continue
  129. tables_footnote.append(bbox)
  130. elif block["type"] == BlockType.IMAGE:
  131. for nested_block in block["blocks"]:
  132. bbox = nested_block["bbox"]
  133. if nested_block["type"] == BlockType.IMAGE_BODY:
  134. imgs_body.append(bbox)
  135. elif nested_block["type"] == BlockType.IMAGE_CAPTION:
  136. imgs_caption.append(bbox)
  137. elif nested_block["type"] == BlockType.IMAGE_FOOTNOTE:
  138. imgs_footnote.append(bbox)
  139. elif block["type"] == BlockType.CODE:
  140. for nested_block in block["blocks"]:
  141. if nested_block["type"] == BlockType.CODE_BODY:
  142. bbox = nested_block["bbox"]
  143. codes_body.append(bbox)
  144. elif nested_block["type"] == BlockType.CODE_CAPTION:
  145. bbox = nested_block["bbox"]
  146. codes_caption.append(bbox)
  147. elif block["type"] == BlockType.TITLE:
  148. titles.append(bbox)
  149. elif block["type"] == BlockType.TEXT:
  150. texts.append(bbox)
  151. elif block["type"] == BlockType.INTERLINE_EQUATION:
  152. interequations.append(bbox)
  153. elif block["type"] == BlockType.LIST:
  154. lists.append(bbox)
  155. elif block["type"] == BlockType.INDEX:
  156. indices.append(bbox)
  157. tables_body_list.append(tables_body)
  158. tables_caption_list.append(tables_caption)
  159. tables_footnote_list.append(tables_footnote)
  160. imgs_body_list.append(imgs_body)
  161. imgs_caption_list.append(imgs_caption)
  162. imgs_footnote_list.append(imgs_footnote)
  163. titles_list.append(titles)
  164. texts_list.append(texts)
  165. interequations_list.append(interequations)
  166. lists_list.append(lists)
  167. indexs_list.append(indices)
  168. codes_body_list.append(codes_body)
  169. codes_caption_list.append(codes_caption)
  170. layout_bbox_list = []
  171. table_type_order = {"table_caption": 1, "table_body": 2, "table_footnote": 3}
  172. for page in pdf_info:
  173. page_block_list = []
  174. for block in page["para_blocks"]:
  175. if block["type"] in [
  176. BlockType.TEXT,
  177. BlockType.TITLE,
  178. BlockType.INTERLINE_EQUATION,
  179. BlockType.LIST,
  180. BlockType.INDEX,
  181. ]:
  182. bbox = block["bbox"]
  183. page_block_list.append(bbox)
  184. elif block["type"] in [BlockType.IMAGE]:
  185. for sub_block in block["blocks"]:
  186. bbox = sub_block["bbox"]
  187. page_block_list.append(bbox)
  188. elif block["type"] in [BlockType.TABLE]:
  189. sorted_blocks = sorted(block["blocks"], key=lambda x: table_type_order[x["type"]])
  190. for sub_block in sorted_blocks:
  191. if sub_block.get(SplitFlag.CROSS_PAGE, False):
  192. continue
  193. bbox = sub_block["bbox"]
  194. page_block_list.append(bbox)
  195. elif block["type"] in [BlockType.CODE]:
  196. for sub_block in block["blocks"]:
  197. bbox = sub_block["bbox"]
  198. page_block_list.append(bbox)
  199. layout_bbox_list.append(page_block_list)
  200. pdf_bytes_io = BytesIO(pdf_bytes)
  201. pdf_docs = PdfReader(pdf_bytes_io)
  202. output_pdf = PdfWriter()
  203. for i, page in enumerate(pdf_docs.pages):
  204. # 获取原始页面尺寸
  205. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  206. custom_page_size = (page_width, page_height)
  207. packet = BytesIO()
  208. # 使用原始PDF的尺寸创建canvas
  209. c = canvas.Canvas(packet, pagesize=custom_page_size)
  210. c = draw_bbox_without_number(i, codes_body_list, page, c, [102, 0, 204], True)
  211. c = draw_bbox_without_number(i, codes_caption_list, page, c, [204, 153, 255], True)
  212. c = draw_bbox_without_number(i, dropped_bbox_list, page, c, [158, 158, 158], True)
  213. c = draw_bbox_without_number(i, tables_body_list, page, c, [204, 204, 0], True)
  214. c = draw_bbox_without_number(i, tables_caption_list, page, c, [255, 255, 102], True)
  215. c = draw_bbox_without_number(i, tables_footnote_list, page, c, [229, 255, 204], True)
  216. c = draw_bbox_without_number(i, imgs_body_list, page, c, [153, 255, 51], True)
  217. c = draw_bbox_without_number(i, imgs_caption_list, page, c, [102, 178, 255], True)
  218. c = draw_bbox_without_number(i, imgs_footnote_list, page, c, [255, 178, 102], True)
  219. c = draw_bbox_without_number(i, titles_list, page, c, [102, 102, 255], True)
  220. c = draw_bbox_without_number(i, texts_list, page, c, [153, 0, 76], True)
  221. c = draw_bbox_without_number(i, interequations_list, page, c, [0, 255, 0], True)
  222. c = draw_bbox_without_number(i, lists_list, page, c, [40, 169, 92], True)
  223. c = draw_bbox_without_number(i, indexs_list, page, c, [40, 169, 92], True)
  224. c = draw_bbox_with_number(i, layout_bbox_list, page, c, [255, 0, 0], False, draw_bbox=False)
  225. c.save()
  226. packet.seek(0)
  227. overlay_pdf = PdfReader(packet)
  228. # 添加检查确保overlay_pdf.pages不为空
  229. if len(overlay_pdf.pages) > 0:
  230. new_page = PageObject(pdf=None)
  231. new_page.update(page)
  232. page = new_page
  233. page.merge_page(overlay_pdf.pages[0])
  234. else:
  235. # 记录日志并继续处理下一个页面
  236. # logger.warning(f"layout.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  237. pass
  238. output_pdf.add_page(page)
  239. # 保存结果
  240. with open(f"{out_path}/{filename}", "wb") as f:
  241. output_pdf.write(f)
  242. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  243. text_list = []
  244. inline_equation_list = []
  245. interline_equation_list = []
  246. image_list = []
  247. table_list = []
  248. dropped_list = []
  249. def get_span_info(span):
  250. if span['type'] == ContentType.TEXT:
  251. page_text_list.append(span['bbox'])
  252. elif span['type'] == ContentType.INLINE_EQUATION:
  253. page_inline_equation_list.append(span['bbox'])
  254. elif span['type'] == ContentType.INTERLINE_EQUATION:
  255. page_interline_equation_list.append(span['bbox'])
  256. elif span['type'] == ContentType.IMAGE:
  257. page_image_list.append(span['bbox'])
  258. elif span['type'] == ContentType.TABLE:
  259. page_table_list.append(span['bbox'])
  260. for page in pdf_info:
  261. page_text_list = []
  262. page_inline_equation_list = []
  263. page_interline_equation_list = []
  264. page_image_list = []
  265. page_table_list = []
  266. page_dropped_list = []
  267. # 构造dropped_list
  268. for block in page['discarded_blocks']:
  269. if block['type'] == BlockType.DISCARDED:
  270. for line in block['lines']:
  271. for span in line['spans']:
  272. page_dropped_list.append(span['bbox'])
  273. dropped_list.append(page_dropped_list)
  274. # 构造其余useful_list
  275. # for block in page['para_blocks']: # span直接用分段合并前的结果就可以
  276. for block in page['preproc_blocks']:
  277. if block['type'] in [
  278. BlockType.TEXT,
  279. BlockType.TITLE,
  280. BlockType.INTERLINE_EQUATION,
  281. BlockType.LIST,
  282. BlockType.INDEX,
  283. ]:
  284. for line in block['lines']:
  285. for span in line['spans']:
  286. get_span_info(span)
  287. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  288. for sub_block in block['blocks']:
  289. for line in sub_block['lines']:
  290. for span in line['spans']:
  291. get_span_info(span)
  292. text_list.append(page_text_list)
  293. inline_equation_list.append(page_inline_equation_list)
  294. interline_equation_list.append(page_interline_equation_list)
  295. image_list.append(page_image_list)
  296. table_list.append(page_table_list)
  297. pdf_bytes_io = BytesIO(pdf_bytes)
  298. pdf_docs = PdfReader(pdf_bytes_io)
  299. output_pdf = PdfWriter()
  300. for i, page in enumerate(pdf_docs.pages):
  301. # 获取原始页面尺寸
  302. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  303. custom_page_size = (page_width, page_height)
  304. packet = BytesIO()
  305. # 使用原始PDF的尺寸创建canvas
  306. c = canvas.Canvas(packet, pagesize=custom_page_size)
  307. # 获取当前页面的数据
  308. draw_bbox_without_number(i, text_list, page, c,[255, 0, 0], False)
  309. draw_bbox_without_number(i, inline_equation_list, page, c, [0, 255, 0], False)
  310. draw_bbox_without_number(i, interline_equation_list, page, c, [0, 0, 255], False)
  311. draw_bbox_without_number(i, image_list, page, c, [255, 204, 0], False)
  312. draw_bbox_without_number(i, table_list, page, c, [204, 0, 255], False)
  313. draw_bbox_without_number(i, dropped_list, page, c, [158, 158, 158], False)
  314. c.save()
  315. packet.seek(0)
  316. overlay_pdf = PdfReader(packet)
  317. # 添加检查确保overlay_pdf.pages不为空
  318. if len(overlay_pdf.pages) > 0:
  319. new_page = PageObject(pdf=None)
  320. new_page.update(page)
  321. page = new_page
  322. page.merge_page(overlay_pdf.pages[0])
  323. else:
  324. # 记录日志并继续处理下一个页面
  325. # logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  326. pass
  327. output_pdf.add_page(page)
  328. # Save the PDF
  329. with open(f"{out_path}/{filename}", "wb") as f:
  330. output_pdf.write(f)
  331. def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  332. layout_bbox_list = []
  333. for page in pdf_info:
  334. page_line_list = []
  335. for block in page['preproc_blocks']:
  336. if block['type'] in [BlockType.TEXT]:
  337. for line in block['lines']:
  338. bbox = line['bbox']
  339. index = line['index']
  340. page_line_list.append({'index': index, 'bbox': bbox})
  341. elif block['type'] in [BlockType.TITLE, BlockType.INTERLINE_EQUATION]:
  342. if 'virtual_lines' in block:
  343. if len(block['virtual_lines']) > 0 and block['virtual_lines'][0].get('index', None) is not None:
  344. for line in block['virtual_lines']:
  345. bbox = line['bbox']
  346. index = line['index']
  347. page_line_list.append({'index': index, 'bbox': bbox})
  348. else:
  349. for line in block['lines']:
  350. bbox = line['bbox']
  351. index = line['index']
  352. page_line_list.append({'index': index, 'bbox': bbox})
  353. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  354. for sub_block in block['blocks']:
  355. if sub_block['type'] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY]:
  356. if len(sub_block['virtual_lines']) > 0 and sub_block['virtual_lines'][0].get('index', None) is not None:
  357. for line in sub_block['virtual_lines']:
  358. bbox = line['bbox']
  359. index = line['index']
  360. page_line_list.append({'index': index, 'bbox': bbox})
  361. else:
  362. for line in sub_block['lines']:
  363. bbox = line['bbox']
  364. index = line['index']
  365. page_line_list.append({'index': index, 'bbox': bbox})
  366. elif sub_block['type'] in [BlockType.IMAGE_CAPTION, BlockType.TABLE_CAPTION, BlockType.IMAGE_FOOTNOTE, BlockType.TABLE_FOOTNOTE]:
  367. for line in sub_block['lines']:
  368. bbox = line['bbox']
  369. index = line['index']
  370. page_line_list.append({'index': index, 'bbox': bbox})
  371. sorted_bboxes = sorted(page_line_list, key=lambda x: x['index'])
  372. layout_bbox_list.append(sorted_bbox['bbox'] for sorted_bbox in sorted_bboxes)
  373. pdf_bytes_io = BytesIO(pdf_bytes)
  374. pdf_docs = PdfReader(pdf_bytes_io)
  375. output_pdf = PdfWriter()
  376. for i, page in enumerate(pdf_docs.pages):
  377. # 获取原始页面尺寸
  378. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  379. custom_page_size = (page_width, page_height)
  380. packet = BytesIO()
  381. # 使用原始PDF的尺寸创建canvas
  382. c = canvas.Canvas(packet, pagesize=custom_page_size)
  383. # 获取当前页面的数据
  384. draw_bbox_with_number(i, layout_bbox_list, page, c, [255, 0, 0], False)
  385. c.save()
  386. packet.seek(0)
  387. overlay_pdf = PdfReader(packet)
  388. # 添加检查确保overlay_pdf.pages不为空
  389. if len(overlay_pdf.pages) > 0:
  390. new_page = PageObject(pdf=None)
  391. new_page.update(page)
  392. page = new_page
  393. page.merge_page(overlay_pdf.pages[0])
  394. else:
  395. # 记录日志并继续处理下一个页面
  396. # logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  397. pass
  398. output_pdf.add_page(page)
  399. # Save the PDF
  400. with open(f"{out_path}/{filename}", "wb") as f:
  401. output_pdf.write(f)
  402. if __name__ == "__main__":
  403. # 读取PDF文件
  404. pdf_path = "examples/demo1.pdf"
  405. with open(pdf_path, "rb") as f:
  406. pdf_bytes = f.read()
  407. # 从json文件读取pdf_info
  408. json_path = "examples/demo1_1746005777.0863056_middle.json"
  409. with open(json_path, "r", encoding="utf-8") as f:
  410. pdf_ann = json.load(f)
  411. pdf_info = pdf_ann["pdf_info"]
  412. # 调用可视化函数,输出到examples目录
  413. draw_layout_bbox(pdf_info, pdf_bytes, "examples", "output_with_layout.pdf")