draw_bbox.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. rotation = int(rotation_obj) % 360 # cast rotation to int to handle IndirectObject
  21. if rotation in [90, 270]:
  22. # PDF is rotated 90 degrees or 270 degrees, and the width and height need to be swapped
  23. actual_width, actual_height = actual_height, actual_width
  24. x0, y0, x1, y1 = bbox
  25. rect_w = abs(x1 - x0)
  26. rect_h = abs(y1 - y0)
  27. if rotation == 270:
  28. rect_w, rect_h = rect_h, rect_w
  29. x0 = actual_height - y1
  30. y0 = actual_width - x1
  31. elif rotation == 180:
  32. x0 = page_width - x1
  33. # y0 stays the same
  34. elif rotation == 90:
  35. rect_w, rect_h = rect_h, rect_w
  36. x0, y0 = y0, x0
  37. else:
  38. # rotation == 0
  39. y0 = page_height - y1
  40. rect = [x0, y0, rect_w, rect_h]
  41. return rect
  42. def draw_bbox_without_number(i, bbox_list, page, c, rgb_config, fill_config):
  43. new_rgb = [float(color) / 255 for color in rgb_config]
  44. page_data = bbox_list[i]
  45. for bbox in page_data:
  46. rect = cal_canvas_rect(page, bbox) # Define the rectangle
  47. if fill_config: # filled rectangle
  48. c.setFillColorRGB(new_rgb[0], new_rgb[1], new_rgb[2], 0.3)
  49. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=0, fill=1)
  50. else: # bounding box
  51. c.setStrokeColorRGB(new_rgb[0], new_rgb[1], new_rgb[2])
  52. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=1, fill=0)
  53. return c
  54. def draw_bbox_with_number(i, bbox_list, page, c, rgb_config, fill_config, draw_bbox=True):
  55. new_rgb = [float(color) / 255 for color in rgb_config]
  56. page_data = bbox_list[i]
  57. # 强制转换为 float
  58. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  59. for j, bbox in enumerate(page_data):
  60. # 确保bbox的每个元素都是float
  61. rect = cal_canvas_rect(page, bbox) # Define the rectangle
  62. if draw_bbox:
  63. if fill_config:
  64. c.setFillColorRGB(*new_rgb, 0.3)
  65. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=0, fill=1)
  66. else:
  67. c.setStrokeColorRGB(*new_rgb)
  68. c.rect(rect[0], rect[1], rect[2], rect[3], stroke=1, fill=0)
  69. c.setFillColorRGB(*new_rgb, 1.0)
  70. c.setFontSize(size=10)
  71. c.saveState()
  72. rotation_obj = page.get("/Rotate", 0)
  73. rotation = int(rotation_obj) % 360 # cast rotation to int to handle IndirectObject
  74. if rotation == 0:
  75. c.translate(rect[0] + rect[2] + 2, rect[1] + rect[3] - 10)
  76. elif rotation == 90:
  77. c.translate(rect[0] + 10, rect[1] + rect[3] + 2)
  78. elif rotation == 180:
  79. c.translate(rect[0] - 2, rect[1] + 10)
  80. elif rotation == 270:
  81. c.translate(rect[0] + rect[2] - 10, rect[1] - 2)
  82. c.rotate(rotation)
  83. c.drawString(0, 0, str(j + 1))
  84. c.restoreState()
  85. return c
  86. def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
  87. dropped_bbox_list = []
  88. tables_list, tables_body_list = [], []
  89. tables_caption_list, tables_footnote_list = [], []
  90. imgs_list, imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], [], []
  91. titles_list = []
  92. texts_list = []
  93. interequations_list = []
  94. lists_list = []
  95. indexs_list = []
  96. for page in pdf_info:
  97. page_dropped_list = []
  98. tables, tables_body, tables_caption, tables_footnote = [], [], [], []
  99. imgs, imgs_body, imgs_caption, imgs_footnote = [], [], [], []
  100. titles = []
  101. texts = []
  102. interequations = []
  103. lists = []
  104. indices = []
  105. for dropped_bbox in page['discarded_blocks']:
  106. page_dropped_list.append(dropped_bbox['bbox'])
  107. dropped_bbox_list.append(page_dropped_list)
  108. for block in page["para_blocks"]:
  109. bbox = block["bbox"]
  110. if block["type"] == BlockType.TABLE:
  111. tables.append(bbox)
  112. for nested_block in block["blocks"]:
  113. bbox = nested_block["bbox"]
  114. if nested_block["type"] == BlockType.TABLE_BODY:
  115. tables_body.append(bbox)
  116. elif nested_block["type"] == BlockType.TABLE_CAPTION:
  117. tables_caption.append(bbox)
  118. elif nested_block["type"] == BlockType.TABLE_FOOTNOTE:
  119. tables_footnote.append(bbox)
  120. elif block["type"] == BlockType.IMAGE:
  121. imgs.append(bbox)
  122. for nested_block in block["blocks"]:
  123. bbox = nested_block["bbox"]
  124. if nested_block["type"] == BlockType.IMAGE_BODY:
  125. imgs_body.append(bbox)
  126. elif nested_block["type"] == BlockType.IMAGE_CAPTION:
  127. imgs_caption.append(bbox)
  128. elif nested_block["type"] == BlockType.IMAGE_FOOTNOTE:
  129. imgs_footnote.append(bbox)
  130. elif block["type"] == BlockType.TITLE:
  131. titles.append(bbox)
  132. elif block["type"] == BlockType.TEXT:
  133. texts.append(bbox)
  134. elif block["type"] == BlockType.INTERLINE_EQUATION:
  135. interequations.append(bbox)
  136. elif block["type"] == BlockType.LIST:
  137. lists.append(bbox)
  138. elif block["type"] == BlockType.INDEX:
  139. indices.append(bbox)
  140. tables_list.append(tables)
  141. tables_body_list.append(tables_body)
  142. tables_caption_list.append(tables_caption)
  143. tables_footnote_list.append(tables_footnote)
  144. imgs_list.append(imgs)
  145. imgs_body_list.append(imgs_body)
  146. imgs_caption_list.append(imgs_caption)
  147. imgs_footnote_list.append(imgs_footnote)
  148. titles_list.append(titles)
  149. texts_list.append(texts)
  150. interequations_list.append(interequations)
  151. lists_list.append(lists)
  152. indexs_list.append(indices)
  153. layout_bbox_list = []
  154. table_type_order = {"table_caption": 1, "table_body": 2, "table_footnote": 3}
  155. for page in pdf_info:
  156. page_block_list = []
  157. for block in page["para_blocks"]:
  158. if block["type"] in [
  159. BlockType.TEXT,
  160. BlockType.TITLE,
  161. BlockType.INTERLINE_EQUATION,
  162. BlockType.LIST,
  163. BlockType.INDEX,
  164. ]:
  165. bbox = block["bbox"]
  166. page_block_list.append(bbox)
  167. elif block["type"] in [BlockType.IMAGE]:
  168. for sub_block in block["blocks"]:
  169. bbox = sub_block["bbox"]
  170. page_block_list.append(bbox)
  171. elif block["type"] in [BlockType.TABLE]:
  172. sorted_blocks = sorted(block["blocks"], key=lambda x: table_type_order[x["type"]])
  173. for sub_block in sorted_blocks:
  174. bbox = sub_block["bbox"]
  175. page_block_list.append(bbox)
  176. layout_bbox_list.append(page_block_list)
  177. pdf_bytes_io = BytesIO(pdf_bytes)
  178. pdf_docs = PdfReader(pdf_bytes_io)
  179. output_pdf = PdfWriter()
  180. for i, page in enumerate(pdf_docs.pages):
  181. # 获取原始页面尺寸
  182. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  183. custom_page_size = (page_width, page_height)
  184. packet = BytesIO()
  185. # 使用原始PDF的尺寸创建canvas
  186. c = canvas.Canvas(packet, pagesize=custom_page_size)
  187. c = draw_bbox_without_number(i, dropped_bbox_list, page, c, [158, 158, 158], True)
  188. c = draw_bbox_without_number(i, tables_body_list, page, c, [204, 204, 0], True)
  189. c = draw_bbox_without_number(i, tables_caption_list, page, c, [255, 255, 102], True)
  190. c = draw_bbox_without_number(i, tables_footnote_list, page, c, [229, 255, 204], True)
  191. c = draw_bbox_without_number(i, imgs_body_list, page, c, [153, 255, 51], True)
  192. c = draw_bbox_without_number(i, imgs_caption_list, page, c, [102, 178, 255], True)
  193. c = draw_bbox_without_number(i, imgs_footnote_list, page, c, [255, 178, 102], True)
  194. c = draw_bbox_without_number(i, titles_list, page, c, [102, 102, 255], True)
  195. c = draw_bbox_without_number(i, texts_list, page, c, [153, 0, 76], True)
  196. c = draw_bbox_without_number(i, interequations_list, page, c, [0, 255, 0], True)
  197. c = draw_bbox_without_number(i, lists_list, page, c, [40, 169, 92], True)
  198. c = draw_bbox_without_number(i, indexs_list, page, c, [40, 169, 92], True)
  199. c = draw_bbox_with_number(i, layout_bbox_list, page, c, [255, 0, 0], False, draw_bbox=False)
  200. c.save()
  201. packet.seek(0)
  202. overlay_pdf = PdfReader(packet)
  203. # 添加检查确保overlay_pdf.pages不为空
  204. if len(overlay_pdf.pages) > 0:
  205. new_page = PageObject(pdf=None)
  206. new_page.update(page)
  207. page = new_page
  208. page.merge_page(overlay_pdf.pages[0])
  209. else:
  210. # 记录日志并继续处理下一个页面
  211. # logger.warning(f"layout.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  212. pass
  213. output_pdf.add_page(page)
  214. # 保存结果
  215. with open(f"{out_path}/{filename}", "wb") as f:
  216. output_pdf.write(f)
  217. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  218. text_list = []
  219. inline_equation_list = []
  220. interline_equation_list = []
  221. image_list = []
  222. table_list = []
  223. dropped_list = []
  224. next_page_text_list = []
  225. next_page_inline_equation_list = []
  226. def get_span_info(span):
  227. if span['type'] == ContentType.TEXT:
  228. if span.get('cross_page', False):
  229. next_page_text_list.append(span['bbox'])
  230. else:
  231. page_text_list.append(span['bbox'])
  232. elif span['type'] == ContentType.INLINE_EQUATION:
  233. if span.get('cross_page', False):
  234. next_page_inline_equation_list.append(span['bbox'])
  235. else:
  236. page_inline_equation_list.append(span['bbox'])
  237. elif span['type'] == ContentType.INTERLINE_EQUATION:
  238. page_interline_equation_list.append(span['bbox'])
  239. elif span['type'] == ContentType.IMAGE:
  240. page_image_list.append(span['bbox'])
  241. elif span['type'] == ContentType.TABLE:
  242. page_table_list.append(span['bbox'])
  243. for page in pdf_info:
  244. page_text_list = []
  245. page_inline_equation_list = []
  246. page_interline_equation_list = []
  247. page_image_list = []
  248. page_table_list = []
  249. page_dropped_list = []
  250. # 将跨页的span放到移动到下一页的列表中
  251. if len(next_page_text_list) > 0:
  252. page_text_list.extend(next_page_text_list)
  253. next_page_text_list.clear()
  254. if len(next_page_inline_equation_list) > 0:
  255. page_inline_equation_list.extend(next_page_inline_equation_list)
  256. next_page_inline_equation_list.clear()
  257. # 构造dropped_list
  258. for block in page['discarded_blocks']:
  259. if block['type'] == BlockType.DISCARDED:
  260. for line in block['lines']:
  261. for span in line['spans']:
  262. page_dropped_list.append(span['bbox'])
  263. dropped_list.append(page_dropped_list)
  264. # 构造其余useful_list
  265. # for block in page['para_blocks']: # span直接用分段合并前的结果就可以
  266. for block in page['preproc_blocks']:
  267. if block['type'] in [
  268. BlockType.TEXT,
  269. BlockType.TITLE,
  270. BlockType.INTERLINE_EQUATION,
  271. BlockType.LIST,
  272. BlockType.INDEX,
  273. ]:
  274. for line in block['lines']:
  275. for span in line['spans']:
  276. get_span_info(span)
  277. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  278. for sub_block in block['blocks']:
  279. for line in sub_block['lines']:
  280. for span in line['spans']:
  281. get_span_info(span)
  282. text_list.append(page_text_list)
  283. inline_equation_list.append(page_inline_equation_list)
  284. interline_equation_list.append(page_interline_equation_list)
  285. image_list.append(page_image_list)
  286. table_list.append(page_table_list)
  287. pdf_bytes_io = BytesIO(pdf_bytes)
  288. pdf_docs = PdfReader(pdf_bytes_io)
  289. output_pdf = PdfWriter()
  290. for i, page in enumerate(pdf_docs.pages):
  291. # 获取原始页面尺寸
  292. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  293. custom_page_size = (page_width, page_height)
  294. packet = BytesIO()
  295. # 使用原始PDF的尺寸创建canvas
  296. c = canvas.Canvas(packet, pagesize=custom_page_size)
  297. # 获取当前页面的数据
  298. draw_bbox_without_number(i, text_list, page, c,[255, 0, 0], False)
  299. draw_bbox_without_number(i, inline_equation_list, page, c, [0, 255, 0], False)
  300. draw_bbox_without_number(i, interline_equation_list, page, c, [0, 0, 255], False)
  301. draw_bbox_without_number(i, image_list, page, c, [255, 204, 0], False)
  302. draw_bbox_without_number(i, table_list, page, c, [204, 0, 255], False)
  303. draw_bbox_without_number(i, dropped_list, page, c, [158, 158, 158], False)
  304. c.save()
  305. packet.seek(0)
  306. overlay_pdf = PdfReader(packet)
  307. # 添加检查确保overlay_pdf.pages不为空
  308. if len(overlay_pdf.pages) > 0:
  309. new_page = PageObject(pdf=None)
  310. new_page.update(page)
  311. page = new_page
  312. page.merge_page(overlay_pdf.pages[0])
  313. else:
  314. # 记录日志并继续处理下一个页面
  315. # logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  316. pass
  317. output_pdf.add_page(page)
  318. # Save the PDF
  319. with open(f"{out_path}/{filename}", "wb") as f:
  320. output_pdf.write(f)
  321. if __name__ == "__main__":
  322. # 读取PDF文件
  323. pdf_path = "examples/demo1.pdf"
  324. with open(pdf_path, "rb") as f:
  325. pdf_bytes = f.read()
  326. # 从json文件读取pdf_info
  327. json_path = "examples/demo1_1746005777.0863056_middle.json"
  328. with open(json_path, "r", encoding="utf-8") as f:
  329. pdf_ann = json.load(f)
  330. pdf_info = pdf_ann["pdf_info"]
  331. # 调用可视化函数,输出到examples目录
  332. draw_layout_bbox(pdf_info, pdf_bytes, "examples", "output_with_layout.pdf")