draw_bbox.py 13 KB

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