extract_pdfs.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. """批量提取 PDF 为文本文件,存到 processed/ 目录"""
  3. import os
  4. import sys
  5. import fitz # PyMuPDF
  6. from pathlib import Path
  7. RAW_DIR = Path('/home/67/knowledge/maritime/raw')
  8. OUT_DIR = Path('/home/67/knowledge/maritime/processed')
  9. OUT_DIR.mkdir(exist_ok=True)
  10. pdf_files = sorted(RAW_DIR.glob('*.pdf'))
  11. total = len(pdf_files)
  12. print(f'共 {total} 个 PDF 文件')
  13. success = 0
  14. failed = 0
  15. skipped = 0
  16. for i, pdf_path in enumerate(pdf_files):
  17. out_path = OUT_DIR / (pdf_path.stem + '.txt')
  18. # 跳过已处理的
  19. if out_path.exists() and out_path.stat().st_size > 0:
  20. skipped += 1
  21. continue
  22. try:
  23. doc = fitz.open(str(pdf_path))
  24. text_parts = []
  25. for page_num, page in enumerate(doc):
  26. text = page.get_text()
  27. if text.strip():
  28. text_parts.append(f'--- 第{page_num+1}页 ---\n{text}')
  29. doc.close()
  30. full_text = '\n'.join(text_parts)
  31. if full_text.strip():
  32. with open(out_path, 'w', encoding='utf-8') as f:
  33. f.write(f'# 源文件: {pdf_path.name}\n\n')
  34. f.write(full_text)
  35. success += 1
  36. else:
  37. # 扫描版 PDF,无法提取文字
  38. with open(out_path, 'w', encoding='utf-8') as f:
  39. f.write(f'# 源文件: {pdf_path.name}\n# [扫描版PDF,无法提取文字]\n')
  40. failed += 1
  41. except Exception as e:
  42. failed += 1
  43. print(f' ERROR [{i+1}/{total}] {pdf_path.name}: {e}', file=sys.stderr)
  44. if (i+1) % 100 == 0:
  45. print(f' 进度: {i+1}/{total} (成功:{success} 跳过:{skipped} 失败:{failed})')
  46. print(f'完成! 成功:{success} 跳过:{skipped} 失败:{failed} 总计:{total}')