draw_bbox.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import time
  2. import torch
  3. from magic_pdf.libs.commons import fitz # PyMuPDF
  4. from magic_pdf.libs.Constants import CROSS_PAGE
  5. from magic_pdf.libs.ocr_content_type import BlockType, CategoryId, ContentType
  6. from magic_pdf.model.magic_model import MagicModel
  7. def draw_bbox_without_number(i, bbox_list, page, rgb_config, fill_config):
  8. new_rgb = []
  9. for item in rgb_config:
  10. item = float(item) / 255
  11. new_rgb.append(item)
  12. page_data = bbox_list[i]
  13. for bbox in page_data:
  14. x0, y0, x1, y1 = bbox
  15. rect_coords = fitz.Rect(x0, y0, x1, y1) # Define the rectangle
  16. if fill_config:
  17. page.draw_rect(
  18. rect_coords,
  19. color=None,
  20. fill=new_rgb,
  21. fill_opacity=0.3,
  22. width=0.5,
  23. overlay=True,
  24. ) # Draw the rectangle
  25. else:
  26. page.draw_rect(
  27. rect_coords,
  28. color=new_rgb,
  29. fill=None,
  30. fill_opacity=1,
  31. width=0.5,
  32. overlay=True,
  33. ) # Draw the rectangle
  34. def draw_bbox_with_number(i, bbox_list, page, rgb_config, fill_config, draw_bbox=True):
  35. new_rgb = []
  36. for item in rgb_config:
  37. item = float(item) / 255
  38. new_rgb.append(item)
  39. page_data = bbox_list[i]
  40. for j, bbox in enumerate(page_data):
  41. x0, y0, x1, y1 = bbox
  42. rect_coords = fitz.Rect(x0, y0, x1, y1) # Define the rectangle
  43. if draw_bbox:
  44. if fill_config:
  45. page.draw_rect(
  46. rect_coords,
  47. color=None,
  48. fill=new_rgb,
  49. fill_opacity=0.3,
  50. width=0.5,
  51. overlay=True,
  52. ) # Draw the rectangle
  53. else:
  54. page.draw_rect(
  55. rect_coords,
  56. color=new_rgb,
  57. fill=None,
  58. fill_opacity=1,
  59. width=0.5,
  60. overlay=True,
  61. ) # Draw the rectangle
  62. page.insert_text(
  63. (x1+2, y0 + 10), str(j + 1), fontsize=10, color=new_rgb
  64. ) # Insert the index in the top left corner of the rectangle
  65. def draw_layout_bbox(pdf_info, pdf_bytes, out_path, filename):
  66. # layout_bbox_list = []
  67. dropped_bbox_list = []
  68. tables_list, tables_body_list = [], []
  69. tables_caption_list, tables_footnote_list = [], []
  70. imgs_list, imgs_body_list, imgs_caption_list = [], [], []
  71. imgs_footnote_list = []
  72. titles_list = []
  73. texts_list = []
  74. interequations_list = []
  75. for page in pdf_info:
  76. # page_layout_list = []
  77. page_dropped_list = []
  78. tables, tables_body, tables_caption, tables_footnote = [], [], [], []
  79. imgs, imgs_body, imgs_caption, imgs_footnote = [], [], [], []
  80. titles = []
  81. texts = []
  82. interequations = []
  83. # for layout in page['layout_bboxes']:
  84. # page_layout_list.append(layout['layout_bbox'])
  85. # layout_bbox_list.append(page_layout_list)
  86. for dropped_bbox in page['discarded_blocks']:
  87. page_dropped_list.append(dropped_bbox['bbox'])
  88. dropped_bbox_list.append(page_dropped_list)
  89. for block in page['para_blocks']:
  90. bbox = block['bbox']
  91. if block['type'] == BlockType.Table:
  92. tables.append(bbox)
  93. for nested_block in block['blocks']:
  94. bbox = nested_block['bbox']
  95. if nested_block['type'] == BlockType.TableBody:
  96. tables_body.append(bbox)
  97. elif nested_block['type'] == BlockType.TableCaption:
  98. tables_caption.append(bbox)
  99. elif nested_block['type'] == BlockType.TableFootnote:
  100. tables_footnote.append(bbox)
  101. elif block['type'] == BlockType.Image:
  102. imgs.append(bbox)
  103. for nested_block in block['blocks']:
  104. bbox = nested_block['bbox']
  105. if nested_block['type'] == BlockType.ImageBody:
  106. imgs_body.append(bbox)
  107. elif nested_block['type'] == BlockType.ImageCaption:
  108. imgs_caption.append(bbox)
  109. elif nested_block['type'] == BlockType.ImageFootnote:
  110. imgs_footnote.append(bbox)
  111. elif block['type'] == BlockType.Title:
  112. titles.append(bbox)
  113. elif block['type'] == BlockType.Text:
  114. texts.append(bbox)
  115. elif block['type'] == BlockType.InterlineEquation:
  116. interequations.append(bbox)
  117. tables_list.append(tables)
  118. tables_body_list.append(tables_body)
  119. tables_caption_list.append(tables_caption)
  120. tables_footnote_list.append(tables_footnote)
  121. imgs_list.append(imgs)
  122. imgs_body_list.append(imgs_body)
  123. imgs_caption_list.append(imgs_caption)
  124. imgs_footnote_list.append(imgs_footnote)
  125. titles_list.append(titles)
  126. texts_list.append(texts)
  127. interequations_list.append(interequations)
  128. layout_bbox_list = []
  129. for page in pdf_info:
  130. page_block_list = []
  131. for block in page['para_blocks']:
  132. bbox = block['bbox']
  133. page_block_list.append(bbox)
  134. layout_bbox_list.append(page_block_list)
  135. pdf_docs = fitz.open('pdf', pdf_bytes)
  136. for i, page in enumerate(pdf_docs):
  137. # draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
  138. draw_bbox_without_number(i, dropped_bbox_list, page, [158, 158, 158],
  139. True)
  140. draw_bbox_without_number(i, tables_list, page, [153, 153, 0],
  141. True) # color !
  142. draw_bbox_without_number(i, tables_body_list, page, [204, 204, 0],
  143. True)
  144. draw_bbox_without_number(i, tables_caption_list, page, [255, 255, 102],
  145. True)
  146. draw_bbox_without_number(i, tables_footnote_list, page,
  147. [229, 255, 204], True)
  148. draw_bbox_without_number(i, imgs_list, page, [51, 102, 0], True)
  149. draw_bbox_without_number(i, imgs_body_list, page, [153, 255, 51], True)
  150. draw_bbox_without_number(i, imgs_caption_list, page, [102, 178, 255],
  151. True)
  152. draw_bbox_without_number(i, imgs_footnote_list, page, [255, 178, 102],
  153. True),
  154. draw_bbox_without_number(i, titles_list, page, [102, 102, 255], True)
  155. draw_bbox_without_number(i, texts_list, page, [153, 0, 76], True)
  156. draw_bbox_without_number(i, interequations_list, page, [0, 255, 0],
  157. True)
  158. for i, page in enumerate(pdf_docs):
  159. draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False, draw_bbox=False)
  160. # Save the PDF
  161. pdf_docs.save(f'{out_path}/{filename}_layout.pdf')
  162. def draw_span_bbox(pdf_info, pdf_bytes, out_path, filename):
  163. text_list = []
  164. inline_equation_list = []
  165. interline_equation_list = []
  166. image_list = []
  167. table_list = []
  168. dropped_list = []
  169. next_page_text_list = []
  170. next_page_inline_equation_list = []
  171. def get_span_info(span):
  172. if span['type'] == ContentType.Text:
  173. if span.get(CROSS_PAGE, False):
  174. next_page_text_list.append(span['bbox'])
  175. else:
  176. page_text_list.append(span['bbox'])
  177. elif span['type'] == ContentType.InlineEquation:
  178. if span.get(CROSS_PAGE, False):
  179. next_page_inline_equation_list.append(span['bbox'])
  180. else:
  181. page_inline_equation_list.append(span['bbox'])
  182. elif span['type'] == ContentType.InterlineEquation:
  183. page_interline_equation_list.append(span['bbox'])
  184. elif span['type'] == ContentType.Image:
  185. page_image_list.append(span['bbox'])
  186. elif span['type'] == ContentType.Table:
  187. page_table_list.append(span['bbox'])
  188. for page in pdf_info:
  189. page_text_list = []
  190. page_inline_equation_list = []
  191. page_interline_equation_list = []
  192. page_image_list = []
  193. page_table_list = []
  194. page_dropped_list = []
  195. # 将跨页的span放到移动到下一页的列表中
  196. if len(next_page_text_list) > 0:
  197. page_text_list.extend(next_page_text_list)
  198. next_page_text_list.clear()
  199. if len(next_page_inline_equation_list) > 0:
  200. page_inline_equation_list.extend(next_page_inline_equation_list)
  201. next_page_inline_equation_list.clear()
  202. # 构造dropped_list
  203. for block in page['discarded_blocks']:
  204. if block['type'] == BlockType.Discarded:
  205. for line in block['lines']:
  206. for span in line['spans']:
  207. page_dropped_list.append(span['bbox'])
  208. dropped_list.append(page_dropped_list)
  209. # 构造其余useful_list
  210. for block in page['para_blocks']:
  211. if block['type'] in [
  212. BlockType.Text,
  213. BlockType.Title,
  214. BlockType.InterlineEquation,
  215. ]:
  216. for line in block['lines']:
  217. for span in line['spans']:
  218. get_span_info(span)
  219. elif block['type'] in [BlockType.Image, BlockType.Table]:
  220. for sub_block in block['blocks']:
  221. for line in sub_block['lines']:
  222. for span in line['spans']:
  223. get_span_info(span)
  224. text_list.append(page_text_list)
  225. inline_equation_list.append(page_inline_equation_list)
  226. interline_equation_list.append(page_interline_equation_list)
  227. image_list.append(page_image_list)
  228. table_list.append(page_table_list)
  229. pdf_docs = fitz.open('pdf', pdf_bytes)
  230. for i, page in enumerate(pdf_docs):
  231. # 获取当前页面的数据
  232. draw_bbox_without_number(i, text_list, page, [255, 0, 0], False)
  233. draw_bbox_without_number(i, inline_equation_list, page, [0, 255, 0], False)
  234. draw_bbox_without_number(i, interline_equation_list, page, [0, 0, 255], False)
  235. draw_bbox_without_number(i, image_list, page, [255, 204, 0], False)
  236. draw_bbox_without_number(i, table_list, page, [204, 0, 255], False)
  237. draw_bbox_without_number(i, dropped_list, page, [158, 158, 158], False)
  238. # Save the PDF
  239. pdf_docs.save(f'{out_path}/{filename}_spans.pdf')
  240. def draw_model_bbox(model_list: list, pdf_bytes, out_path, filename):
  241. dropped_bbox_list = []
  242. tables_body_list, tables_caption_list, tables_footnote_list = [], [], []
  243. imgs_body_list, imgs_caption_list, imgs_footnote_list = [], [], []
  244. titles_list = []
  245. texts_list = []
  246. interequations_list = []
  247. pdf_docs = fitz.open('pdf', pdf_bytes)
  248. magic_model = MagicModel(model_list, pdf_docs)
  249. for i in range(len(model_list)):
  250. page_dropped_list = []
  251. tables_body, tables_caption, tables_footnote = [], [], []
  252. imgs_body, imgs_caption, imgs_footnote = [], [], []
  253. titles = []
  254. texts = []
  255. interequations = []
  256. page_info = magic_model.get_model_list(i)
  257. layout_dets = page_info['layout_dets']
  258. for layout_det in layout_dets:
  259. bbox = layout_det['bbox']
  260. if layout_det['category_id'] == CategoryId.Text:
  261. texts.append(bbox)
  262. elif layout_det['category_id'] == CategoryId.Title:
  263. titles.append(bbox)
  264. elif layout_det['category_id'] == CategoryId.TableBody:
  265. tables_body.append(bbox)
  266. elif layout_det['category_id'] == CategoryId.TableCaption:
  267. tables_caption.append(bbox)
  268. elif layout_det['category_id'] == CategoryId.TableFootnote:
  269. tables_footnote.append(bbox)
  270. elif layout_det['category_id'] == CategoryId.ImageBody:
  271. imgs_body.append(bbox)
  272. elif layout_det['category_id'] == CategoryId.ImageCaption:
  273. imgs_caption.append(bbox)
  274. elif layout_det[
  275. 'category_id'] == CategoryId.InterlineEquation_YOLO:
  276. interequations.append(bbox)
  277. elif layout_det['category_id'] == CategoryId.Abandon:
  278. page_dropped_list.append(bbox)
  279. elif layout_det['category_id'] == CategoryId.ImageFootnote:
  280. imgs_footnote.append(bbox)
  281. tables_body_list.append(tables_body)
  282. tables_caption_list.append(tables_caption)
  283. tables_footnote_list.append(tables_footnote)
  284. imgs_body_list.append(imgs_body)
  285. imgs_caption_list.append(imgs_caption)
  286. titles_list.append(titles)
  287. texts_list.append(texts)
  288. interequations_list.append(interequations)
  289. dropped_bbox_list.append(page_dropped_list)
  290. imgs_footnote_list.append(imgs_footnote)
  291. for i, page in enumerate(pdf_docs):
  292. draw_bbox_with_number(i, dropped_bbox_list, page, [158, 158, 158],
  293. True) # color !
  294. draw_bbox_with_number(i, tables_body_list, page, [204, 204, 0], True)
  295. draw_bbox_with_number(i, tables_caption_list, page, [255, 255, 102],
  296. True)
  297. draw_bbox_with_number(i, tables_footnote_list, page, [229, 255, 204],
  298. True)
  299. draw_bbox_with_number(i, imgs_body_list, page, [153, 255, 51], True)
  300. draw_bbox_with_number(i, imgs_caption_list, page, [102, 178, 255],
  301. True)
  302. draw_bbox_with_number(i, imgs_footnote_list, page, [255, 178, 102],
  303. True)
  304. draw_bbox_with_number(i, titles_list, page, [102, 102, 255], True)
  305. draw_bbox_with_number(i, texts_list, page, [153, 0, 76], True)
  306. draw_bbox_with_number(i, interequations_list, page, [0, 255, 0], True)
  307. # Save the PDF
  308. pdf_docs.save(f'{out_path}/{filename}_model.pdf')
  309. def draw_line_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  310. layout_bbox_list = []
  311. from loguru import logger
  312. for page in pdf_info:
  313. page_line_list = []
  314. for block in page['preproc_blocks']:
  315. if block['type'] == 'text' or block['type'] == 'title' or block['type'] == 'interline_equation':
  316. for line in block['lines']:
  317. bbox = line['bbox']
  318. index = line['index']
  319. page_line_list.append({'index': index, 'bbox': bbox})
  320. if block['type'] == 'table' or block['type'] == 'image':
  321. bbox = block['bbox']
  322. index = block['index']
  323. page_line_list.append({'index': index, 'bbox': bbox})
  324. sorted_bboxes = sorted(page_line_list, key=lambda x: x['index'])
  325. layout_bbox_list.append(sorted_bbox['bbox'] for sorted_bbox in sorted_bboxes)
  326. pdf_docs = fitz.open('pdf', pdf_bytes)
  327. for i, page in enumerate(pdf_docs):
  328. draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
  329. pdf_docs.save(f'{out_path}/{filename}_line_sort.pdf')
  330. def draw_layout_sort_bbox(pdf_info, pdf_bytes, out_path, filename):
  331. layout_bbox_list = []
  332. for page in pdf_info:
  333. page_block_list = []
  334. for block in page['para_blocks']:
  335. bbox = block['bbox']
  336. page_block_list.append(bbox)
  337. layout_bbox_list.append(page_block_list)
  338. pdf_docs = fitz.open('pdf', pdf_bytes)
  339. for i, page in enumerate(pdf_docs):
  340. draw_bbox_with_number(i, layout_bbox_list, page, [255, 0, 0], False)
  341. pdf_docs.save(f'{out_path}/{filename}_layout_sort.pdf')