khmer-document-corpus / scripts /batch_ingest.py
darachhat
feat: build production-ready Khmer Document Corpus v0.2.0 with Typer CLI, PyMuPDF, Polars, and DI architecture
c4e128a
Raw
History Blame Contribute Delete
3.78 kB
#!/usr/bin/env python3
"""
scripts/batch_ingest.py
-----------------------
Batch ingest all PDFs from a source directory, generate metadata stubs,
and render first-page previews in one shot.
Usage:
python scripts/batch_ingest.py --source /path/to/pdfs --category government_report
"""
from __future__ import annotations
import argparse
import json
import shutil
import uuid
from pathlib import Path
from rich.console import Console
from rich.progress import track
console = Console()
CATEGORIES = [
"government_report",
"government_form",
"law",
"gazette",
"book",
"research_paper",
"manual",
"annual_report",
"financial_report",
"certificate",
"contract",
"invoice",
"receipt",
"newspaper",
"magazine",
"presentation",
"other",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Batch ingest PDFs into the corpus.")
parser.add_argument("--source", required=True, type=Path, help="Source directory of PDFs.")
parser.add_argument("--category", default="other", choices=CATEGORIES)
parser.add_argument("--language", default="km", choices=["km", "en", "mixed"])
parser.add_argument("--pdf-dir", default=Path("pdf"), type=Path)
parser.add_argument("--meta-dir", default=Path("metadata"), type=Path)
parser.add_argument("--preview-dir", default=Path("preview"), type=Path)
parser.add_argument("--dpi", default=150, type=int)
parser.add_argument("--no-preview", action="store_true")
return parser.parse_args()
def main() -> None:
args = parse_args()
source: Path = args.source.resolve()
pdf_dest: Path = (args.pdf_dir / args.category).resolve()
meta_dest: Path = args.meta_dir.resolve()
preview_dest: Path = args.preview_dir.resolve()
pdf_dest.mkdir(parents=True, exist_ok=True)
meta_dest.mkdir(parents=True, exist_ok=True)
preview_dest.mkdir(parents=True, exist_ok=True)
pdfs = list(source.rglob("*.pdf"))
console.print(f"Found [cyan]{len(pdfs)}[/cyan] PDF(s) in [bold]{source}[/bold]")
try:
from pdf2image import convert_from_path # type: ignore[import]
has_pdf2image = True
except ImportError:
has_pdf2image = False
if not args.no_preview:
console.print("[yellow]pdf2image not found – skipping previews.[/yellow]")
for pdf in track(pdfs, description="Processing…"):
dest_pdf = pdf_dest / pdf.name
if not dest_pdf.exists():
shutil.copy2(pdf, dest_pdf)
meta_file = meta_dest / (pdf.stem + ".json")
if not meta_file.exists():
stub = {
"id": str(uuid.uuid4()),
"language": args.language,
"category": args.category,
"pages": 0,
"native_pdf": False,
"scanned": False,
"has_tables": False,
"has_images": False,
"has_header": False,
"has_footer": False,
"source": None,
"license": None,
"pdf_path": str(dest_pdf.relative_to(Path(".").resolve())),
"preview_path": None,
}
meta_file.write_text(json.dumps(stub, indent=2, ensure_ascii=False), encoding="utf-8")
if has_pdf2image and not args.no_preview:
doc_preview = preview_dest / pdf.stem
doc_preview.mkdir(parents=True, exist_ok=True)
if not list(doc_preview.glob("*.png")):
images = convert_from_path(dest_pdf, dpi=args.dpi, last_page=1)
images[0].save(doc_preview / "page_0001.png", "PNG")
console.print("[green]✓ Batch ingest complete.[/green]")
if __name__ == "__main__":
main()