"""One-time extraction: python scripts/extract_k1_journals.py . Requires pdfplumber for this development operation only; the service reads JSON. """ import argparse from collections import Counter from datetime import datetime import hashlib import json from pathlib import Path import pdfplumber def extract(source: Path) -> dict: rows = [] with pdfplumber.open(source) as document: for page in document.pages: for table in page.extract_tables(): for row in table: if row[0] and row[0].isdigit(): if len(row) != 4 or not all(row) or not set(row[2].split()) <= {"К1", "К2", "К3"}: raise ValueError(f"Invalid category row: {row}") # Some entries include previous categories; use the final category. row[2] = row[2].split()[-1] row[3] = row[3].splitlines()[-1] datetime.strptime(row[3], "%d.%m.%Y") rows.append(row) if not rows or [int(row[0]) for row in rows] != list(range(1, len(rows) + 1)): raise ValueError("Journal numbering is incomplete or duplicated") journals = [{"name": " ".join(row[1].split()), "categorized_on": row[3], "source_row": int(row[0])} for row in rows if row[2] == "К1"] if not journals: raise ValueError("No K1 journals found") return {"source": source.name, "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(), "source_rows": len(rows), "category_counts": dict(Counter(row[2] for row in rows)), "journals": journals} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) parser.add_argument("--output", type=Path, default=Path("app/data/k1_journals.json")) args = parser.parse_args() result = extract(args.source) args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Saved {len(result['journals'])} K1 journals; verified {result['source_rows']} source rows")