"""Build prompt QC samples for the de-identified new-data manifest.""" from __future__ import annotations import argparse import html import io import math import re import tarfile from pathlib import Path from typing import Any import pandas as pd from PIL import Image, ImageOps DEFAULT_MANIFEST = Path( "/data/team/lisicheng/new_data_manifest/" "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet" ) DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_qc") MODALITY_TEXT = { "fundus_color": "color fundus photograph", "oct_bscan": "OCT B-scan", "octa": "optical coherence tomography angiography image", "ffa": "fluorescein fundus angiography image", "bscan_us": "ocular B-scan ultrasound image", "ubm": "ultrasound biomicroscopy image", "uwf": "ultra-widefield fundus photograph", } BANNED_PROMPT_TERMS = { "tongren", "xiangya", "yinhai", "chengdu", "eryuan", "handan", "data0410", "hcw", "fq_unlabeled", "mixed_unlabeled", "octbuckets", "train", "test", "internal_test", "external_test", "unlabeled", } DIAG_MAP = { "amd": "age-related macular degeneration", "年龄相关性黄斑变性": "age-related macular degeneration", "老年性黄斑变性": "age-related macular degeneration", "dr": "diabetic retinopathy", "糖尿病视网膜病变": "diabetic retinopathy", "糖网": "diabetic retinopathy", "normal": "normal", "正常": "normal", "rvo": "retinal vein occlusion", "视网膜静脉阻塞": "retinal vein occlusion", "csc": "central serous chorioretinopathy", "中心性浆液性脉络膜视网膜病变": "central serous chorioretinopathy", "中浆": "central serous chorioretinopathy", "erm": "epiretinal membrane", "黄斑前膜": "epiretinal membrane", "mh": "macular hole", "黄斑裂孔": "macular hole", "rao": "retinal artery occlusion", "视网膜动脉阻塞": "retinal artery occlusion", "rd": "retinal detachment", "视网膜脱离": "retinal detachment", "vkh": "Vogt-Koyanagi-Harada disease", "葡萄膜炎": "uveitis", "青光眼": "glaucoma", "白内障": "cataract", } FINDING_RULES = [ (re.compile(r"玻璃体混浊|中低回声光点|中低回声光斑"), "vitreous opacity"), (re.compile(r"玻璃体积血"), "vitreous hemorrhage"), (re.compile(r"玻璃体后脱离"), "posterior vitreous detachment"), (re.compile(r"后巩膜葡萄肿"), "posterior staphyloma"), (re.compile(r"视网膜脱离"), "retinal detachment"), (re.compile(r"视网膜裂孔"), "retinal tear"), (re.compile(r"眼内占位|占位性病变"), "intraocular mass"), (re.compile(r"脉络膜黑色素瘤"), "choroidal melanoma"), (re.compile(r"硅油眼"), "silicone oil eye"), (re.compile(r"黄斑囊样水肿|黄斑水肿|囊样水肿"), "macular edema"), (re.compile(r"黄斑前膜"), "epiretinal membrane"), (re.compile(r"黄斑裂孔"), "macular hole"), (re.compile(r"分支静脉阻塞"), "branch retinal vein occlusion"), (re.compile(r"视网膜静脉阻塞|静脉阻塞"), "retinal vein occlusion"), (re.compile(r"视网膜动脉阻塞|动脉阻塞"), "retinal artery occlusion"), (re.compile(r"糖尿病视网膜病变|糖网"), "diabetic retinopathy"), (re.compile(r"高血压视网膜病变"), "hypertensive retinopathy"), (re.compile(r"新生血管|CNV", re.I), "neovascularization"), (re.compile(r"荧光渗漏|渗漏"), "fluorescein leakage"), (re.compile(r"无灌注"), "capillary nonperfusion"), (re.compile(r"微动脉瘤"), "microaneurysms"), (re.compile(r"硬性渗出|硬渗"), "hard exudates"), (re.compile(r"棉絮斑"), "cotton-wool spots"), (re.compile(r"出血"), "retinal hemorrhage"), (re.compile(r"视盘.*高荧光|视盘.*渗漏"), "optic disc leakage"), (re.compile(r"房角开放"), "open anterior chamber angle"), (re.compile(r"房角偏窄|窄房角|房角狭窄"), "narrow anterior chamber angle"), (re.compile(r"虹膜平坦"), "flat iris configuration"), (re.compile(r"睫状体.*囊|囊样暗区|囊样无回声区"), "ciliary body cyst"), (re.compile(r"晶体内回声增强"), "lens opacity"), (re.compile(r"前房.*浅"), "shallow anterior chamber"), ] PII_PATTERNS = [ re.compile(r"(姓名|患者姓名|病人姓名|name)\s*[::]?\s*[\u4e00-\u9fffA-Za-z·]{1,8}", re.I), re.compile(r"(ID号|\bID\b|编号|住院号|门诊号|检查号|patient\s*id)\s*[::]?\s*[A-Za-z0-9_-]+", re.I), re.compile(r"(检查日期|出生日期|DOB)\s*[::]?\s*\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?", re.I), re.compile(r"\b\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?\b"), re.compile(r"\b\d{8,}\b"), ] def clean_text(text: Any) -> str: if text is None: return "" if isinstance(text, float) and math.isnan(text): return "" out = str(text) for pattern in PII_PATTERNS: out = pattern.sub("", out) out = re.sub(r"(医师签名|医生签名|签名|建议门诊|门诊时间).*", "", out, flags=re.I) out = re.sub(r"(待删|删除)", "", out) out = re.sub(r"\s+", " ", out) out = re.sub(r"[,。;;,\s]+$", "", out) return out.strip(" ,。;;,") def build_prompts(row: dict[str, Any]) -> dict[str, str]: modality = str(row.get("modality") or "") base = base_prompt(row, modality) descriptors = _clinical_descriptors(row) demographics = _demographics(row) short_parts = [base] medium_parts = [base] + demographics + descriptors[:3] dense_parts = [base] + demographics + descriptors[:8] return { "short": _join(short_parts), "medium": _join(medium_parts), "dense": _join(dense_parts), } def base_prompt(row: dict[str, Any], modality: str) -> str: if str(row.get("cohort") or "") == "tongren_external_fundus": return "anterior segment photograph" return MODALITY_TEXT.get(modality, f"{modality.replace('_', ' ')} ophthalmic image") def main() -> None: args = parse_args() args.out.mkdir(parents=True, exist_ok=True) (args.out / "imgs").mkdir(exist_ok=True) df = pd.read_parquet(args.manifest) df = df[df.get("split", "train") == "train"].copy() if "split" in df.columns else df.copy() for col in ["center", "modality"]: if col not in df.columns: raise KeyError(f"manifest missing {col!r}") samples = sample_by_center_modality(df, args.per_group, args.seed) records = [] caption_rows = [] for idx, row in enumerate(samples.to_dict("records")): prompts = build_prompts(row) for level, prompt in prompts.items(): caption_rows.append( {"image_id": row["image_id"], "level": level, "prompt_text": prompt} ) image_rel = render_thumb(row, args.out / "imgs", idx, args.thumb) record = { "idx": idx, "image_rel": image_rel, "prompts": prompts, **{k: row.get(k) for k in [ "image_id", "center", "modality", "cohort", "diagnosis_raw", "group_raw", "diagnosis_group", "caption", "train_path", "pii_masked", "ocr_age", "ocr_sex", "ocr_eye", ]}, } records.append(record) caps = pd.DataFrame(caption_rows) caps.to_parquet(args.out / "prompt_qc_captions.parquet", index=False) caps.to_csv(args.out / "prompt_qc_captions.csv", index=False) write_html(records, args.out / "prompt_qc.html") write_design(args.out / "prompt_design.md") print(f"DONE -> {args.out / 'prompt_qc.html'} ({len(records)} samples)") def sample_by_center_modality(df: pd.DataFrame, n: int, seed: int) -> pd.DataFrame: groups = [] for (_, _), group in df.groupby(["center", "modality"], dropna=False): groups.append(group.sample(n=min(n, len(group)), random_state=seed)) out = pd.concat(groups, ignore_index=True) return out.sort_values(["modality", "center", "cohort", "image_id"]).reset_index(drop=True) def render_thumb(row: dict[str, Any], img_dir: Path, idx: int, size: int) -> str: path = str(row.get("train_path") or row.get("file_path")) name = f"{idx:04d}_{safe_name(row.get('modality'))}_{safe_name(row.get('center'))}.jpg" out = img_dir / name try: if "::" in path: im = open_wds_member(path).convert("RGB") else: im = Image.open(path).convert("RGB") im.thumbnail((size, size), Image.Resampling.LANCZOS) canvas = Image.new("RGB", (size, size), (0, 0, 0)) canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2)) im = canvas im.save(out, quality=90) except Exception: im = Image.new("RGB", (size, size), (80, 20, 20)) im = ImageOps.expand(im, border=2, fill=(255, 0, 0)) im.save(out, quality=90) return f"imgs/{name}" def open_wds_member(path: str) -> Image.Image: tar_path, member_name = path.split("::", 1) with tarfile.open(tar_path, "r:*") as tf: member = tf.getmember(member_name) fp = tf.extractfile(member) if fp is None: raise FileNotFoundError(path) data = fp.read() return Image.open(io.BytesIO(data)) def write_html(records: list[dict[str, Any]], out: Path) -> None: css = """ body{font-family:Arial,sans-serif;margin:20px;background:#f7f7f7;color:#222} .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(460px,1fr));gap:14px} .card{background:white;border:1px solid #ddd;border-radius:6px;padding:12px} img{width:180px;height:180px;object-fit:contain;background:#000;float:left;margin-right:12px} .meta{font-size:12px;color:#555;line-height:1.35} .prompt{font-size:13px;margin:6px 0}.level{font-weight:bold;color:#333} .caption{clear:both;font-size:12px;color:#555;border-top:1px solid #eee;margin-top:10px;padding-top:8px} h1{margin-bottom:4px}.note{color:#555;margin-bottom:18px} """ parts = [ "
", f"", "