draw_bbox.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. list_items_list = []
  104. indexs_list = []
  105. for page in pdf_info:
  106. page_dropped_list = []
  107. tables_body, tables_caption, tables_footnote = [], [], []
  108. imgs_body, imgs_caption, imgs_footnote = [], [], []
  109. codes_body, codes_caption = [], []
  110. titles = []
  111. texts = []
  112. interequations = []
  113. lists = []
  114. list_items = []
  115. indices = []
  116. for dropped_bbox in page['discarded_blocks']:
  117. page_dropped_list.append(dropped_bbox['bbox'])
  118. dropped_bbox_list.append(page_dropped_list)
  119. for block in page["para_blocks"]:
  120. bbox = block["bbox"]
  121. if block["type"] == BlockType.TABLE:
  122. for nested_block in block["blocks"]:
  123. bbox = nested_block["bbox"]
  124. if nested_block["type"] == BlockType.TABLE_BODY:
  125. tables_body.append(bbox)
  126. elif nested_block["type"] == BlockType.TABLE_CAPTION:
  127. tables_caption.append(bbox)
  128. elif nested_block["type"] == BlockType.TABLE_FOOTNOTE:
  129. if nested_block.get(SplitFlag.CROSS_PAGE, False):
  130. continue
  131. tables_footnote.append(bbox)
  132. elif block["type"] == BlockType.IMAGE:
  133. for nested_block in block["blocks"]:
  134. bbox = nested_block["bbox"]
  135. if nested_block["type"] == BlockType.IMAGE_BODY:
  136. imgs_body.append(bbox)
  137. elif nested_block["type"] == BlockType.IMAGE_CAPTION:
  138. imgs_caption.append(bbox)
  139. elif nested_block["type"] == BlockType.IMAGE_FOOTNOTE:
  140. imgs_footnote.append(bbox)
  141. elif block["type"] == BlockType.CODE:
  142. for nested_block in block["blocks"]:
  143. if nested_block["type"] == BlockType.CODE_BODY:
  144. bbox = nested_block["bbox"]
  145. codes_body.append(bbox)
  146. elif nested_block["type"] == BlockType.CODE_CAPTION:
  147. bbox = nested_block["bbox"]
  148. codes_caption.append(bbox)
  149. elif block["type"] == BlockType.TITLE:
  150. titles.append(bbox)
  151. elif block["type"] in [BlockType.TEXT, BlockType.REF_TEXT]:
  152. texts.append(bbox)
  153. elif block["type"] == BlockType.INTERLINE_EQUATION:
  154. interequations.append(bbox)
  155. elif block["type"] == BlockType.LIST:
  156. lists.append(bbox)
  157. if "blocks" in block:
  158. for sub_block in block["blocks"]:
  159. list_items.append(sub_block["bbox"])
  160. elif block["type"] == BlockType.INDEX:
  161. indices.append(bbox)
  162. tables_body_list.append(tables_body)
  163. tables_caption_list.append(tables_caption)
  164. tables_footnote_list.append(tables_footnote)
  165. imgs_body_list.append(imgs_body)
  166. imgs_caption_list.append(imgs_caption)
  167. imgs_footnote_list.append(imgs_footnote)
  168. titles_list.append(titles)
  169. texts_list.append(texts)
  170. interequations_list.append(interequations)
  171. lists_list.append(lists)
  172. list_items_list.append(list_items)
  173. indexs_list.append(indices)
  174. codes_body_list.append(codes_body)
  175. codes_caption_list.append(codes_caption)
  176. layout_bbox_list = []
  177. table_type_order = {"table_caption": 1, "table_body": 2, "table_footnote": 3}
  178. for page in pdf_info:
  179. page_block_list = []
  180. for block in page["para_blocks"]:
  181. if block["type"] in [
  182. BlockType.TEXT,
  183. BlockType.TITLE,
  184. BlockType.INTERLINE_EQUATION,
  185. BlockType.LIST,
  186. BlockType.INDEX,
  187. ]:
  188. bbox = block["bbox"]
  189. page_block_list.append(bbox)
  190. elif block["type"] in [BlockType.IMAGE]:
  191. for sub_block in block["blocks"]:
  192. bbox = sub_block["bbox"]
  193. page_block_list.append(bbox)
  194. elif block["type"] in [BlockType.TABLE]:
  195. sorted_blocks = sorted(block["blocks"], key=lambda x: table_type_order[x["type"]])
  196. for sub_block in sorted_blocks:
  197. if sub_block.get(SplitFlag.CROSS_PAGE, False):
  198. continue
  199. bbox = sub_block["bbox"]
  200. page_block_list.append(bbox)
  201. elif block["type"] in [BlockType.CODE]:
  202. for sub_block in block["blocks"]:
  203. bbox = sub_block["bbox"]
  204. page_block_list.append(bbox)
  205. layout_bbox_list.append(page_block_list)
  206. pdf_bytes_io = BytesIO(pdf_bytes)
  207. pdf_docs = PdfReader(pdf_bytes_io)
  208. output_pdf = PdfWriter()
  209. for i, page in enumerate(pdf_docs.pages):
  210. # 获取原始页面尺寸
  211. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  212. custom_page_size = (page_width, page_height)
  213. packet = BytesIO()
  214. # 使用原始PDF的尺寸创建canvas
  215. c = canvas.Canvas(packet, pagesize=custom_page_size)
  216. c = draw_bbox_without_number(i, codes_body_list, page, c, [102, 0, 204], True)
  217. c = draw_bbox_without_number(i, codes_caption_list, page, c, [204, 153, 255], True)
  218. c = draw_bbox_without_number(i, dropped_bbox_list, page, c, [158, 158, 158], True)
  219. c = draw_bbox_without_number(i, tables_body_list, page, c, [204, 204, 0], True)
  220. c = draw_bbox_without_number(i, tables_caption_list, page, c, [255, 255, 102], True)
  221. c = draw_bbox_without_number(i, tables_footnote_list, page, c, [229, 255, 204], True)
  222. c = draw_bbox_without_number(i, imgs_body_list, page, c, [153, 255, 51], True)
  223. c = draw_bbox_without_number(i, imgs_caption_list, page, c, [102, 178, 255], True)
  224. c = draw_bbox_without_number(i, imgs_footnote_list, page, c, [255, 178, 102], True)
  225. c = draw_bbox_without_number(i, titles_list, page, c, [102, 102, 255], True)
  226. c = draw_bbox_without_number(i, texts_list, page, c, [153, 0, 76], True)
  227. c = draw_bbox_without_number(i, interequations_list, page, c, [0, 255, 0], True)
  228. c = draw_bbox_without_number(i, lists_list, page, c, [40, 169, 92], True)
  229. c = draw_bbox_without_number(i, list_items_list, page, c, [40, 169, 92], False)
  230. c = draw_bbox_without_number(i, indexs_list, page, c, [40, 169, 92], True)
  231. c = draw_bbox_with_number(i, layout_bbox_list, page, c, [255, 0, 0], False, draw_bbox=False)
  232. c.save()
  233. packet.seek(0)
  234. overlay_pdf = PdfReader(packet)
  235. # 添加检查确保overlay_pdf.pages不为空
  236. if len(overlay_pdf.pages) > 0:
  237. new_page = PageObject(pdf=None)
  238. new_page.update(page)
  239. page = new_page
  240. page.merge_page(overlay_pdf.pages[0])
  241. else:
  242. # 记录日志并继续处理下一个页面
  243. # logger.warning(f"layout.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  244. pass
  245. output_pdf.add_page(page)
  246. # 保存结果
  247. with open(f"{out_path}/{filename}", "wb") as f:
  248. output_pdf.write(f)
  249. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  250. text_list = []
  251. inline_equation_list = []
  252. interline_equation_list = []
  253. image_list = []
  254. table_list = []
  255. dropped_list = []
  256. def get_span_info(span):
  257. if span['type'] == ContentType.TEXT:
  258. page_text_list.append(span['bbox'])
  259. elif span['type'] == ContentType.INLINE_EQUATION:
  260. page_inline_equation_list.append(span['bbox'])
  261. elif span['type'] == ContentType.INTERLINE_EQUATION:
  262. page_interline_equation_list.append(span['bbox'])
  263. elif span['type'] == ContentType.IMAGE:
  264. page_image_list.append(span['bbox'])
  265. elif span['type'] == ContentType.TABLE:
  266. page_table_list.append(span['bbox'])
  267. for page in pdf_info:
  268. page_text_list = []
  269. page_inline_equation_list = []
  270. page_interline_equation_list = []
  271. page_image_list = []
  272. page_table_list = []
  273. page_dropped_list = []
  274. # 构造dropped_list
  275. for block in page['discarded_blocks']:
  276. if block['type'] == BlockType.DISCARDED:
  277. for line in block['lines']:
  278. for span in line['spans']:
  279. page_dropped_list.append(span['bbox'])
  280. dropped_list.append(page_dropped_list)
  281. # 构造其余useful_list
  282. # for block in page['para_blocks']: # span直接用分段合并前的结果就可以
  283. for block in page['preproc_blocks']:
  284. if block['type'] in [
  285. BlockType.TEXT,
  286. BlockType.TITLE,
  287. BlockType.INTERLINE_EQUATION,
  288. BlockType.LIST,
  289. BlockType.INDEX,
  290. ]:
  291. for line in block['lines']:
  292. for span in line['spans']:
  293. get_span_info(span)
  294. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  295. for sub_block in block['blocks']:
  296. for line in sub_block['lines']:
  297. for span in line['spans']:
  298. get_span_info(span)
  299. text_list.append(page_text_list)
  300. inline_equation_list.append(page_inline_equation_list)
  301. interline_equation_list.append(page_interline_equation_list)
  302. image_list.append(page_image_list)
  303. table_list.append(page_table_list)
  304. pdf_bytes_io = BytesIO(pdf_bytes)
  305. pdf_docs = PdfReader(pdf_bytes_io)
  306. output_pdf = PdfWriter()
  307. for i, page in enumerate(pdf_docs.pages):
  308. # 获取原始页面尺寸
  309. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  310. custom_page_size = (page_width, page_height)
  311. packet = BytesIO()
  312. # 使用原始PDF的尺寸创建canvas
  313. c = canvas.Canvas(packet, pagesize=custom_page_size)
  314. # 获取当前页面的数据
  315. draw_bbox_without_number(i, text_list, page, c,[255, 0, 0], False)
  316. draw_bbox_without_number(i, inline_equation_list, page, c, [0, 255, 0], False)
  317. draw_bbox_without_number(i, interline_equation_list, page, c, [0, 0, 255], False)
  318. draw_bbox_without_number(i, image_list, page, c, [255, 204, 0], False)
  319. draw_bbox_without_number(i, table_list, page, c, [204, 0, 255], False)
  320. draw_bbox_without_number(i, dropped_list, page, c, [158, 158, 158], False)
  321. c.save()
  322. packet.seek(0)
  323. overlay_pdf = PdfReader(packet)
  324. # 添加检查确保overlay_pdf.pages不为空
  325. if len(overlay_pdf.pages) > 0:
  326. new_page = PageObject(pdf=None)
  327. new_page.update(page)
  328. page = new_page
  329. page.merge_page(overlay_pdf.pages[0])
  330. else:
  331. # 记录日志并继续处理下一个页面
  332. # logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  333. pass
  334. output_pdf.add_page(page)
  335. # Save the PDF
  336. with open(f"{out_path}/{filename}", "wb") as f:
  337. output_pdf.write(f)
  338. def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  339. layout_bbox_list = []
  340. for page in pdf_info:
  341. page_line_list = []
  342. for block in page['preproc_blocks']:
  343. if block['type'] in [BlockType.TEXT]:
  344. for line in block['lines']:
  345. bbox = line['bbox']
  346. index = line['index']
  347. page_line_list.append({'index': index, 'bbox': bbox})
  348. elif block['type'] in [BlockType.TITLE, BlockType.INTERLINE_EQUATION]:
  349. if 'virtual_lines' in block:
  350. if len(block['virtual_lines']) > 0 and block['virtual_lines'][0].get('index', None) is not None:
  351. for line in block['virtual_lines']:
  352. bbox = line['bbox']
  353. index = line['index']
  354. page_line_list.append({'index': index, 'bbox': bbox})
  355. else:
  356. for line in block['lines']:
  357. bbox = line['bbox']
  358. index = line['index']
  359. page_line_list.append({'index': index, 'bbox': bbox})
  360. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  361. for sub_block in block['blocks']:
  362. if sub_block['type'] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY]:
  363. if len(sub_block['virtual_lines']) > 0 and sub_block['virtual_lines'][0].get('index', None) is not None:
  364. for line in sub_block['virtual_lines']:
  365. bbox = line['bbox']
  366. index = line['index']
  367. page_line_list.append({'index': index, 'bbox': bbox})
  368. else:
  369. for line in sub_block['lines']:
  370. bbox = line['bbox']
  371. index = line['index']
  372. page_line_list.append({'index': index, 'bbox': bbox})
  373. elif sub_block['type'] in [BlockType.IMAGE_CAPTION, BlockType.TABLE_CAPTION, BlockType.IMAGE_FOOTNOTE, BlockType.TABLE_FOOTNOTE]:
  374. for line in sub_block['lines']:
  375. bbox = line['bbox']
  376. index = line['index']
  377. page_line_list.append({'index': index, 'bbox': bbox})
  378. sorted_bboxes = sorted(page_line_list, key=lambda x: x['index'])
  379. layout_bbox_list.append(sorted_bbox['bbox'] for sorted_bbox in sorted_bboxes)
  380. pdf_bytes_io = BytesIO(pdf_bytes)
  381. pdf_docs = PdfReader(pdf_bytes_io)
  382. output_pdf = PdfWriter()
  383. for i, page in enumerate(pdf_docs.pages):
  384. # 获取原始页面尺寸
  385. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  386. custom_page_size = (page_width, page_height)
  387. packet = BytesIO()
  388. # 使用原始PDF的尺寸创建canvas
  389. c = canvas.Canvas(packet, pagesize=custom_page_size)
  390. # 获取当前页面的数据
  391. draw_bbox_with_number(i, layout_bbox_list, page, c, [255, 0, 0], False)
  392. c.save()
  393. packet.seek(0)
  394. overlay_pdf = PdfReader(packet)
  395. # 添加检查确保overlay_pdf.pages不为空
  396. if len(overlay_pdf.pages) > 0:
  397. new_page = PageObject(pdf=None)
  398. new_page.update(page)
  399. page = new_page
  400. page.merge_page(overlay_pdf.pages[0])
  401. else:
  402. # 记录日志并继续处理下一个页面
  403. # logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  404. pass
  405. output_pdf.add_page(page)
  406. # Save the PDF
  407. with open(f"{out_path}/{filename}", "wb") as f:
  408. output_pdf.write(f)
  409. if __name__ == "__main__":
  410. # 读取PDF文件
  411. pdf_path = "examples/demo1.pdf"
  412. with open(pdf_path, "rb") as f:
  413. pdf_bytes = f.read()
  414. # 从json文件读取pdf_info
  415. json_path = "examples/demo1_1746005777.0863056_middle.json"
  416. with open(json_path, "r", encoding="utf-8") as f:
  417. pdf_ann = json.load(f)
  418. pdf_info = pdf_ann["pdf_info"]
  419. # 调用可视化函数,输出到examples目录
  420. draw_layout_bbox(pdf_info, pdf_bytes, "examples", "output_with_layout.pdf")