Preserve raw HTML alongside stripped text when archiving documents

This commit is contained in:
2026-08-06 16:45:07 +08:00
parent bbbd0c92f6
commit 6971411574
2 changed files with 25 additions and 10 deletions
+14 -8
View File
@@ -1,9 +1,13 @@
#!/usr/bin/env python
"""Download every clinical document (病历文书) for each patient/visit as plain text.
"""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 text locally, plus a per-patient manifest.
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
@@ -25,9 +29,10 @@ from download_documents import (
DEFAULT_BASE_URL,
DEFAULT_DELAY_SEC,
DEFAULT_HOSPITAL_NO,
get_document_text,
get_document_html,
get_medical_index,
get_patient_info,
html_to_text,
)
@@ -49,22 +54,23 @@ def process_patient(base_url: str, hospital_no: str, patient_id: str, patient_di
seen_names: dict[str, int] = {}
for rec in records:
text = get_document_text(session, base_url, rec["doc_id"])
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(":", "")
filename = f"{safe_date}_{safe_name}{suffix}.txt"
base_name = f"{safe_date}_{safe_name}{suffix}"
if text:
if html:
visit_dir.mkdir(parents=True, exist_ok=True)
(visit_dir / filename).write_text(text, encoding="utf-8")
(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": filename if text else None,
"saved_as": base_name if html else None,
})
manifest["visits"].append(visit_manifest)