extract_pdfs_v2.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env python3
  2. """
  3. PDF extraction v2: table-aware
  4. - Extracts tables as Markdown tables
  5. - Marks table boundaries with [TABLE_START] [TABLE_END] tags
  6. - Regular text extracted normally
  7. """
  8. import os
  9. import sys
  10. import re
  11. import fitz
  12. from pathlib import Path
  13. from config import cfg
  14. RAW_DIR = cfg.raw_dir
  15. OUT_DIR = cfg.processed_dir
  16. OUT_DIR.mkdir(exist_ok=True)
  17. pdf_files = sorted(RAW_DIR.glob('*.pdf'))
  18. total = len(pdf_files)
  19. print(f'Total: {total} PDFs')
  20. success = 0
  21. failed = 0
  22. tables_found = 0
  23. def table_to_markdown(table_data, headers=None):
  24. """Convert extracted table data to Markdown table format"""
  25. if not table_data or not table_data[0]:
  26. return ''
  27. rows = []
  28. for row in table_data:
  29. # Clean cells: replace None with empty, remove newlines
  30. cells = []
  31. for cell in row:
  32. if cell is None:
  33. cells.append('')
  34. else:
  35. cells.append(str(cell).replace('\n', ' ').strip())
  36. rows.append(cells)
  37. if not rows:
  38. return ''
  39. # Ensure all rows have same number of columns
  40. max_cols = max(len(r) for r in rows)
  41. for r in rows:
  42. while len(r) < max_cols:
  43. r.append('')
  44. # Build markdown table
  45. lines = []
  46. # Header row
  47. lines.append('| ' + ' | '.join(rows[0]) + ' |')
  48. lines.append('| ' + ' | '.join(['---'] * max_cols) + ' |')
  49. # Data rows
  50. for row in rows[1:]:
  51. lines.append('| ' + ' | '.join(row) + ' |')
  52. return '\n'.join(lines)
  53. for i, pdf_path in enumerate(pdf_files):
  54. out_path = OUT_DIR / (pdf_path.stem + '.txt')
  55. try:
  56. doc = fitz.open(str(pdf_path))
  57. text_parts = []
  58. for page_num in range(len(doc)):
  59. page = doc[page_num]
  60. # Try to find tables on this page
  61. page_tables = page.find_tables()
  62. table_rects = []
  63. if page_tables.tables:
  64. for tab in page_tables.tables:
  65. table_data = tab.extract()
  66. if table_data and len(table_data) > 1:
  67. md_table = table_to_markdown(table_data)
  68. if md_table:
  69. text_parts.append(f'[TABLE_START]\n{md_table}\n[TABLE_END]')
  70. tables_found += 1
  71. table_rects.append(tab.bbox)
  72. # Get regular text, excluding table areas
  73. if not table_rects:
  74. page_text = page.get_text()
  75. if page_text.strip():
  76. text_parts.append(page_text)
  77. else:
  78. # Extract text only from non-table regions
  79. # Get page full rect, then extract text blocks and skip those inside table rects
  80. blocks = page.get_text("blocks") # list of (x0, y0, x1, y1, text, block_no, type)
  81. for block in blocks:
  82. bx0, by0, bx1, by1, block_text = block[:5]
  83. if not block_text.strip():
  84. continue
  85. # Check if this text block overlaps any table rect
  86. in_table = False
  87. for trect in table_rects:
  88. tx0, ty0, tx1, ty1 = trect
  89. # Check overlap: block center inside table rect
  90. bcx = (bx0 + bx1) / 2
  91. bcy = (by0 + by1) / 2
  92. if tx0 <= bcx <= tx1 and ty0 <= bcy <= ty1:
  93. in_table = True
  94. break
  95. if not in_table:
  96. text_parts.append(block_text)
  97. doc.close()
  98. full_text = '\n'.join(text_parts)
  99. if full_text.strip():
  100. with open(out_path, 'w', encoding='utf-8') as f:
  101. f.write(f'# {pdf_path.name}\n\n')
  102. f.write(full_text)
  103. success += 1
  104. else:
  105. with open(out_path, 'w', encoding='utf-8') as f:
  106. f.write(f'# {pdf_path.name}\n# [scan PDF]\n')
  107. failed += 1
  108. except Exception as e:
  109. failed += 1
  110. if (i + 1) % 100 == 0:
  111. print(f' ERROR [{i+1}/{total}] {pdf_path.name}: {e}', file=sys.stderr)
  112. if (i + 1) % 200 == 0:
  113. print(f' Progress: {i+1}/{total}, tables: {tables_found}')
  114. print(f'\nDone! success={success} failed={failed} tables={tables_found}')