105 lines
3.1 KiB
Python
105 lines
3.1 KiB
Python
#!/usr/bin/env python3
|
||
"""把听力材料的 PDF 抽成 actions/ 下的 Markdown 素材草稿。
|
||
|
||
用法:
|
||
python actions/pdf_extract.py "C:/Users/HUAWEI/Desktop/第3期_classic.pdf"
|
||
python actions/pdf_extract.py <pdf> --slug issue3-classic --level B2 --title "第3期 classic"
|
||
|
||
依赖 pdftotext(poppler,优先);没有则回退 pypdf(pip install pypdf)。
|
||
抽取后是"原文草稿",我再人工补小标题/生词/等级。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import datetime as _dt
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
ACTIONS = ROOT / "actions"
|
||
|
||
|
||
def extract_pdf(pdf: Path) -> str:
|
||
if shutil.which("pdftotext"):
|
||
proc = subprocess.run(
|
||
["pdftotext", "-layout", str(pdf), "-"],
|
||
capture_output=True, text=True, encoding="utf-8", errors="replace",
|
||
)
|
||
if proc.returncode == 0 and proc.stdout.strip():
|
||
return proc.stdout
|
||
try:
|
||
import pypdf # type: ignore
|
||
except ImportError:
|
||
sys.exit("找不到 pdftotext(poppler),也没装 pypdf。请二选一安装。")
|
||
reader = pypdf.PdfReader(str(pdf))
|
||
return "\n".join((page.extract_text() or "") for page in reader.pages)
|
||
|
||
|
||
def clean(text: str) -> str:
|
||
text = text.replace("\ufffd", "") # 替换字符
|
||
lines = [ln.rstrip() for ln in text.splitlines()]
|
||
kept: list[str] = []
|
||
blanks = 0
|
||
for ln in lines:
|
||
if not ln.strip():
|
||
blanks += 1
|
||
if blanks > 1:
|
||
continue
|
||
else:
|
||
blanks = 0
|
||
# 丢掉只有引号/标点的残留行(PDF 抽取常见噪音)
|
||
if ln.strip() and not re.search(r"[A-Za-z0-9\u4e00-\u9fff]", ln):
|
||
continue
|
||
kept.append(ln)
|
||
return "\n".join(kept).strip() + "\n"
|
||
|
||
|
||
def default_slug(pdf: Path) -> str:
|
||
slug = re.sub(r"[^\w\-]+", "-", pdf.stem, flags=re.UNICODE).strip("-").lower()
|
||
return slug or "material"
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description="PDF → actions/*.md")
|
||
ap.add_argument("pdf", help="PDF 路径")
|
||
ap.add_argument("--slug", help="文件名 slug(默认取 PDF 文件名)")
|
||
ap.add_argument("--level", default="待定", help="CEFR 等级")
|
||
ap.add_argument("--title", help="素材标题(默认取 PDF 文件名)")
|
||
ap.add_argument("--date", default=_dt.date.today().isoformat(), help="日期 YYYY-MM-DD")
|
||
args = ap.parse_args()
|
||
|
||
pdf = Path(args.pdf)
|
||
if not pdf.is_file():
|
||
sys.exit(f"文件不存在: {pdf}")
|
||
|
||
slug = args.slug or default_slug(pdf)
|
||
title = args.title or pdf.stem
|
||
body = clean(extract_pdf(pdf))
|
||
|
||
ACTIONS.mkdir(exist_ok=True)
|
||
out = ACTIONS / f"{args.date}-{slug}.md"
|
||
out.write_text(
|
||
f"""# Material — {args.date} · {slug}
|
||
|
||
- **source**: 用户 PDF · `{pdf.name}` · {title}
|
||
- **level**: {args.level}
|
||
- **duration**: 待补
|
||
- **pdf**: `{pdf}`
|
||
|
||
---
|
||
|
||
## 原文(自动抽取草稿,待人工整理)
|
||
|
||
{body}
|
||
""",
|
||
encoding="utf-8",
|
||
)
|
||
print(f"已写出: {out.relative_to(ROOT)}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|