draw_bbox.py 15 KB

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