Add document downloader and treatment-plan summary combining orders + operation notes
This commit is contained in:
@@ -0,0 +1,221 @@
|
||||
#!/usr/bin/env python
|
||||
"""Batch-download key clinical documents (手术记录 / 出院记录) from the HIS system.
|
||||
|
||||
Medical orders alone cannot tell whether a patient actually had definitive
|
||||
cancer surgery - operative details only live in the operation note /
|
||||
discharge summary documents. This script fetches those specific documents
|
||||
per visit and extracts the surgery name, TNM stage and discharge diagnosis
|
||||
when present.
|
||||
|
||||
Usage:
|
||||
python download_documents.py --template patient_id_full.csv --output-dir docs_output
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
DEFAULT_BASE_URL = "http://129.1.163.23:8086"
|
||||
DEFAULT_HOSPITAL_NO = "41580193-4"
|
||||
DEFAULT_DELAY_SEC = 0.3
|
||||
|
||||
KEY_DOC_KEYWORDS = ["手术记录", "出院记录"]
|
||||
|
||||
INFO_PATTERNS = {
|
||||
"name": r"姓名:([^<]+)",
|
||||
"visitMax": r'<span id="span_index_visitMax">(.*?)</span>',
|
||||
}
|
||||
|
||||
SURGERY_NAME_PATTERNS = [
|
||||
r"实施手术名称[::]\s*([^<\n]+)",
|
||||
r"手术名称[::]\s*([^<\n]+)",
|
||||
r"术式[::]\s*([^<\n]+)",
|
||||
r"手术方式[::]\s*([^<\n]+)",
|
||||
]
|
||||
|
||||
SURGERY_DATE_PATTERNS = [
|
||||
r"手术开始时间[::]\s*(\d{4}[-/]\d{2}[-/]\d{2})",
|
||||
r"手术日期[::]\s*(\d{4}[-/]\d{2}[-/]\d{2})",
|
||||
]
|
||||
|
||||
DISCHARGE_DX_PATTERNS = [
|
||||
r"出院诊断[::]\s*(.*?)(?=出院医嘱|出院情况|$)",
|
||||
r"入院诊断[::]\s*(.*?)(?=诊疗经过|$)",
|
||||
]
|
||||
|
||||
TNM_PATTERNS = [
|
||||
r"[pP]?([Tt]\d[a-zA-Z]*[Nn]\d[a-zA-Z]*[Mm]\d[a-zA-Z]*)",
|
||||
r"([Tt]\d[Nn]\d[Mm]\d)",
|
||||
r"分期[::]\s*([IViv]+[a-zA-Z]*)",
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisitDocs:
|
||||
visit_id: int
|
||||
has_surgery_record: bool = False
|
||||
surgery_name: str = ""
|
||||
surgery_date: str = ""
|
||||
discharge_dx: str = ""
|
||||
tnm: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatientDocs:
|
||||
patient_id: str
|
||||
name: str
|
||||
visits: list[VisitDocs] = field(default_factory=list)
|
||||
|
||||
|
||||
def get_patient_info(session: requests.Session, base_url: str, hospital_no: str, patient_id: str, visit_id: int) -> dict:
|
||||
url = f"{base_url}/?hospital_no={hospital_no}&patient_id={patient_id}&visit_id={visit_id}"
|
||||
resp = session.get(url, timeout=15)
|
||||
resp.encoding = "utf-8"
|
||||
html = resp.text
|
||||
info = {}
|
||||
for key, pattern in INFO_PATTERNS.items():
|
||||
match = re.search(pattern, html)
|
||||
if match:
|
||||
info[key] = match.group(1).strip().replace(" ", "").strip()
|
||||
return info
|
||||
|
||||
|
||||
def get_medical_index(session: requests.Session, base_url: str, hospital_no: str, patient_id: str, visit_id: int) -> list[dict]:
|
||||
"""List documents via Medical/Index. Returns doc_id (not a URL) per entry."""
|
||||
headers = {
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "text/html, */*; q=0.01",
|
||||
"Referer": f"{base_url}/?hospital_no={hospital_no}&patient_id={patient_id}&visit_id={visit_id}",
|
||||
}
|
||||
params = {"hospitalNo": hospital_no, "patientId": patient_id, "visitId": str(visit_id), "fileId": "2", "deptcode": "", "inpno": ""}
|
||||
resp = session.get(f"{base_url}/Medical/Index", params=params, headers=headers, timeout=30)
|
||||
resp.encoding = "utf-8"
|
||||
if "无病历文书" in resp.text:
|
||||
return []
|
||||
doc_pattern = r'value="([^"]+)"[^>]*>\s*<span>\s*([^<]*?)\s* \s*([^<]*?)\s*</span>'
|
||||
docs = re.findall(doc_pattern, resp.text)
|
||||
return [{"doc_id": doc_id, "date": d.strip(), "name": n.strip()} for doc_id, d, n in docs]
|
||||
|
||||
|
||||
def get_document_text(session: requests.Session, base_url: str, doc_id: str) -> str | None:
|
||||
resp = session.get(f"{base_url}/Medical/MedicalRecord", params={"fileId": doc_id}, timeout=30)
|
||||
resp.encoding = "utf-8"
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
text = re.sub(r"<[^>]+>", " ", resp.text)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
return text.replace(" ", " ")
|
||||
|
||||
|
||||
def first_match(patterns: list[str], text: str, max_len: int = 500) -> str:
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, text, re.DOTALL)
|
||||
if match:
|
||||
return match.group(1).strip()[:max_len]
|
||||
return ""
|
||||
|
||||
|
||||
def process_patient(base_url: str, hospital_no: str, patient_id: str) -> PatientDocs:
|
||||
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")
|
||||
|
||||
result = PatientDocs(patient_id=patient_id, name=info.get("name", ""))
|
||||
|
||||
for visit_id in range(1, visit_max + 1):
|
||||
records = get_medical_index(session, base_url, hospital_no, patient_id, visit_id)
|
||||
visit_docs = VisitDocs(visit_id=visit_id)
|
||||
|
||||
for rec in records:
|
||||
if not any(kw in rec["name"] for kw in KEY_DOC_KEYWORDS):
|
||||
continue
|
||||
text = get_document_text(session, base_url, rec["doc_id"])
|
||||
if not text:
|
||||
continue
|
||||
|
||||
if "手术记录" in rec["name"]:
|
||||
visit_docs.has_surgery_record = True
|
||||
if not visit_docs.surgery_name:
|
||||
visit_docs.surgery_name = first_match(SURGERY_NAME_PATTERNS, text)
|
||||
if not visit_docs.surgery_date:
|
||||
visit_docs.surgery_date = first_match(SURGERY_DATE_PATTERNS, text, max_len=10)
|
||||
|
||||
if "出院记录" in rec["name"]:
|
||||
if not visit_docs.discharge_dx:
|
||||
visit_docs.discharge_dx = first_match(DISCHARGE_DX_PATTERNS, text)
|
||||
if not visit_docs.tnm:
|
||||
visit_docs.tnm = first_match(TNM_PATTERNS, text, max_len=20)
|
||||
|
||||
result.visits.append(visit_docs)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def save_patient_json(patient: PatientDocs, output_dir: Path) -> Path:
|
||||
out_path = output_dir / f"{patient.patient_id}.json"
|
||||
payload = {
|
||||
"patient_id": patient.patient_id,
|
||||
"name": patient.name,
|
||||
"visits": [vars(v) for v in patient.visits],
|
||||
}
|
||||
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return out_path
|
||||
|
||||
|
||||
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_output"))
|
||||
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)
|
||||
summary_path = args.output_dir / "documents_summary.csv"
|
||||
|
||||
with summary_path.open("w", newline="", encoding="utf-8-sig") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerow(["住院号", "姓名", "住院次", "有手术记录", "手术名称", "手术日期", "出院诊断", "TNM分期"])
|
||||
|
||||
for i, patient_id in enumerate(patient_ids, start=1):
|
||||
print(f"[{i}/{len(patient_ids)}] {patient_id}")
|
||||
try:
|
||||
patient = process_patient(args.base_url, args.hospital_no, patient_id)
|
||||
except Exception as exc:
|
||||
print(f" failed: {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
save_patient_json(patient, args.output_dir)
|
||||
for v in patient.visits:
|
||||
writer.writerow([
|
||||
patient.patient_id, patient.name, v.visit_id,
|
||||
"是" if v.has_surgery_record else "否",
|
||||
v.surgery_name, v.surgery_date, v.discharge_dx, v.tnm,
|
||||
])
|
||||
|
||||
if i < len(patient_ids):
|
||||
time.sleep(args.delay)
|
||||
|
||||
print(f"\nDone -> {summary_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user