Scripts for batch-scraping pathology reports from the hospital PACS system (by inpatient + outpatient number, across pathology and bone marrow exam categories) and using the results to fill in blank fields in a lymphoma patient dataset.
330 lines
13 KiB
Python
330 lines
13 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
批量抓取并保存病理报告(淋巴瘤数据)
|
||
- 病历号取自 Excel 表格中的 住院号 列(自动补 000 前缀)
|
||
- 按病历号(住院号)搜一次,再查出对应门诊号后按门诊号搜一次,两次结果按检查号去重合并
|
||
(部分病理检查是门诊开的单,只挂在门诊号下,仅按住院号搜会漏)
|
||
- 每个患者的所有报告合并保存为一个json+一个txt,图片统一放images子目录,不保存原始html
|
||
- 用法: python extract_pathology_reports.py [患者数量上限,不填则跑全部]
|
||
"""
|
||
|
||
import sys
|
||
sys.path.insert(0, r"C:\Users\senqu\Desktop\all-codex - 副本")
|
||
from http_scraper import HttpScaper
|
||
import re
|
||
import json
|
||
import html as html_lib
|
||
import pandas as pd
|
||
import requests
|
||
import time
|
||
import os
|
||
|
||
# 配置
|
||
EXCEL_PATH = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\淋巴瘤数据.xlsx"
|
||
OUTPUT_ROOT = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\患者报告"
|
||
PROGRESS_FILE = r"C:\Users\senqu\Desktop\尚安迪\2026.8.25\progress.json"
|
||
|
||
HIS_BASE_URL = 'http://129.1.163.23:8086'
|
||
ZZ_URL = 'http://129.1.177.108:8118/wfinpatientproof.aspx'
|
||
HOSPITAL_NO = '41580193-4'
|
||
|
||
|
||
def get_visit_max(his_session, patient_id):
|
||
"""获取患者最大住院次数(用于拼门诊号查询参数)"""
|
||
url = f'{HIS_BASE_URL}/?hospital_no={HOSPITAL_NO}&patient_id={patient_id}&visit_id=1'
|
||
resp = his_session.get(url, timeout=60)
|
||
resp.encoding = 'utf-8'
|
||
m = re.search(r'span_index_visitMax[^>]*>(\d+)', resp.text)
|
||
return int(m.group(1)) if m else 1
|
||
|
||
|
||
def get_outpatient_no(his_session, patient_id, visit_max):
|
||
"""从住院证页面查询该病历号对应的门诊号"""
|
||
patient_no = f'ZY{visit_max:02d}{patient_id}'
|
||
url = f'{ZZ_URL}?patient_no={patient_no}'
|
||
resp = his_session.get(url, timeout=30)
|
||
resp.encoding = 'utf-8'
|
||
m = re.search(r'id="alCardNO">(\d+)</span>', resp.text)
|
||
return m.group(1) if m else ''
|
||
|
||
|
||
# 检查类别下拉框里,"病理"和"骨髓"是两个独立类别(淋巴瘤患者常规做骨髓穿刺/活检,
|
||
# 这部分报告只挂在"骨髓"类别下,不在"病理"类别里),所以两个类别都要搜,缺一个就会漏。
|
||
EXAM_CLASSES = [("patho|9", "病理"), ("BoneMarrow|S", "骨髓")]
|
||
|
||
|
||
def search_by_clinicno_and_class(scraper, clinic_no, exam_class):
|
||
"""按病历号/门诊号(clinicno)搜索,限定检查类别为 exam_class
|
||
|
||
注意:不能先搜"全部"类别再本地过滤,因为搜索结果每页只有20条,
|
||
翻页按钮(goPage/lnkBtnNext)对该搜索会返回500错误、无法翻页,
|
||
older的报告会被截断丢失。直接在服务端按类别过滤可以避开这个问题。
|
||
"""
|
||
data = dict(scraper._form_fields)
|
||
for k in ("CB_Time", "__EVENTTARGET", "__EVENTARGUMENT"):
|
||
data.pop(k, None)
|
||
data.update({
|
||
"clinicno": clinic_no, "checkno": "", "CB_Info": "on",
|
||
"DDL_ExamClassItem": exam_class,
|
||
"IB_Search.x": "30", "IB_Search.y": "10",
|
||
})
|
||
resp = scraper.session.post("http://129.1.58.7:5001/Pages/HISToPacs.aspx", data=data, timeout=15)
|
||
resp.encoding = "gbk"
|
||
scraper._update_form_fields(resp.text)
|
||
return resp.text
|
||
|
||
|
||
def get_total_pages(html_text):
|
||
m = re.search(r'id="lblSumPage"[^>]*>([^<]*)<', html_text)
|
||
if m and m.group(1).strip().isdigit():
|
||
return int(m.group(1).strip())
|
||
return 1
|
||
|
||
|
||
def search_pathology_records(scraper, clinic_no):
|
||
"""对病理+骨髓两个类别分别搜索并合并,返回(报告列表, 是否有截断)"""
|
||
all_records = []
|
||
truncated = False
|
||
for exam_class, class_label in EXAM_CLASSES:
|
||
ht = search_by_clinicno_and_class(scraper, clinic_no, exam_class)
|
||
if scraper.has_no_records(ht):
|
||
continue
|
||
records = scraper.parse_result_table(ht)
|
||
for r in records:
|
||
r['检查类别'] = class_label
|
||
all_records.extend(records)
|
||
if get_total_pages(ht) > 1:
|
||
truncated = True
|
||
return all_records, truncated
|
||
|
||
|
||
def extract_report_details(scraper, report_url):
|
||
"""抓取报告详情页,解析出影像表现/印象/图片URL"""
|
||
try:
|
||
resp = scraper.session.get(f"http://129.1.58.7:5001/Pages/{report_url}", timeout=8)
|
||
resp.encoding = "gbk"
|
||
html_text = resp.text
|
||
result = {"影像表现": "", "印象": "", "raw_html": html_text, "image_urls": []}
|
||
|
||
hd_raw = re.search(r'name="hd_images"[^>]*value="([^"]*)"', html_text)
|
||
if hd_raw:
|
||
images = json.loads(html_lib.unescape(hd_raw.group(1)))
|
||
if images:
|
||
result["影像表现"] = (images[0].get("Describe") or "").strip()
|
||
result["印象"] = (images[0].get("Diagnosis") or "").strip()
|
||
result["images_data"] = images
|
||
for img in images:
|
||
u = img.get("ImgUrl", "")
|
||
if u:
|
||
result["image_urls"].append(f"http://129.1.58.7:5001/Pages/{u}")
|
||
|
||
if not result["印象"] and not result["影像表现"]:
|
||
hd_r = re.search(r'name="hdReportMsg"[^>]*value="([^"]*)"', html_text)
|
||
if hd_r:
|
||
reports = json.loads(html_lib.unescape(hd_r.group(1)))
|
||
if reports:
|
||
result["影像表现"] = (reports[0].get("examdesc") or "").strip()
|
||
result["印象"] = (reports[0].get("examdiagnosis") or "").strip()
|
||
|
||
if not result["印象"]:
|
||
m = re.search(r'<textarea[^>]*id="TB_YX"[^>]*>(.*?)</textarea>', html_text, re.S | re.I)
|
||
if m and m.group(1).strip():
|
||
result["印象"] = m.group(1).strip()
|
||
if not result["影像表现"]:
|
||
m = re.search(r'<textarea[^>]*id="TB_YXBX"[^>]*>(.*?)</textarea>', html_text, re.S | re.I)
|
||
if m and m.group(1).strip():
|
||
result["影像表现"] = m.group(1).strip()
|
||
|
||
return result
|
||
except Exception as e:
|
||
return {"影像表现": "", "印象": "", "error": str(e), "image_urls": []}
|
||
|
||
|
||
def download_image(scraper, img_url, save_path):
|
||
"""下载报告中的图片"""
|
||
try:
|
||
resp = scraper.session.get(img_url, timeout=15)
|
||
if resp.status_code == 200 and len(resp.content) > 100:
|
||
with open(save_path, 'wb') as f:
|
||
f.write(resp.content)
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def save_patient_reports(patient_dir, report_type, items, scraper):
|
||
"""合并保存一个患者的所有报告:
|
||
- 一个汇总 json(列表)+ 一个汇总 txt(分隔拼接)
|
||
- 所有图片平铺存到 images/ 子目录(按检查号_序号命名,避免重名)
|
||
- 不保存原始html
|
||
items: [(report_info, details), ...]
|
||
"""
|
||
d = os.path.join(patient_dir, report_type)
|
||
os.makedirs(d, exist_ok=True)
|
||
img_dir = os.path.join(d, 'images')
|
||
|
||
all_json = []
|
||
txt_parts = []
|
||
|
||
for report_info, details in items:
|
||
check_no = re.sub(r'[<>:"/\\|?*]', '', report_info.get('检查号', '') or 'noid')
|
||
|
||
txt_parts.append(
|
||
f"检查号: {check_no}\n"
|
||
f"检查项目: {report_info.get('检查项目', '')}\n"
|
||
f"检查类别: {report_info.get('检查类别', '')}\n"
|
||
f"查询类型: {report_info.get('查询类型', '')}\n"
|
||
f"检查部位: {report_info.get('检查部位', '')}\n"
|
||
f"检查时间: {report_info.get('检查时间', '')}\n\n"
|
||
f"=== 影像表现 ===\n{details.get('影像表现', '')}\n\n"
|
||
f"=== 印象/诊断 ===\n{details.get('印象', '')}\n"
|
||
)
|
||
|
||
jd = {'report_info': report_info, '影像表现': details.get('影像表现', ''), '印象': details.get('印象', '')}
|
||
if 'images_data' in details:
|
||
jd['images_data'] = details['images_data']
|
||
all_json.append(jd)
|
||
|
||
if details.get('image_urls'):
|
||
os.makedirs(img_dir, exist_ok=True)
|
||
for i, u in enumerate(details['image_urls']):
|
||
download_image(scraper, u, os.path.join(img_dir, f"{check_no}_{i + 1}.jpg"))
|
||
|
||
with open(os.path.join(d, f"{report_type}.json"), 'w', encoding='utf-8') as f:
|
||
json.dump(all_json, f, ensure_ascii=False, indent=2)
|
||
|
||
with open(os.path.join(d, f"{report_type}.txt"), 'w', encoding='utf-8') as f:
|
||
f.write(('\n' + '=' * 60 + '\n').join(txt_parts))
|
||
|
||
|
||
def get_medical_record_no(row):
|
||
"""病历号:住院号列补000前缀"""
|
||
return "000" + str(int(row['住院号'])).zfill(7)
|
||
|
||
|
||
def write_progress(processed, total, stats, current_patient, start_time, done=False):
|
||
"""把当前进度写入json文件,供 watch_progress.py 实时读取展示"""
|
||
data = {
|
||
'total': total,
|
||
'processed': processed,
|
||
'current_patient': current_patient,
|
||
'start_time': start_time,
|
||
'updated_at': time.time(),
|
||
'elapsed_sec': time.time() - start_time,
|
||
'done': done,
|
||
**stats,
|
||
}
|
||
tmp_path = PROGRESS_FILE + '.tmp'
|
||
with open(tmp_path, 'w', encoding='utf-8') as f:
|
||
json.dump(data, f, ensure_ascii=False)
|
||
os.replace(tmp_path, PROGRESS_FILE)
|
||
|
||
|
||
# ===== MAIN =====
|
||
def main():
|
||
limit = int(sys.argv[1]) if len(sys.argv) > 1 else None
|
||
|
||
df = pd.read_excel(EXCEL_PATH, sheet_name=0)
|
||
if limit:
|
||
df = df.head(limit)
|
||
os.makedirs(OUTPUT_ROOT, exist_ok=True)
|
||
scraper = HttpScaper()
|
||
|
||
his_session = requests.Session()
|
||
his_session.trust_env = False
|
||
|
||
total = len(df)
|
||
|
||
print(f"开始抓取 {total} 个患者的病理报告(住院号+门诊号双重查询)...")
|
||
start_time = time.time()
|
||
|
||
stats = {
|
||
'success': 0, 'no_record': 0, 'no_patho': 0, 'failed': 0,
|
||
'report_count': 0, 'truncated': 0, 'outpatient_found': 0,
|
||
'outpatient_extra_reports': 0,
|
||
}
|
||
write_progress(0, total, stats, '', start_time)
|
||
|
||
for idx, row in df.iterrows():
|
||
cn = get_medical_record_no(row)
|
||
|
||
if (idx + 1) % 50 == 0:
|
||
print(f"进度: {idx + 1}/{total} ({time.time() - start_time:.0f}秒)")
|
||
|
||
try:
|
||
# 1) 按病历号(住院号)搜索(病理+骨髓两个类别)
|
||
prs, truncated = search_pathology_records(scraper, cn)
|
||
for r in prs:
|
||
r['查询类型'] = '住院'
|
||
if truncated:
|
||
print(f" [{cn}] 警告: 按住院号搜到的某个类别报告超过1页,只抓取了第1页,可能有遗漏!")
|
||
stats['truncated'] += 1
|
||
|
||
# 2) 查询门诊号,按门诊号再搜一次,去重合并
|
||
try:
|
||
visit_max = get_visit_max(his_session, cn)
|
||
mzh = get_outpatient_no(his_session, cn, visit_max)
|
||
except Exception as e:
|
||
mzh = ''
|
||
print(f" [{cn}] 获取门诊号失败: {e}")
|
||
|
||
if mzh:
|
||
stats['outpatient_found'] += 1
|
||
prs2, truncated2 = search_pathology_records(scraper, mzh)
|
||
if truncated2:
|
||
print(f" [{cn}] 警告: 按门诊号{mzh}搜到的某个类别报告超过1页,只抓取了第1页,可能有遗漏!")
|
||
existing_nos = {r.get('检查号') for r in prs}
|
||
for r in prs2:
|
||
if r.get('检查号') not in existing_nos:
|
||
r['查询类型'] = '门诊'
|
||
prs.append(r)
|
||
existing_nos.add(r.get('检查号'))
|
||
stats['outpatient_extra_reports'] += 1
|
||
|
||
if not prs:
|
||
stats['no_patho'] += 1
|
||
continue
|
||
|
||
pd_dir = os.path.join(OUTPUT_ROOT, cn)
|
||
os.makedirs(pd_dir, exist_ok=True)
|
||
|
||
items = []
|
||
for p in prs:
|
||
d = extract_report_details(scraper, p['报告链接'])
|
||
items.append((p, d))
|
||
stats['report_count'] += 1
|
||
|
||
save_patient_reports(pd_dir, "病理报告", items, scraper)
|
||
|
||
stats['success'] += 1
|
||
print(f" [{cn}] 保存 {len(prs)} 份病理报告(门诊号={mzh or '无'})")
|
||
|
||
except Exception as e:
|
||
print(f" [{cn}] 处理失败: {e}")
|
||
stats['failed'] += 1
|
||
|
||
write_progress(idx + 1, total, stats, cn, start_time)
|
||
|
||
time.sleep(0.2)
|
||
|
||
scraper.close()
|
||
write_progress(total, total, stats, '', start_time, done=True)
|
||
|
||
print(f"\n{'=' * 60}")
|
||
print(f"完成!耗时: {time.time() - start_time:.0f}秒")
|
||
print(f"总患者数: {total}")
|
||
print(f"有病理报告的患者: {stats['success']}")
|
||
print(f"无检查记录/无病理报告: {stats['no_record'] + stats['no_patho']}")
|
||
print(f"抓取失败: {stats['failed']}")
|
||
print(f"病理报告总数: {stats['report_count']}")
|
||
print(f"找到门诊号的患者: {stats['outpatient_found']}")
|
||
print(f"通过门诊号额外补到的报告数: {stats['outpatient_extra_reports']}")
|
||
print(f"可能有遗漏(单次搜索超过20条/1页)的患者: {stats['truncated']}")
|
||
print(f"报告保存路径: {OUTPUT_ROOT}\\<病历号>\\病理报告\\")
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|