Add medical order downloader with patient ID template
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Downloaded patient data (contains real names / hospital IDs) - never commit
|
||||||
|
orders_output/
|
||||||
|
*_output/
|
||||||
|
*_downloads/
|
||||||
|
patient_id.csv
|
||||||
|
patient_id_filled.csv
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# medical_orders
|
||||||
|
|
||||||
|
批量从住院病历系统(HIS)抓取患者医嘱(长期医嘱 + 临时医嘱),按住院次归档保存。
|
||||||
|
|
||||||
|
## 用法
|
||||||
|
|
||||||
|
1. 复制 `patient_id_template.csv`,把示例行换成真实的住院号(`Patient_ID` 列),另存为例如 `patient_id.csv`(该文件名已在 `.gitignore` 中排除,不会被提交)。
|
||||||
|
2. 安装依赖:
|
||||||
|
|
||||||
|
```
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 运行:
|
||||||
|
|
||||||
|
```
|
||||||
|
python download_orders.py --template patient_id.csv --output-dir orders_output
|
||||||
|
```
|
||||||
|
|
||||||
|
## 输出
|
||||||
|
|
||||||
|
写入 `--output-dir`(默认 `orders_output/`,已在 `.gitignore` 中排除):
|
||||||
|
|
||||||
|
- `<住院号>.json`:该患者每次住院的长期/临时医嘱原始行数据
|
||||||
|
- `orders_summary.csv`:所有患者、所有住院次的医嘱汇总表
|
||||||
|
|
||||||
|
## 隐私说明
|
||||||
|
|
||||||
|
抓取结果包含患者姓名、住院号等真实隐私信息(PHI),**任何情况下都不要提交到 Git 仓库**。仓库里只保留代码和空模板;真实的患者名单文件和下载结果目录已通过 `.gitignore` 排除。
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
"""Batch-download inpatient medical orders (医嘱) from the hospital HIS system.
|
||||||
|
|
||||||
|
Reads a list of patient IDs (病历号/住院号) from a CSV template, then for each
|
||||||
|
patient and each hospital visit ("住院次") pulls the long-term and temporary
|
||||||
|
order tables and writes them to per-patient JSON files, plus one combined CSV.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python download_orders.py --template patient_id_template.csv --output-dir orders_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
|
||||||
|
|
||||||
|
INFO_PATTERNS = {
|
||||||
|
"name": r"姓名:([^<]+)",
|
||||||
|
"dept": r"出院科室:([^<]+)",
|
||||||
|
"intime": r'<span id="span_index_intime">(.*?)</span>',
|
||||||
|
"outtime": r'<span id="span_index_outtime">(.*?)</span>',
|
||||||
|
"visitMax": r'<span id="span_index_visitMax">(.*?)</span>',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class VisitOrders:
|
||||||
|
visit_id: int
|
||||||
|
dept: str
|
||||||
|
intime: str
|
||||||
|
outtime: str
|
||||||
|
long_orders: list[list[str]] = field(default_factory=list)
|
||||||
|
temp_orders: list[list[str]] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PatientOrders:
|
||||||
|
patient_id: str
|
||||||
|
name: str
|
||||||
|
visits: list[VisitOrders] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def read_template(path: Path) -> list[str]:
|
||||||
|
"""Read patient IDs from the CSV template (column: Patient_ID)."""
|
||||||
|
patient_ids: list[str] = []
|
||||||
|
with path.open(newline="", encoding="utf-8-sig") as f:
|
||||||
|
reader = csv.DictReader(f)
|
||||||
|
if reader.fieldnames is None or "Patient_ID" not in reader.fieldnames:
|
||||||
|
raise ValueError(f"Template must have a 'Patient_ID' column, got: {reader.fieldnames}")
|
||||||
|
for row in reader:
|
||||||
|
pid = (row.get("Patient_ID") or "").strip()
|
||||||
|
if pid:
|
||||||
|
patient_ids.append(pid)
|
||||||
|
return patient_ids
|
||||||
|
|
||||||
|
|
||||||
|
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 extract_order_rows(html: str) -> list[list[str]]:
|
||||||
|
"""Parse a medical-order HTML table into a list of cell-text rows."""
|
||||||
|
rows = re.findall(r"<tr>(.*?)</tr>", html, re.DOTALL)
|
||||||
|
result = []
|
||||||
|
for row in rows:
|
||||||
|
cells = re.findall(r"<td[^>]*>(.*?)</td>", row, re.DOTALL)
|
||||||
|
if not cells:
|
||||||
|
continue
|
||||||
|
cell_texts = [re.sub(r"<[^>]+>", "", c).strip() for c in cells]
|
||||||
|
if len(cell_texts) >= 3:
|
||||||
|
result.append(cell_texts)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def get_orders(session: requests.Session, base_url: str, hospital_no: str, patient_id: str, visit_id: int) -> dict:
|
||||||
|
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)}
|
||||||
|
|
||||||
|
long_resp = session.get(f"{base_url}/Order/LongOrder", params=params, headers=headers, timeout=30)
|
||||||
|
temp_resp = session.get(f"{base_url}/Order/TempOrder", params=params, headers=headers, timeout=30)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"long": extract_order_rows(long_resp.text),
|
||||||
|
"temp": extract_order_rows(temp_resp.text),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def process_patient(base_url: str, hospital_no: str, patient_id: str) -> PatientOrders:
|
||||||
|
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 = PatientOrders(patient_id=patient_id, name=info.get("name", ""))
|
||||||
|
|
||||||
|
for visit_id in range(1, visit_max + 1):
|
||||||
|
visit_info = info if visit_id == 1 else get_patient_info(session, base_url, hospital_no, patient_id, visit_id)
|
||||||
|
orders = get_orders(session, base_url, hospital_no, patient_id, visit_id)
|
||||||
|
result.visits.append(
|
||||||
|
VisitOrders(
|
||||||
|
visit_id=visit_id,
|
||||||
|
dept=visit_info.get("dept", ""),
|
||||||
|
intime=visit_info.get("intime", ""),
|
||||||
|
outtime=visit_info.get("outtime", ""),
|
||||||
|
long_orders=orders["long"],
|
||||||
|
temp_orders=orders["temp"],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def save_patient_json(patient: PatientOrders, output_dir: Path) -> Path:
|
||||||
|
out_path = output_dir / f"{patient.patient_id}.json"
|
||||||
|
payload = {
|
||||||
|
"patient_id": patient.patient_id,
|
||||||
|
"name": patient.name,
|
||||||
|
"visits": [
|
||||||
|
{
|
||||||
|
"visit_id": v.visit_id,
|
||||||
|
"dept": v.dept,
|
||||||
|
"intime": v.intime,
|
||||||
|
"outtime": v.outtime,
|
||||||
|
"long_orders": v.long_orders,
|
||||||
|
"temp_orders": v.temp_orders,
|
||||||
|
}
|
||||||
|
for v in patient.visits
|
||||||
|
],
|
||||||
|
}
|
||||||
|
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
return out_path
|
||||||
|
|
||||||
|
|
||||||
|
def append_summary_rows(writer: csv.writer, patient: PatientOrders) -> int:
|
||||||
|
row_count = 0
|
||||||
|
for visit in patient.visits:
|
||||||
|
for order_type, rows in (("长期", visit.long_orders), ("临时", visit.temp_orders)):
|
||||||
|
for cells in rows:
|
||||||
|
writer.writerow([patient.patient_id, patient.name, visit.visit_id, order_type, *cells])
|
||||||
|
row_count += 1
|
||||||
|
return row_count
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--template", type=Path, default=Path("patient_id_template.csv"), help="CSV file with a Patient_ID column")
|
||||||
|
parser.add_argument("--output-dir", type=Path, default=Path("orders_output"), help="Where to write per-patient JSON + summary CSV")
|
||||||
|
parser.add_argument("--base-url", default=DEFAULT_BASE_URL, help="HIS system base URL")
|
||||||
|
parser.add_argument("--hospital-no", default=DEFAULT_HOSPITAL_NO, help="Hospital number query param")
|
||||||
|
parser.add_argument("--delay", type=float, default=DEFAULT_DELAY_SEC, help="Seconds to sleep between patients")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
patient_ids = read_template(args.template)
|
||||||
|
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 / "orders_summary.csv"
|
||||||
|
|
||||||
|
with summary_path.open("w", newline="", encoding="utf-8-sig") as f:
|
||||||
|
writer = csv.writer(f)
|
||||||
|
writer.writerow(["住院号", "姓名", "住院次", "医嘱类型", "分类", "时间", "内容", "剂量", "单位", "途径"])
|
||||||
|
|
||||||
|
total_rows = 0
|
||||||
|
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
|
||||||
|
|
||||||
|
json_path = save_patient_json(patient, args.output_dir)
|
||||||
|
row_count = append_summary_rows(writer, patient)
|
||||||
|
total_rows += row_count
|
||||||
|
print(f" {patient.name or '(unknown)'}: {len(patient.visits)} visit(s), {row_count} order row(s) -> {json_path.name}")
|
||||||
|
|
||||||
|
if i < len(patient_ids):
|
||||||
|
time.sleep(args.delay)
|
||||||
|
|
||||||
|
print(f"\nDone. {total_rows} order rows written to {summary_path}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
Patient_ID,Name
|
||||||
|
0000000001,示例患者1
|
||||||
|
0000000002,示例患者2
|
||||||
|
@@ -0,0 +1 @@
|
|||||||
|
requests
|
||||||
Reference in New Issue
Block a user