#!/usr/bin/env python """Download every clinical document (病历文书) for each patient/visit, saving both the raw HTML and a tag-stripped plain-text copy. Unlike download_documents.py (which only extracts 手术记录/出院记录 into a summary CSV), this walks the full Medical/Index document list per visit and saves each document's complete content locally, plus a per-patient manifest. The HTML is kept alongside the .txt because stripping tags flattens any tables (lab results, checkbox exam findings) into a single line of space-separated text, which loses structure that might matter later. Usage: python download_all_documents.py --template patient_id.csv --output-dir docs_full """ from __future__ import annotations import argparse import csv import json import re import sys import time from pathlib import Path import requests from download_documents import ( DEFAULT_BASE_URL, DEFAULT_DELAY_SEC, DEFAULT_HOSPITAL_NO, get_document_html, get_medical_index, get_patient_info, html_to_text, ) def sanitize_filename(name: str) -> str: return re.sub(r'[<>:"/\\|?*]', "_", name).strip() or "unnamed" def process_patient(base_url: str, hospital_no: str, patient_id: str, patient_dir: Path) -> dict: session = requests.Session() info = get_patient_info(session, base_url, hospital_no, patient_id, visit_id=1) visit_max = int(info.get("visitMax") or "1") manifest = {"patient_id": patient_id, "name": info.get("name", ""), "visits": []} for visit_id in range(1, visit_max + 1): records = get_medical_index(session, base_url, hospital_no, patient_id, visit_id) visit_dir = patient_dir / f"visit_{visit_id}" visit_manifest = {"visit_id": visit_id, "documents": []} seen_names: dict[str, int] = {} for rec in records: html = get_document_html(session, base_url, rec["doc_id"]) safe_name = sanitize_filename(rec["name"]) seen_names[safe_name] = seen_names.get(safe_name, 0) + 1 suffix = f"_{seen_names[safe_name]}" if seen_names[safe_name] > 1 else "" safe_date = rec["date"].replace("/", "-").replace(" ", "_").replace(":", "") base_name = f"{safe_date}_{safe_name}{suffix}" if html: visit_dir.mkdir(parents=True, exist_ok=True) (visit_dir / f"{base_name}.html").write_text(html, encoding="utf-8") (visit_dir / f"{base_name}.txt").write_text(html_to_text(html), encoding="utf-8") visit_manifest["documents"].append({ "doc_id": rec["doc_id"], "date": rec["date"], "name": rec["name"], "saved_as": base_name if html else None, }) manifest["visits"].append(visit_manifest) return manifest def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--template", type=Path, default=Path("patient_id_template.csv")) parser.add_argument("--output-dir", type=Path, default=Path("docs_full")) parser.add_argument("--base-url", default=DEFAULT_BASE_URL) parser.add_argument("--hospital-no", default=DEFAULT_HOSPITAL_NO) parser.add_argument("--delay", type=float, default=DEFAULT_DELAY_SEC) args = parser.parse_args() with args.template.open(newline="", encoding="utf-8-sig") as f: patient_ids = [row["Patient_ID"].strip() for row in csv.DictReader(f) if row.get("Patient_ID", "").strip()] if not patient_ids: print(f"No patient IDs found in {args.template}", file=sys.stderr) return 1 args.output_dir.mkdir(parents=True, exist_ok=True) total_docs = 0 for i, patient_id in enumerate(patient_ids, start=1): print(f"[{i}/{len(patient_ids)}] {patient_id}") patient_dir = args.output_dir / patient_id try: manifest = process_patient(args.base_url, args.hospital_no, patient_id, patient_dir) except Exception as exc: print(f" failed: {exc}", file=sys.stderr) continue patient_dir.mkdir(parents=True, exist_ok=True) (patient_dir / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") doc_count = sum(len(v["documents"]) for v in manifest["visits"]) total_docs += doc_count print(f" {manifest['name'] or '(unknown)'}: {len(manifest['visits'])} visit(s), {doc_count} document(s)") if i < len(patient_ids): time.sleep(args.delay) print(f"\nDone. {total_docs} documents saved to {args.output_dir}") return 0 if __name__ == "__main__": raise SystemExit(main())