draw_bbox.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. output_pdf.add_page(page)
  170. # 保存结果
  171. with open(f"{out_path}/{filename}", "wb") as f:
  172. output_pdf.write(f)
  173. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  174. text_list = []
  175. inline_equation_list = []
  176. interline_equation_list = []
  177. image_list = []
  178. table_list = []
  179. dropped_list = []
  180. next_page_text_list = []
  181. next_page_inline_equation_list = []
  182. def get_span_info(span):
  183. if span['type'] == ContentType.TEXT:
  184. if span.get('cross_page', False):
  185. next_page_text_list.append(span['bbox'])
  186. else:
  187. page_text_list.append(span['bbox'])
  188. elif span['type'] == ContentType.INLINE_EQUATION:
  189. if span.get('cross_page', False):
  190. next_page_inline_equation_list.append(span['bbox'])
  191. else:
  192. page_inline_equation_list.append(span['bbox'])
  193. elif span['type'] == ContentType.INTERLINE_EQUATION:
  194. page_interline_equation_list.append(span['bbox'])
  195. elif span['type'] == ContentType.IMAGE:
  196. page_image_list.append(span['bbox'])
  197. elif span['type'] == ContentType.TABLE:
  198. page_table_list.append(span['bbox'])
  199. for page in pdf_info:
  200. page_text_list = []
  201. page_inline_equation_list = []
  202. page_interline_equation_list = []
  203. page_image_list = []
  204. page_table_list = []
  205. page_dropped_list = []
  206. # 将跨页的span放到移动到下一页的列表中
  207. if len(next_page_text_list) > 0:
  208. page_text_list.extend(next_page_text_list)
  209. next_page_text_list.clear()
  210. if len(next_page_inline_equation_list) > 0:
  211. page_inline_equation_list.extend(next_page_inline_equation_list)
  212. next_page_inline_equation_list.clear()
  213. # 构造dropped_list
  214. for block in page['discarded_blocks']:
  215. if block['type'] == BlockType.DISCARDED:
  216. for line in block['lines']:
  217. for span in line['spans']:
  218. page_dropped_list.append(span['bbox'])
  219. dropped_list.append(page_dropped_list)
  220. # 构造其余useful_list
  221. # for block in page['para_blocks']: # span直接用分段合并前的结果就可以
  222. for block in page['preproc_blocks']:
  223. if block['type'] in [
  224. BlockType.TEXT,
  225. BlockType.TITLE,
  226. BlockType.INTERLINE_EQUATION,
  227. BlockType.LIST,
  228. BlockType.INDEX,
  229. ]:
  230. for line in block['lines']:
  231. for span in line['spans']:
  232. get_span_info(span)
  233. elif block['type'] in [BlockType.IMAGE, BlockType.TABLE]:
  234. for sub_block in block['blocks']:
  235. for line in sub_block['lines']:
  236. for span in line['spans']:
  237. get_span_info(span)
  238. text_list.append(page_text_list)
  239. inline_equation_list.append(page_inline_equation_list)
  240. interline_equation_list.append(page_interline_equation_list)
  241. image_list.append(page_image_list)
  242. table_list.append(page_table_list)
  243. pdf_bytes_io = BytesIO(pdf_bytes)
  244. pdf_docs = PdfReader(pdf_bytes_io)
  245. output_pdf = PdfWriter()
  246. for i, page in enumerate(pdf_docs.pages):
  247. # 获取原始页面尺寸
  248. page_width, page_height = float(page.cropbox[2]), float(page.cropbox[3])
  249. custom_page_size = (page_width, page_height)
  250. packet = BytesIO()
  251. # 使用原始PDF的尺寸创建canvas
  252. c = canvas.Canvas(packet, pagesize=custom_page_size)
  253. # 获取当前页面的数据
  254. draw_bbox_without_number(i, text_list, page, c,[255, 0, 0], False)
  255. draw_bbox_without_number(i, inline_equation_list, page, c, [0, 255, 0], False)
  256. draw_bbox_without_number(i, interline_equation_list, page, c, [0, 0, 255], False)
  257. draw_bbox_without_number(i, image_list, page, c, [255, 204, 0], False)
  258. draw_bbox_without_number(i, table_list, page, c, [204, 0, 255], False)
  259. draw_bbox_without_number(i, dropped_list, page, c, [158, 158, 158], False)
  260. c.save()
  261. packet.seek(0)
  262. overlay_pdf = PdfReader(packet)
  263. # 添加检查确保overlay_pdf.pages不为空
  264. if len(overlay_pdf.pages) > 0:
  265. page.merge_page(overlay_pdf.pages[0])
  266. else:
  267. # 记录日志并继续处理下一个页面
  268. logger.warning(f"span.pdf: 第{i + 1}页未能生成有效的overlay PDF")
  269. output_pdf.add_page(page)
  270. # Save the PDF
  271. with open(f"{out_path}/{filename}", "wb") as f:
  272. output_pdf.write(f)
  273. if __name__ == "__main__":
  274. # 读取PDF文件
  275. pdf_path = "examples/demo1.pdf"
  276. with open(pdf_path, "rb") as f:
  277. pdf_bytes = f.read()
  278. # 从json文件读取pdf_info
  279. json_path = "examples/demo1_1746005777.0863056_middle.json"
  280. with open(json_path, "r", encoding="utf-8") as f:
  281. pdf_ann = json.load(f)
  282. pdf_info = pdf_ann["pdf_info"]
  283. # 调用可视化函数,输出到examples目录
  284. draw_layout_bbox(pdf_info, pdf_bytes, "examples", "output_with_layout.pdf")