draw_bbox.py 19 KB

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