Dataset / data_processing /02_quality_control /build_hcw_semantic_patch.py
Kaphathy's picture
Add standalone data_processing directory with per-script dataset mapping and detailed purpose comments
fe5b36e verified
Raw History Blame Contribute Delete
13.5 kB
"""
================================================================================
脚本名称 (Script Name): build_hcw_semantic_patch.py
原本用途 (Original Purpose):
隐私安全的 HCW 眼底诊断侧卡(Sidecar Patch)与 Caption 生成脚本。完全剥离患者住院号、就诊日期、自由病历文本等隐私字段,只保留合规图像 ID、ICD 编码与主诊断,生成轻量化 Parquet 标签集。
适用数据集 (Target Dataset):
archives/data0410/ 中的 fundus_hcw / hcw_fundus 眼底大集。
作者与归属 (Author/Provenance):
李思成 (Lisicheng), 浙江大学多模态眼科团队
输入要求 (Input):
胡成伟清洗后的原始工作簿与 release manifest
输出结果 (Output):
去隐私后的结构化诊断 Parquet 侧卡(包含 image_name, diag_name, diag_icd 等)
依赖环境 (Dependencies):
pandas, pyarrow, json
================================================================================
"""
"""Build a privacy-safe HCW fundus diagnosis sidecar and caption patch.
Only image identifiers and clinical label fields are exported. Patient, visit,
date and free-report columns in the source workbooks are never copied.
"""
from __future__ import annotations
import argparse
import json
import re
from collections import Counter
from pathlib import Path
from typing import Any
import pandas as pd
import pyarrow.parquet as pq
COHORT = "hcw_fundus"
BASE_PROMPT = "ophthalmic image, color fundus photography, standard field of view, retina"
SAFE_SOURCE_COLUMNS = {"image_name", "diag_name", "diag_icd", "is_primary"}
def _clean(value: Any) -> str:
if value is None:
return ""
try:
if pd.isna(value):
return ""
except (TypeError, ValueError):
pass
return re.sub(r"\s+", " ", str(value)).strip(" ,,;;")
def _unique(values: list[str]) -> list[str]:
result: list[str] = []
seen: set[str] = set()
for value in values:
value = _clean(value)
key = value.casefold()
if value and key not in seen:
result.append(value)
seen.add(key)
return result
def _load_release(path: Path, batch_size: int) -> pd.DataFrame:
parts: list[pd.DataFrame] = []
parquet = pq.ParquetFile(path)
columns = ["image_id", "file_path", "cohort", "diagnosis_group_clean"]
missing = set(columns) - set(parquet.schema_arrow.names)
if missing:
raise ValueError(f"release manifest missing columns: {sorted(missing)}")
for batch in parquet.iter_batches(columns=columns, batch_size=batch_size):
frame = batch.to_pandas()
frame = frame[frame["cohort"].eq(COHORT)]
if not frame.empty:
parts.append(frame)
if not parts:
raise ValueError(f"release manifest contains no {COHORT} rows")
release = pd.concat(parts, ignore_index=True)
if len(release) != release["image_id"].nunique():
raise ValueError("release HCW image_id is not unique")
release["stem"] = release["file_path"].map(lambda value: Path(str(value)).stem)
if release["stem"].duplicated().any():
raise ValueError("release HCW file stems are not unique")
return release
def _load_workbook(path: Path, source_name: str) -> pd.DataFrame:
frame = pd.read_excel(path, keep_default_na=False)
missing = SAFE_SOURCE_COLUMNS - set(frame.columns)
if missing:
raise ValueError(f"{path} missing columns: {sorted(missing)}")
safe = frame[list(SAFE_SOURCE_COLUMNS)].copy()
safe["stem"] = safe["image_name"].map(lambda value: Path(str(value)).stem)
safe["diag_name"] = safe["diag_name"].map(_clean)
safe["diag_icd"] = safe["diag_icd"].map(_clean)
safe["is_primary"] = safe["is_primary"].astype(str).str.strip().eq("是")
safe["source_table"] = source_name
safe = safe[safe["stem"].ne("") & safe["diag_name"].ne("")]
return safe.drop(columns=["image_name"])
def _dram_labels(name: str, icd: str) -> tuple[list[str], list[str], list[str]]:
text = f"{name} {icd}".casefold()
families: list[str] = []
subtypes: list[str] = []
findings: list[str] = []
if "糖尿病" in text or "糖尿病视网膜" in text or "h36" in text:
families.append("diabetic retinopathy")
if "增殖" in text:
subtypes.append("proliferative diabetic retinopathy")
elif "背景" in text or "斑点" in text:
subtypes.append("non-proliferative diabetic retinopathy")
if "分支静脉阻塞" in text:
families.append("retinal vein occlusion")
subtypes.append("branch retinal vein occlusion")
elif "中心性静脉阻塞" in text or "中央静脉阻塞" in text:
families.append("retinal vein occlusion")
subtypes.append("central retinal vein occlusion")
elif "静脉阻塞" in text:
families.append("retinal vein occlusion")
if "老年性黄斑变性" in text:
families.append("age-related macular degeneration")
if "渗出性" in text:
subtypes.append("neovascular age-related macular degeneration")
elif "萎缩性" in text:
subtypes.append("non-neovascular age-related macular degeneration")
if "黄斑水肿" in text or "视网膜增厚" in text:
findings.append("macular edema")
if "牵拉性视网膜脱离" in text:
findings.append("tractional retinal detachment")
if "玻璃体出血" in text:
findings.append("vitreous hemorrhage")
return _unique(families), _unique(subtypes), _unique(findings)
GLAUCOMA_TERMS = re.compile(
r"青光眼|闭角|开角|新生血管|继发|先天|青少年|发育|正常眼压|色素|"
r"睫状体炎|眼压失控|恶性|无晶状体|晶状体脱位|血影细胞"
)
def _glaucoma_labels(name: str, icd: str) -> tuple[list[str], list[str], list[str]]:
text = f"{name} {icd}".casefold()
glaucoma_evidence = bool(
GLAUCOMA_TERMS.search(text)
or re.search(r"\b(?:h40|h42|q15)", text, re.I)
)
if not glaucoma_evidence:
return [], [], []
families = ["glaucoma"]
subtypes: list[str] = []
if "新生血管" in text:
subtypes.append("neovascular glaucoma")
if "闭角" in text:
subtypes.append("angle-closure glaucoma")
if "开角" in text:
subtypes.append("open-angle glaucoma")
if "继发" in text:
subtypes.append("secondary glaucoma")
if "先天" in text or "发育" in text or "青少年" in text or icd.upper().startswith("Q15"):
subtypes.append("developmental glaucoma")
if "正常眼压" in text:
subtypes.append("normal-tension glaucoma")
if "色素" in text:
subtypes.append("pigmentary glaucoma")
return families, _unique(subtypes), []
def _aggregate_labels(group: pd.DataFrame) -> dict[str, Any]:
families: list[str] = []
subtypes: list[str] = []
findings: list[str] = []
for row in group.itertuples(index=False):
if row.source_table == "dramdrvo_cleaned.xlsx":
result = _dram_labels(row.diag_name, row.diag_icd)
else:
result = _glaucoma_labels(row.diag_name, row.diag_icd)
families.extend(result[0])
subtypes.extend(result[1])
findings.extend(result[2])
primary = group[group["is_primary"]]
primary_row = primary.iloc[0] if not primary.empty else group.iloc[0]
return {
"source_tables": _unique(group["source_table"].tolist()),
"diagnosis_raw": _unique(group["diag_name"].tolist()),
"diagnosis_icd": _unique(group["diag_icd"].tolist()),
"primary_diagnosis_raw": _clean(primary_row["diag_name"]),
"primary_diagnosis_icd": _clean(primary_row["diag_icd"]),
"diagnosis_families": _unique(families),
"diagnosis_subtypes": _unique(subtypes),
"finding_tags": _unique(findings),
}
def _prompt_rows(row: pd.Series) -> list[dict[str, str]]:
families = list(row["diagnosis_families"])
subtypes = list(row["diagnosis_subtypes"])
findings = list(row["finding_tags"])
medium_parts = [BASE_PROMPT, *(f"diagnosis: {value}" for value in families)]
dense_parts = [
*medium_parts,
*(f"subtype: {value}" for value in subtypes),
*findings,
]
prompts = {
"short": BASE_PROMPT,
"medium": ", ".join(_unique(medium_parts)),
"dense": ", ".join(_unique(dense_parts)),
}
image_id = str(row["image_id"])
return [
{
"caption_id": f"{image_id}_{level}",
"image_id": image_id,
"level": level,
"prompt_text": prompt,
"language": "en",
"generator": "ophgen_semantic_patch_hcw_v1",
"grounded_in": "v10.1+hcw_cleaned_diagnosis_tables+canonical_taxonomy_v1",
}
for level, prompt in prompts.items()
]
def build(args: argparse.Namespace) -> None:
args.out.mkdir(parents=True, exist_ok=True)
release = _load_release(args.release_manifest, args.batch_size)
workbooks = pd.concat(
[
_load_workbook(args.dramdrvo, "dramdrvo_cleaned.xlsx"),
_load_workbook(args.glaucoma, "glaucoma_cleaned.xlsx"),
],
ignore_index=True,
)
release_stems = set(release["stem"])
workbooks = workbooks[workbooks["stem"].isin(release_stems)].copy()
workbook_stems = set(workbooks["stem"])
missing_stems = release_stems - workbook_stems
if missing_stems:
raise ValueError(f"{len(missing_stems)} release HCW images lack a cleaned diagnosis join")
records: list[dict[str, Any]] = []
for stem, group in workbooks.groupby("stem", sort=False):
records.append({"stem": stem, **_aggregate_labels(group)})
semantics = release.merge(
pd.DataFrame(records), on="stem", how="left", validate="one_to_one"
)
semantics["prompt_eligible"] = semantics["diagnosis_families"].map(bool)
eligible = semantics[semantics["prompt_eligible"]].copy()
if eligible.empty:
raise ValueError("no HCW images have prompt-eligible canonical diagnoses")
safe_columns = [
"image_id",
"cohort",
"source_tables",
"diagnosis_raw",
"diagnosis_icd",
"primary_diagnosis_raw",
"primary_diagnosis_icd",
"diagnosis_families",
"diagnosis_subtypes",
"finding_tags",
"diagnosis_group_clean",
"prompt_eligible",
]
semantics[safe_columns].to_parquet(args.out / "hcw_image_semantics.parquet", index=False)
caption_rows: list[dict[str, str]] = []
for _, row in eligible.iterrows():
caption_rows.extend(_prompt_rows(row))
captions = pd.DataFrame(caption_rows)
captions.to_parquet(args.out / "hcw_caption_patch.parquet", index=False)
family_counts = Counter(
family for families in eligible["diagnosis_families"] for family in families
)
subtype_counts = Counter(
subtype for subtypes in eligible["diagnosis_subtypes"] for subtype in subtypes
)
summary_rows = [
{"label_type": "family", "label": label, "images": count}
for label, count in family_counts.items()
] + [
{"label_type": "subtype", "label": label, "images": count}
for label, count in subtype_counts.items()
]
pd.DataFrame(summary_rows).sort_values(
["label_type", "images", "label"], ascending=[True, False, True]
).to_csv(args.out / "hcw_class_summary.csv", index=False)
source_stems = {
source: int(workbooks.loc[workbooks["source_table"].eq(source), "stem"].nunique())
for source in sorted(workbooks["source_table"].unique())
}
level_counts = captions["level"].value_counts().to_dict()
validation = {
"source_read_only": True,
"release_hcw_images": int(len(release)),
"release_hcw_unique_stems": int(release["stem"].nunique()),
"cleaned_workbook_joined_stems": source_stems,
"cleaned_workbook_union_stems": int(workbooks["stem"].nunique()),
"cleaned_workbook_overlap_stems": int(
workbooks.groupby("stem")["source_table"].nunique().gt(1).sum()
),
"prompt_eligible_images": int(len(eligible)),
"prompt_ineligible_images": int(len(semantics) - len(eligible)),
"current_diagnosis_nonempty": int(
semantics["diagnosis_group_clean"].fillna("").astype(str).str.strip().ne("").sum()
),
"patched_caption_rows": int(len(captions)),
"patched_caption_level_counts": {key: int(value) for key, value in level_counts.items()},
"output_columns": safe_columns,
"pii_columns_exported": False,
"output_type": "privacy-safe sidecar and caption delta; source files were not modified",
}
(args.out / "validation.json").write_text(
json.dumps(validation, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(json.dumps(validation, ensure_ascii=False, indent=2))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--release-manifest", type=Path, required=True)
parser.add_argument("--dramdrvo", type=Path, required=True)
parser.add_argument("--glaucoma", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--batch-size", type=int, default=250_000)
return parser.parse_args()
if __name__ == "__main__":
build(parse_args())