draw_bbox.py 19 KB

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