Kaphathy commited on
Commit
fe5b36e
·
verified ·
1 Parent(s): d2ce7dd

Add standalone data_processing directory with per-script dataset mapping and detailed purpose comments

Browse files
Files changed (25) hide show
  1. data_processing/01_deidentification/audit_fundus_corner_pii.py +309 -0
  2. data_processing/01_deidentification/crop_fundus_images.py +138 -0
  3. data_processing/01_deidentification/deidentify_batch.py +519 -0
  4. data_processing/01_deidentification/deidentify_trial.py +439 -0
  5. data_processing/01_deidentification/fundus_pii_trial.py +203 -0
  6. data_processing/01_deidentification/test_deidentify_trial.py +208 -0
  7. data_processing/02_quality_control/asrm_preprocess.py +298 -0
  8. data_processing/02_quality_control/build_hcw_semantic_patch.py +336 -0
  9. data_processing/02_quality_control/build_quality_risk_review.py +403 -0
  10. data_processing/02_quality_control/clean_excel.py +70 -0
  11. data_processing/02_quality_control/filter_prompt_artifacts.py +173 -0
  12. data_processing/02_quality_control/prompt_qc.py +480 -0
  13. data_processing/02_quality_control/resize_mode_qc.py +125 -0
  14. data_processing/02_quality_control/scan_eyepacs_edge_artifact.py +520 -0
  15. data_processing/03_report_parsing/attach_labels.py +181 -0
  16. data_processing/03_report_parsing/batch_retrieve_reports.py +488 -0
  17. data_processing/03_report_parsing/cohorts.py +201 -0
  18. data_processing/03_report_parsing/materialize_newdata_prompts.py +555 -0
  19. data_processing/04_modality_split/split_octbuckets_octa_review.py +381 -0
  20. data_processing/05_taxonomy_and_prompts/build_clean_captions.py +85 -0
  21. data_processing/05_taxonomy_and_prompts/build_mixed_v5_taxonomy.py +502 -0
  22. data_processing/05_taxonomy_and_prompts/build_mixed_v6_taxonomy.py +488 -0
  23. data_processing/05_taxonomy_and_prompts/test_build_mixed_v6_taxonomy.py +100 -0
  24. data_processing/05_taxonomy_and_prompts/test_taxonomy_sampling.py +72 -0
  25. data_processing/README.md +123 -0
data_processing/01_deidentification/audit_fundus_corner_pii.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): audit_fundus_corner_pii.py
4
+ 原本用途 (Original Purpose):
5
+ 脱敏图像隐私合规自动化复审与审计脚本。通过深度光学字符识别(OCR)与图像四角非零像素密度分析,高召回检测脱敏后的眼底图像是否仍有残留的患者个人身份信息(PII)。
6
+ 适用数据集 (Target Dataset):
7
+ 脱敏处理后的各中心彩色眼底图库(CFP / UWF),用于在对外公开或模型训练前进行数据合规质检。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 已脱敏图像目录与对应的 Manifest 清单文件
12
+ 输出结果 (Output):
13
+ PII 审计报告与可疑残余文字样本的复审清单(CSV/HTML)
14
+ 依赖环境 (Dependencies):
15
+ easyocr, pyarrow, pandas, pillow, numpy
16
+ ================================================================================
17
+ """
18
+
19
+ """Audit fundus-like cohorts for residual top-left burned-in PII.
20
+
21
+ This script samples images from a prompt-adapter manifest, computes a fast
22
+ top-left white-text proxy, optionally runs OCR on top candidates, and writes a
23
+ review HTML. It never modifies source images and never stores raw OCR text.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import base64
30
+ import io
31
+ import json
32
+ import math
33
+ import tarfile
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ import cv2
38
+ import numpy as np
39
+ import pandas as pd
40
+ from PIL import Image
41
+
42
+
43
+ DEFAULT_MANIFEST = Path(
44
+ "/data/team/lisicheng/new_data_manifest/"
45
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/adapter_manifest_mixed_v6.parquet"
46
+ )
47
+ DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/fundus_corner_pii_audit_20260709")
48
+ DEFAULT_COHORTS = [
49
+ "tongren_fundus",
50
+ "tongren_95disease_fundus",
51
+ "fundus90wer",
52
+ "fq_rawfundus",
53
+ "fq_testfundus",
54
+ "tongren_external_fundus",
55
+ "eryuan_t17_fundus",
56
+ "hcw_fundus",
57
+ "eyfrd6_fundus",
58
+ ]
59
+
60
+
61
+ class ImageOpener:
62
+ def __init__(self) -> None:
63
+ self._tar_cache: dict[str, tarfile.TarFile] = {}
64
+
65
+ def close(self) -> None:
66
+ for tf in self._tar_cache.values():
67
+ tf.close()
68
+ self._tar_cache.clear()
69
+
70
+ def open(self, path: str) -> Image.Image:
71
+ if "::" not in path:
72
+ return Image.open(path).convert("RGB")
73
+ tar_path, member = path.split("::", 1)
74
+ tf = self._tar_cache.get(tar_path)
75
+ if tf is None:
76
+ tf = tarfile.open(tar_path, "r:*")
77
+ self._tar_cache[tar_path] = tf
78
+ fh = tf.extractfile(member)
79
+ if fh is None:
80
+ raise FileNotFoundError(member)
81
+ return Image.open(io.BytesIO(fh.read())).convert("RGB")
82
+
83
+
84
+ def top_left_text_proxy(im: Image.Image, top_ratio: float, left_ratio: float) -> dict[str, float]:
85
+ arr = np.asarray(im.convert("RGB"), dtype=np.float32)
86
+ h, w = arr.shape[:2]
87
+ crop = arr[: max(1, int(h * top_ratio)), : max(1, int(w * left_ratio))]
88
+ gray = crop.mean(axis=2)
89
+ white = (crop[..., 0] > 180) & (crop[..., 1] > 180) & (crop[..., 2] > 180)
90
+ dx = np.abs(np.diff(gray, axis=1))
91
+ dy = np.abs(np.diff(gray, axis=0)) if gray.shape[0] > 1 else np.zeros_like(dx)
92
+ edge_density = float(((dx > 18).mean() + (dy > 18).mean()) / 2.0)
93
+ white_fraction = float(white.mean())
94
+ return {
95
+ "corner_white_fraction": round(white_fraction, 6),
96
+ "corner_edge_density": round(edge_density, 6),
97
+ "corner_gray_std": round(float(gray.std()), 4),
98
+ "corner_text_score": round(float(white_fraction * 100.0 + edge_density * 10.0), 6),
99
+ }
100
+
101
+
102
+ def likely_text(stats: dict[str, float]) -> bool:
103
+ return (
104
+ stats["corner_white_fraction"] >= 0.01
105
+ and stats["corner_edge_density"] >= 0.006
106
+ and stats["corner_gray_std"] >= 15.0
107
+ )
108
+
109
+
110
+ def load_ocr_reader(enable: bool) -> object | None:
111
+ if not enable:
112
+ return None
113
+ import easyocr
114
+
115
+ return easyocr.Reader(["ch_sim", "en"], gpu=True)
116
+
117
+
118
+ def run_ocr(reader: object | None, im: Image.Image, top_ratio: float, left_ratio: float) -> dict[str, Any]:
119
+ if reader is None:
120
+ return {
121
+ "ocr_checked": False,
122
+ "ocr_box_count": 0,
123
+ "ocr_has_age": False,
124
+ "ocr_has_sex": False,
125
+ "ocr_has_chinese": False,
126
+ "ocr_has_any_text": False,
127
+ }
128
+ arr = np.asarray(im.convert("RGB"))
129
+ h, w = arr.shape[:2]
130
+ crop = arr[: max(1, int(h * top_ratio)), : max(1, int(w * left_ratio))]
131
+ results = reader.readtext(crop, detail=1)
132
+ detected_text = " ".join(str(item[1]) for item in results if len(item) >= 2)
133
+ return {
134
+ "ocr_checked": True,
135
+ "ocr_box_count": int(len(results)),
136
+ "ocr_has_age": bool(("岁" in detected_text) or any(str(i) in detected_text for i in range(1, 100))),
137
+ "ocr_has_sex": bool(("男" in detected_text) or ("女" in detected_text)),
138
+ "ocr_has_chinese": bool(any("\u4e00" <= ch <= "\u9fff" for ch in detected_text)),
139
+ "ocr_has_any_text": bool(detected_text.strip()),
140
+ }
141
+
142
+
143
+ def thumb_data(im: Image.Image, size: int) -> str:
144
+ thumb = im.copy()
145
+ thumb.thumbnail((size, size), Image.Resampling.LANCZOS)
146
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
147
+ canvas.paste(thumb, ((size - thumb.width) // 2, (size - thumb.height) // 2))
148
+ buf = io.BytesIO()
149
+ canvas.save(buf, format="JPEG", quality=86)
150
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
151
+
152
+
153
+ def json_safe(value: Any) -> Any:
154
+ if isinstance(value, dict):
155
+ return {str(k): json_safe(v) for k, v in value.items()}
156
+ if isinstance(value, list | tuple):
157
+ return [json_safe(v) for v in value]
158
+ if isinstance(value, np.integer):
159
+ return int(value)
160
+ if isinstance(value, np.floating):
161
+ value = float(value)
162
+ if isinstance(value, float):
163
+ return value if math.isfinite(value) else None
164
+ try:
165
+ if pd.isna(value):
166
+ return None
167
+ except (TypeError, ValueError):
168
+ pass
169
+ return value
170
+
171
+
172
+ def audit(args: argparse.Namespace) -> tuple[list[dict[str, Any]], dict[str, Any]]:
173
+ df = pd.read_parquet(
174
+ args.manifest,
175
+ columns=["image_id", "cohort", "modality", "modality_subtype", "file_path"],
176
+ )
177
+ df = df[df["cohort"].astype(str).isin(args.cohorts)].copy()
178
+ sampled = []
179
+ for cohort, group in df.groupby("cohort", sort=True):
180
+ sampled.append(group.sample(n=min(args.per_cohort, len(group)), random_state=args.seed))
181
+ sample = pd.concat(sampled, ignore_index=True) if sampled else df.head(0)
182
+
183
+ opener = ImageOpener()
184
+ rows: list[dict[str, Any]] = []
185
+ try:
186
+ for i, row in enumerate(sample.to_dict("records"), start=1):
187
+ rec = {k: row.get(k) for k in row}
188
+ rec["decode_error"] = ""
189
+ try:
190
+ im = opener.open(str(row["file_path"]))
191
+ rec.update(top_left_text_proxy(im, args.top_ratio, args.left_ratio))
192
+ rec["likely_corner_text"] = likely_text(rec)
193
+ rec["_image"] = im
194
+ except Exception as exc:
195
+ rec["decode_error"] = repr(exc)
196
+ rec["likely_corner_text"] = False
197
+ rec["corner_white_fraction"] = None
198
+ rec["corner_edge_density"] = None
199
+ rec["corner_gray_std"] = None
200
+ rec["corner_text_score"] = None
201
+ rec["_image"] = None
202
+ rows.append(rec)
203
+ if i % 200 == 0:
204
+ print(f"[scan] {i}/{len(sample)}", flush=True)
205
+ finally:
206
+ opener.close()
207
+
208
+ rows.sort(key=lambda r: (str(r.get("cohort")), -(r.get("corner_text_score") or 0.0)))
209
+ ocr_targets: list[dict[str, Any]] = []
210
+ for _, group in pd.DataFrame([{k: v for k, v in r.items() if k != "_image"} for r in rows]).groupby("cohort", sort=True):
211
+ ids = set(group.sort_values("corner_text_score", ascending=False).head(args.ocr_top_per_cohort)["image_id"].astype(str))
212
+ ocr_targets.extend([r for r in rows if str(r["image_id"]) in ids])
213
+
214
+ reader = load_ocr_reader(args.ocr)
215
+ target_ids = {str(r["image_id"]) for r in ocr_targets}
216
+ for rec in rows:
217
+ if str(rec["image_id"]) in target_ids and rec.get("_image") is not None:
218
+ rec.update(run_ocr(reader, rec["_image"], args.top_ratio, args.left_ratio))
219
+ else:
220
+ rec.update(run_ocr(None, None, args.top_ratio, args.left_ratio))
221
+
222
+ html_records = []
223
+ for _, group in pd.DataFrame([{k: v for k, v in r.items() if k != "_image"} for r in rows]).groupby("cohort", sort=True):
224
+ ids = set(group.sort_values("corner_text_score", ascending=False).head(args.html_top_per_cohort)["image_id"].astype(str))
225
+ html_records.extend([r for r in rows if str(r["image_id"]) in ids])
226
+ for rec in html_records:
227
+ im = rec.get("_image")
228
+ rec["thumb_data"] = thumb_data(im, args.thumb_size) if im is not None else ""
229
+
230
+ clean_rows = [{k: v for k, v in r.items() if k != "_image"} for r in rows]
231
+ clean_html = [{k: v for k, v in r.items() if k != "_image"} for r in html_records]
232
+ data = pd.DataFrame(clean_rows)
233
+ summary = {
234
+ "manifest": str(args.manifest),
235
+ "rows_sampled": int(len(clean_rows)),
236
+ "per_cohort": int(args.per_cohort),
237
+ "likely_corner_text_total": int(data["likely_corner_text"].sum()) if len(data) else 0,
238
+ "decode_errors": int(data["decode_error"].fillna("").astype(str).ne("").sum()) if len(data) else 0,
239
+ "by_cohort": data.groupby("cohort").agg(
240
+ sampled=("image_id", "count"),
241
+ likely_corner_text=("likely_corner_text", "sum"),
242
+ mean_corner_text_score=("corner_text_score", "mean"),
243
+ max_corner_text_score=("corner_text_score", "max"),
244
+ ocr_checked=("ocr_checked", "sum"),
245
+ ocr_has_any_text=("ocr_has_any_text", "sum"),
246
+ ocr_has_chinese=("ocr_has_chinese", "sum"),
247
+ ocr_has_age=("ocr_has_age", "sum"),
248
+ ocr_has_sex=("ocr_has_sex", "sum"),
249
+ ).reset_index().to_dict("records")
250
+ if len(data)
251
+ else [],
252
+ }
253
+ return clean_rows, {"summary": summary, "html_records": clean_html}
254
+
255
+
256
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
257
+ rows_json = json.dumps(json_safe(records), ensure_ascii=False, allow_nan=False).replace("</", "<\\/")
258
+ css = """:root{--bg:#f5f6f8;--panel:#fff;--line:#d8dee8;--text:#1f2937;--muted:#667085;--blue:#0f62fe}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:Arial,"Noto Sans CJK SC","Microsoft YaHei",sans-serif}header{position:sticky;top:0;background:#fff;border-bottom:1px solid var(--line);padding:12px 16px}.viewer{display:grid;grid-template-columns:minmax(440px,52vw) 1fr;gap:14px;padding:14px}.panel{background:#fff;border:1px solid var(--line);border-radius:6px;padding:12px}.imgbox{height:min(68vh,720px);min-height:420px;background:#050505;display:flex;align-items:center;justify-content:center;overflow:hidden}.imgbox img{max-width:100%;max-height:100%;object-fit:contain}.badge{display:inline-block;border-radius:999px;padding:3px 8px;margin:0 5px 6px 0;font-size:12px;background:#edf2ff;color:#173b8f}.bad{background:#ffecec;color:#9b1c1c}.meta{font-size:13px;line-height:1.5;word-break:break-word}.path{font-family:monospace;font-size:12px;color:#334155}button,input{font-size:13px;border:1px solid #b8c0cc;border-radius:4px;background:#fff;padding:7px 9px}button.primary{background:var(--blue);border-color:var(--blue);color:#fff}"""
259
+ js = """
260
+ const rows = JSON.parse(document.getElementById('rows-data').textContent);
261
+ let idx = 0;
262
+ function esc(v) { return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
263
+ function go(delta) { idx=Math.max(0, Math.min(rows.length-1, idx+delta)); render(); }
264
+ function gotoIndex(v) { const n=Number(v); if (Number.isFinite(n)) { idx=Math.max(0, Math.min(rows.length-1, n-1)); render(); } }
265
+ function render() {
266
+ if (!rows.length) { document.getElementById('root').innerHTML='<div class=viewer><div class=panel>没有样本。</div></div>'; return; }
267
+ const r=rows[idx];
268
+ document.getElementById('progress').textContent=`第 ${idx+1} / ${rows.length} 张`;
269
+ document.getElementById('jump').value=idx+1;
270
+ document.getElementById('root').innerHTML=`<section class="viewer"><div class="panel"><div class="imgbox"><img src="${esc(r.thumb_data)}"></div></div><div class="panel"><div><span class="badge ${r.likely_corner_text ? 'bad' : ''}">likely_corner_text=${esc(r.likely_corner_text)}</span><span class="badge">score=${esc(r.corner_text_score)}</span><span class="badge">${esc(r.cohort)}</span></div><div class="meta"><b>image_id</b>: ${esc(r.image_id)}<br><b>modality</b>: ${esc(r.modality_subtype)}<br><b>corner white</b>: ${esc(r.corner_white_fraction)}; <b>edge</b>: ${esc(r.corner_edge_density)}; <b>std</b>: ${esc(r.corner_gray_std)}<br><b>OCR checked</b>: ${esc(r.ocr_checked)}; <b>any</b>: ${esc(r.ocr_has_any_text)}; <b>Chinese</b>: ${esc(r.ocr_has_chinese)}; <b>age</b>: ${esc(r.ocr_has_age)}; <b>sex</b>: ${esc(r.ocr_has_sex)}<br><b>path</b>: <span class="path">${esc(r.file_path)}</span></div></div></section>`;
271
+ }
272
+ document.addEventListener('keydown', ev => { if (ev.key === 'ArrowRight') go(1); else if (ev.key === 'ArrowLeft') go(-1); });
273
+ render();
274
+ """
275
+ doc = f"""<!doctype html><html><head><meta charset="utf-8"><title>Fundus corner PII audit</title><style>{css}</style></head><body><header><h1>Fundus corner PII audit</h1><span id="progress"></span> <button onclick="go(-1)">上一张</button> <button class="primary" onclick="go(1)">下一张</button> <label>跳转 <input id="jump" type="number" min="1" max="{len(records)}" onchange="gotoIndex(this.value)" style="width:80px"></label></header><main id="root"></main><script type="application/json" id="rows-data">{rows_json}</script><script>{js}</script></body></html>"""
276
+ out.write_text(doc, encoding="utf-8")
277
+
278
+
279
+ def parse_args() -> argparse.Namespace:
280
+ parser = argparse.ArgumentParser(description=__doc__)
281
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
282
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
283
+ parser.add_argument("--cohorts", nargs="+", default=DEFAULT_COHORTS)
284
+ parser.add_argument("--per-cohort", type=int, default=400)
285
+ parser.add_argument("--ocr-top-per-cohort", type=int, default=20)
286
+ parser.add_argument("--html-top-per-cohort", type=int, default=30)
287
+ parser.add_argument("--top-ratio", type=float, default=0.18)
288
+ parser.add_argument("--left-ratio", type=float, default=0.20)
289
+ parser.add_argument("--thumb-size", type=int, default=512)
290
+ parser.add_argument("--seed", type=int, default=20260709)
291
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
292
+ return parser.parse_args()
293
+
294
+
295
+ def main() -> None:
296
+ args = parse_args()
297
+ args.out.mkdir(parents=True, exist_ok=True)
298
+ rows, payload = audit(args)
299
+ pd.DataFrame(rows).to_csv(args.out / "corner_pii_sample_stats.csv", index=False)
300
+ (args.out / "summary.json").write_text(
301
+ json.dumps(json_safe(payload["summary"]), ensure_ascii=False, indent=2, allow_nan=False),
302
+ encoding="utf-8",
303
+ )
304
+ write_html(payload["html_records"], args.out / "OPEN_THIS_FUNDUS_CORNER_PII_AUDIT.html")
305
+ print(json.dumps(json_safe(payload["summary"]), ensure_ascii=False), flush=True)
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
data_processing/01_deidentification/crop_fundus_images.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): crop_fundus_images.py
4
+ 原本用途 (Original Purpose):
5
+ 自动轮廓提取与多余黑边裁剪算法。基于图像灰度梯度与外接轮廓算法,精准识别眼底视网膜有效成像区域,裁除四周不对称的大面积无信息黑边,实现画幅居中与尺寸标准化。
6
+ 适用数据集 (Target Dataset):
7
+ 公开眼底图像集 CSDI 以及 zhanghuan_selected_public 中的公开彩色眼底集(如 Messidor, ODIR, DDR 等带有非对称大黑框的公开集)。
8
+ 作者与归属 (Author/Provenance):
9
+ 张焕 (Zhanghuan), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 原始带有不对称大面积黑边的眼底相片
12
+ 输出结果 (Output):
13
+ 紧密贴合有效视网膜圆形视野、居中标准化的裁切图像
14
+ 依赖环境 (Dependencies):
15
+ opencv-python, numpy, pillow
16
+ ================================================================================
17
+ """
18
+
19
+ import cv2
20
+ import numpy as np
21
+ import os
22
+ import argparse
23
+ from tqdm import tqdm
24
+ import csv
25
+
26
+ def crop_and_save_image(input_path, output_path, padding=10):
27
+ """
28
+ Crop a single fundus image to remove black background and save to the specified path.
29
+
30
+ Returns:
31
+ dict: A dictionary containing cropping information, used for writing to CSV.
32
+ """
33
+ try:
34
+ image = cv2.imread(input_path)
35
+ if image is None:
36
+ print(f"Warning: Unable to read image {input_path}, skipped.")
37
+ return None
38
+
39
+ original_h, original_w = image.shape[:2]
40
+
41
+ # Convert to grayscale for thresholding
42
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
43
+ _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
44
+
45
+ # Find contours
46
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
47
+ if not contours:
48
+ print(f"Warning: No contours found in image {input_path}, skipped.")
49
+ return None
50
+
51
+ # Find the largest contour (main fundus region)
52
+ main_contour = max(contours, key=cv2.contourArea)
53
+ x, y, w, h = cv2.boundingRect(main_contour)
54
+
55
+ img_h, img_w = original_h, original_w
56
+ x1 = max(0, x - padding)
57
+ y1 = max(0, y - padding)
58
+ x2 = min(img_w, x + w + padding)
59
+ y2 = min(img_h, y + h + padding)
60
+
61
+ cropped_image = image[y1:y2, x1:x2]
62
+
63
+ # Replace white spots in black background with black
64
+ white_mask = np.all(cropped_image == [255, 255, 255], axis=-1)
65
+ cropped_image[white_mask] = [0, 0, 0]
66
+
67
+ cv2.imwrite(output_path, cropped_image)
68
+
69
+ # Calculate cropped pixels (left, top, right, bottom)
70
+ left_crop = x1
71
+ top_crop = y1
72
+ right_crop = img_w - x2
73
+ bottom_crop = img_h - y2
74
+
75
+ return {
76
+ "filename": os.path.basename(input_path),
77
+ "original_width": original_w,
78
+ "original_height": original_h,
79
+ "left_crop": left_crop,
80
+ "top_crop": top_crop,
81
+ "right_crop": right_crop,
82
+ "bottom_crop": bottom_crop
83
+ }
84
+
85
+ except Exception as e:
86
+ print(f"Error processing file {input_path}: {e}")
87
+ return None
88
+
89
+ def main():
90
+ parser = argparse.ArgumentParser(description="Automatically crop fundus images to remove black background.")
91
+ parser.add_argument('-i', '--input_dir', help="Input directory containing original images.", default="csdi_datasets/original_images")
92
+ parser.add_argument('-o', '--output_dir', help="Output directory for saving cropped images.", default="csdi_datasets/croped_images")
93
+ parser.add_argument('-p', '--padding', type=int, default=0, help="Extra pixel padding around the crop boundary, default 0.")
94
+ parser.add_argument('-c', '--csv_path', type=str, default="crop_info.csv", help="CSV file path to save cropping information, default 'crop_info.csv'.")
95
+
96
+ args = parser.parse_args()
97
+ input_dir = args.input_dir
98
+ output_dir = args.output_dir
99
+ padding = args.padding
100
+ csv_path = args.csv_path
101
+
102
+ if not os.path.isdir(input_dir):
103
+ print(f"Error: Input directory '{input_dir}' does not exist.")
104
+ return
105
+
106
+ os.makedirs(output_dir, exist_ok=True)
107
+ print(f"Cropped images will be saved to: '{output_dir}'")
108
+
109
+ supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')
110
+ image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(supported_formats)]
111
+
112
+ if not image_files:
113
+ print(f"No supported image files found in directory '{input_dir}'.")
114
+ return
115
+
116
+ crop_records = []
117
+
118
+ print(f"Found {len(image_files)} images, starting processing...")
119
+ for filename in tqdm(image_files, desc="Processing progress"):
120
+ input_image_path = os.path.join(input_dir, filename)
121
+ output_image_path = os.path.join(output_dir, filename)
122
+
123
+ record = crop_and_save_image(input_image_path, output_image_path, padding)
124
+ if record:
125
+ crop_records.append(record)
126
+
127
+ # Write CSV file
128
+ with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
129
+ fieldnames = ["filename", "original_width", "original_height", "left_crop", "top_crop", "right_crop", "bottom_crop"]
130
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
131
+ writer.writeheader()
132
+ for rec in crop_records:
133
+ writer.writerow(rec)
134
+
135
+ print(f"All images processed! Cropping information saved to '{csv_path}'.")
136
+
137
+ if __name__ == '__main__':
138
+ main()
data_processing/01_deidentification/deidentify_batch.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): deidentify_batch.py
4
+ 原本用途 (Original Purpose):
5
+ 高通量多进程眼底相片批量隐私脱敏流水线。自动提取视网膜有效圆形视场掩模(FOV Mask),抹黑外围边框与非眼球区域(Frame Blackout),并结合 EasyOCR 扫描角部敏感字符进行正则遮蔽。
6
+ 适用数据集 (Target Dataset):
7
+ 多中心大规模原始彩色眼底相片(CFP),包括北京同仁医院、浙二眼科、河北邯郸眼科等积累的数百万张未脱敏眼底图像。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 多中心未脱敏的原始 JPG/PNG 彩色眼底图像及目录路径
12
+ 输出结果 (Output):
13
+ 已剥离患者姓名、病历号、检查时间等隐私信息的脱敏眼底图像
14
+ 依赖环境 (Dependencies):
15
+ opencv-python, easyocr, numpy, pillow, tqdm
16
+ ================================================================================
17
+ """
18
+
19
+ """Batch de-identification for cohorts with confirmed pixel-level PII.
20
+
21
+ Original images are read-only. Processed images are written as opaque-ID JPEGs
22
+ under /data/team/lisicheng/new_data_deid and the manifest is updated to use
23
+ train_path for the affected cohorts.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import math
31
+ import os
32
+ import tarfile
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ import cv2
37
+ import numpy as np
38
+
39
+ from deidentify_trial import (
40
+ blackout_frame,
41
+ deidentify_fundus_circle,
42
+ deidentify_fundus_left_outside_circle,
43
+ load_easyocr_reader,
44
+ maybe_ocr_metadata,
45
+ make_sheet,
46
+ read_image,
47
+ write_image,
48
+ )
49
+
50
+
51
+ DEFAULT_MANIFEST = Path(
52
+ "/data/team/lisicheng/new_data_manifest/"
53
+ "new_data_manifest_dedup_split_labeled_with_wds.parquet"
54
+ )
55
+ DEFAULT_OUT_ROOT = Path("/data/team/lisicheng/new_data_deid")
56
+ DEFAULT_TONGREN_METADATA = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv")
57
+ DEID_COHORTS = (
58
+ "tongren_95disease_fundus",
59
+ "fundus90wer",
60
+ "eryuan_fundus",
61
+ "xiangya_bscan",
62
+ "tongren_fundus",
63
+ "tongren_external_fundus",
64
+ "fq_testfundus",
65
+ "fq_rawfundus",
66
+ "fq_validfundus",
67
+ )
68
+ LEFT_ONLY_FUNDUS_COHORTS = {
69
+ "tongren_fundus",
70
+ "tongren_external_fundus",
71
+ "fq_testfundus",
72
+ "fq_rawfundus",
73
+ "fq_validfundus",
74
+ }
75
+ FULL_CIRCLE_FUNDUS_COHORTS = {
76
+ "tongren_95disease_fundus",
77
+ "fundus90wer",
78
+ "eryuan_fundus",
79
+ }
80
+
81
+
82
+ def main() -> None:
83
+ args = parse_args()
84
+ if args.command == "prepare":
85
+ prepare_inputs(args)
86
+ elif args.command == "process":
87
+ process_inputs(args)
88
+ elif args.command == "finalize":
89
+ finalize_manifest(args)
90
+ elif args.command == "qc":
91
+ build_qc(args)
92
+ else:
93
+ raise ValueError(f"unknown command: {args.command}")
94
+
95
+
96
+ def prepare_inputs(args: argparse.Namespace) -> None:
97
+ import pandas as pd
98
+
99
+ args.out_root.mkdir(parents=True, exist_ok=True)
100
+ meta_dir = args.out_root / "metadata"
101
+ meta_dir.mkdir(parents=True, exist_ok=True)
102
+ out_jsonl = args.input_jsonl or meta_dir / "deid_inputs.jsonl"
103
+
104
+ df = pd.read_parquet(args.manifest)
105
+ cohorts = tuple(args.cohorts or DEID_COHORTS)
106
+ subset = df[df["cohort"].isin(cohorts)].copy()
107
+ if args.limit:
108
+ subset = subset.groupby("cohort", group_keys=False).head(args.limit)
109
+
110
+ fields = ["image_id", "cohort", "file_path", "train_path", "rel_path", "modality"]
111
+ missing = [field for field in fields if field not in subset.columns]
112
+ if missing:
113
+ raise KeyError(f"manifest missing columns: {missing}")
114
+
115
+ tongren_meta = load_tongren_metadata(args.tongren_metadata)
116
+ with out_jsonl.open("w", encoding="utf-8") as f:
117
+ for row in subset[fields].to_dict("records"):
118
+ meta = metadata_for_row(row, tongren_meta)
119
+ row.update({f"ocr_{key}": value for key, value in meta.items()})
120
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
121
+
122
+ counts = subset.groupby("cohort").size().to_dict()
123
+ print(json.dumps({"input_jsonl": str(out_jsonl), "counts": counts}, ensure_ascii=False))
124
+
125
+
126
+ def process_inputs(args: argparse.Namespace) -> None:
127
+ meta_dir = args.out_root / "metadata"
128
+ meta_dir.mkdir(parents=True, exist_ok=True)
129
+ shard_name = f"{args.run_name}_shard{args.shard_index:03d}-of-{args.num_shards:03d}.jsonl"
130
+ metadata_path = args.metadata_jsonl or meta_dir / shard_name
131
+ if metadata_path.exists() and not args.overwrite_metadata:
132
+ raise FileExistsError(f"metadata exists; use --overwrite-metadata: {metadata_path}")
133
+
134
+ done_ids = load_done_ids(args.skip_done_metadata_dir, args.skip_done_metadata_glob)
135
+ if done_ids:
136
+ print(f"[resume] loaded {len(done_ids)} completed image_ids")
137
+
138
+ reader = load_easyocr_reader(args.ocr)
139
+ n_seen = 0
140
+ n_skip = 0
141
+ n_done = 0
142
+ n_error = 0
143
+ with args.input_jsonl.open("r", encoding="utf-8") as src, metadata_path.open(
144
+ "w", encoding="utf-8"
145
+ ) as meta_out:
146
+ for idx, line in enumerate(src):
147
+ if idx % args.num_shards != args.shard_index:
148
+ continue
149
+ if args.limit and n_seen >= args.limit:
150
+ break
151
+ n_seen += 1
152
+ row = json.loads(line)
153
+ if row.get("image_id") in done_ids:
154
+ n_skip += 1
155
+ continue
156
+ try:
157
+ result = process_one(row, args, reader)
158
+ n_done += 1
159
+ except Exception as exc:
160
+ n_error += 1
161
+ result = {
162
+ "image_id": row.get("image_id"),
163
+ "cohort": row.get("cohort"),
164
+ "ok": False,
165
+ "error": repr(exc),
166
+ }
167
+ meta_out.write(json.dumps(result, ensure_ascii=False) + "\n")
168
+ if n_seen % args.log_every == 0:
169
+ print(
170
+ f"[{args.shard_index}/{args.num_shards}] "
171
+ f"seen={n_seen} skip={n_skip} done={n_done} err={n_error}"
172
+ )
173
+ print(
174
+ json.dumps(
175
+ {
176
+ "metadata_jsonl": str(metadata_path),
177
+ "seen": n_seen,
178
+ "skip": n_skip,
179
+ "done": n_done,
180
+ "error": n_error,
181
+ },
182
+ ensure_ascii=False,
183
+ )
184
+ )
185
+
186
+
187
+ def process_one(row: dict[str, Any], args: argparse.Namespace, reader: object | None) -> dict[str, Any]:
188
+ cohort = row["cohort"]
189
+ src_path = str(row.get("train_path") or row["file_path"])
190
+ image_id = row["image_id"]
191
+ out_path = args.out_root / "images" / cohort / f"{image_id}.jpg"
192
+ out_path.parent.mkdir(parents=True, exist_ok=True)
193
+
194
+ img = read_image_any(src_path)
195
+ ocr_meta: dict[str, int | str] = existing_ocr_meta(row)
196
+ circle_ok: bool | None = None
197
+ circle_info: dict[str, Any] | None = None
198
+
199
+ if cohort in FULL_CIRCLE_FUNDUS_COHORTS:
200
+ if reader is not None and not ocr_meta:
201
+ ocr_meta = maybe_ocr_metadata(img, reader)
202
+ out_img, circle_ok, circle_info = deidentify_fundus_circle(
203
+ img,
204
+ radius_ratio=args.fundus_radius_ratio,
205
+ threshold=args.fundus_threshold,
206
+ open_kernel=args.fundus_open_kernel,
207
+ )
208
+ method = "fundus_circle_mask"
209
+ elif cohort in LEFT_ONLY_FUNDUS_COHORTS:
210
+ if reader is not None and not ocr_meta:
211
+ ocr_meta = maybe_ocr_metadata(img, reader)
212
+ out_img, circle_ok, circle_info = deidentify_fundus_left_outside_circle(
213
+ img,
214
+ radius_ratio=args.left_fundus_radius_ratio,
215
+ left_ratio=args.left_fundus_ratio,
216
+ threshold=args.fundus_threshold,
217
+ open_kernel=args.fundus_open_kernel,
218
+ )
219
+ method = "fundus_left_outside_circle_mask_r0985_l055"
220
+ elif cohort == "xiangya_bscan":
221
+ out_img = blackout_frame(
222
+ img,
223
+ top=args.bscan_top,
224
+ bottom=args.bscan_bottom,
225
+ right=args.bscan_right,
226
+ )
227
+ method = "bscan_blackout_top10_bottom5_right2"
228
+ else:
229
+ raise ValueError(f"unsupported cohort: {cohort}")
230
+
231
+ if not out_path.exists() or args.overwrite_images:
232
+ write_image(out_path, out_img, quality=args.jpeg_quality)
233
+
234
+ return {
235
+ "image_id": image_id,
236
+ "cohort": cohort,
237
+ "ok": True,
238
+ "source_path": src_path,
239
+ "deid_path": str(out_path),
240
+ "deid_method": method,
241
+ "pii_masked": True,
242
+ "ocr_age": ocr_meta.get("age"),
243
+ "ocr_sex": ocr_meta.get("sex"),
244
+ "ocr_eye": ocr_meta.get("eye"),
245
+ "circle_ok": circle_ok,
246
+ "circle_info": circle_info,
247
+ }
248
+
249
+
250
+ def finalize_manifest(args: argparse.Namespace) -> None:
251
+ import pandas as pd
252
+
253
+ meta_files = sorted(args.metadata_dir.glob(args.metadata_glob))
254
+ if not meta_files:
255
+ raise FileNotFoundError(f"no metadata files match {args.metadata_dir}/{args.metadata_glob}")
256
+
257
+ rows: list[dict[str, Any]] = []
258
+ failed_rows: list[dict[str, Any]] = []
259
+ for path in meta_files:
260
+ with path.open("r", encoding="utf-8") as f:
261
+ for line in f:
262
+ try:
263
+ row = json.loads(line)
264
+ except json.JSONDecodeError:
265
+ continue
266
+ if row.get("ok"):
267
+ rows.append(row)
268
+ elif row.get("image_id"):
269
+ failed_rows.append(row)
270
+ meta = pd.DataFrame(rows)
271
+ if meta.empty:
272
+ raise ValueError("no successful deid metadata rows found")
273
+ meta = meta.drop_duplicates("image_id", keep="last")
274
+
275
+ df = pd.read_parquet(args.manifest)
276
+ df = df.copy()
277
+ if "train_path" not in df.columns:
278
+ df["train_path"] = df["file_path"]
279
+ else:
280
+ df["train_path"] = df["train_path"].where(df["train_path"].notna(), df["file_path"])
281
+ for col, default in [
282
+ ("deid_path", None),
283
+ ("pii_masked", False),
284
+ ("deid_method", None),
285
+ ("ocr_age", None),
286
+ ("ocr_sex", None),
287
+ ("ocr_eye", None),
288
+ ]:
289
+ if col not in df.columns:
290
+ df[col] = default
291
+
292
+ cols = ["image_id", "deid_path", "deid_method", "ocr_age", "ocr_sex", "ocr_eye"]
293
+ merged = df.merge(meta[cols], on="image_id", how="left", suffixes=("", "_new"))
294
+ has_deid = merged["deid_path_new"].notna()
295
+ nullable_cols = [
296
+ "deid_path",
297
+ "deid_path_new",
298
+ "deid_method",
299
+ "deid_method_new",
300
+ "ocr_age",
301
+ "ocr_age_new",
302
+ "ocr_sex",
303
+ "ocr_sex_new",
304
+ "ocr_eye",
305
+ "ocr_eye_new",
306
+ ]
307
+ for col in nullable_cols:
308
+ if col in merged.columns:
309
+ merged[col] = merged[col].astype("object")
310
+ merged.loc[has_deid, "train_path"] = merged.loc[has_deid, "deid_path_new"]
311
+ merged.loc[has_deid, "deid_path"] = merged.loc[has_deid, "deid_path_new"]
312
+ merged.loc[has_deid, "pii_masked"] = True
313
+ for col in ["deid_method", "ocr_age", "ocr_sex", "ocr_eye"]:
314
+ merged.loc[has_deid, col] = merged.loc[has_deid, f"{col}_new"]
315
+ merged = merged.drop(columns=[f"{col}_new" for col in cols if col != "image_id"])
316
+
317
+ required_cohorts = tuple(args.cohorts or DEID_COHORTS)
318
+ missing_deid = merged["cohort"].isin(required_cohorts) & ~merged["pii_masked"]
319
+ dropped_missing_deid = int(missing_deid.sum())
320
+ if dropped_missing_deid:
321
+ missing_path = args.out_manifest.with_suffix(".missing_deid.jsonl")
322
+ missing_records = merged.loc[
323
+ missing_deid, ["image_id", "cohort", "file_path", "rel_path"]
324
+ ].to_dict("records")
325
+ failure_by_id = {row.get("image_id"): row for row in failed_rows}
326
+ with missing_path.open("w", encoding="utf-8") as f:
327
+ for row in missing_records:
328
+ failure = failure_by_id.get(row["image_id"])
329
+ if failure:
330
+ row["error"] = failure.get("error")
331
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
332
+ if args.drop_missing_deid:
333
+ merged = merged.loc[~missing_deid].copy()
334
+
335
+ args.out_manifest.parent.mkdir(parents=True, exist_ok=True)
336
+ merged.to_parquet(args.out_manifest, index=False)
337
+ print(
338
+ json.dumps(
339
+ {
340
+ "out_manifest": str(args.out_manifest),
341
+ "rows": int(len(merged)),
342
+ "pii_masked": int(merged["pii_masked"].sum()),
343
+ "by_cohort": merged[merged["pii_masked"]].groupby("cohort").size().to_dict(),
344
+ "dropped_missing_deid": dropped_missing_deid if args.drop_missing_deid else 0,
345
+ },
346
+ ensure_ascii=False,
347
+ )
348
+ )
349
+
350
+
351
+ def build_qc(args: argparse.Namespace) -> None:
352
+ rows = []
353
+ with args.metadata_jsonl.open("r", encoding="utf-8") as f:
354
+ for line in f:
355
+ row = json.loads(line)
356
+ if args.cohort and row.get("cohort") != args.cohort:
357
+ continue
358
+ if row.get("ok"):
359
+ rows.append(row)
360
+ rows = rows[: args.n]
361
+ groups = []
362
+ for row in rows:
363
+ src = read_image_any(str(row["source_path"]))
364
+ deid = read_image(Path(row["deid_path"]))
365
+ groups.append([src, deid])
366
+ make_sheet(groups, ["source", "deid"], args.out, cell=args.cell)
367
+ print(f"DONE -> {args.out}")
368
+
369
+
370
+ def parse_args() -> argparse.Namespace:
371
+ parser = argparse.ArgumentParser()
372
+ sub = parser.add_subparsers(dest="command", required=True)
373
+
374
+ p = sub.add_parser("prepare")
375
+ p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
376
+ p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT)
377
+ p.add_argument("--input-jsonl", type=Path, default=None)
378
+ p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS))
379
+ p.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_METADATA)
380
+ p.add_argument("--limit", type=int, default=None)
381
+
382
+ p = sub.add_parser("process")
383
+ p.add_argument("--input-jsonl", type=Path, required=True)
384
+ p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT)
385
+ p.add_argument("--run-name", default="deid")
386
+ p.add_argument("--metadata-jsonl", type=Path, default=None)
387
+ p.add_argument("--overwrite-metadata", action="store_true")
388
+ p.add_argument("--overwrite-images", action="store_true")
389
+ p.add_argument("--skip-done-metadata-dir", type=Path, default=None)
390
+ p.add_argument("--skip-done-metadata-glob", default="*.jsonl")
391
+ p.add_argument("--num-shards", type=int, default=1)
392
+ p.add_argument("--shard-index", type=int, default=0)
393
+ p.add_argument("--limit", type=int, default=None)
394
+ p.add_argument("--log-every", type=int, default=1000)
395
+ p.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
396
+ p.add_argument("--jpeg-quality", type=int, default=95)
397
+ p.add_argument("--fundus-radius-ratio", type=float, default=0.97)
398
+ p.add_argument("--left-fundus-radius-ratio", type=float, default=0.985)
399
+ p.add_argument("--left-fundus-ratio", type=float, default=0.55)
400
+ p.add_argument("--fundus-threshold", type=int, default=25)
401
+ p.add_argument("--fundus-open-kernel", type=int, default=25)
402
+ p.add_argument("--bscan-top", type=float, default=0.10)
403
+ p.add_argument("--bscan-bottom", type=float, default=0.05)
404
+ p.add_argument("--bscan-right", type=float, default=0.02)
405
+
406
+ p = sub.add_parser("finalize")
407
+ p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
408
+ p.add_argument("--metadata-dir", type=Path, default=DEFAULT_OUT_ROOT / "metadata")
409
+ p.add_argument("--metadata-glob", default="deid_shard*.jsonl")
410
+ p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS))
411
+ p.add_argument("--drop-missing-deid", action=argparse.BooleanOptionalAction, default=True)
412
+ p.add_argument(
413
+ "--out-manifest",
414
+ type=Path,
415
+ default=DEFAULT_MANIFEST.with_name(
416
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
417
+ ),
418
+ )
419
+
420
+ p = sub.add_parser("qc")
421
+ p.add_argument("--metadata-jsonl", type=Path, required=True)
422
+ p.add_argument("--out", type=Path, required=True)
423
+ p.add_argument("--cohort", default=None)
424
+ p.add_argument("--n", type=int, default=24)
425
+ p.add_argument("--cell", type=int, default=256)
426
+
427
+ return parser.parse_args()
428
+
429
+
430
+ def load_done_ids(metadata_dir: Path | None, metadata_glob: str) -> set[str]:
431
+ if metadata_dir is None:
432
+ return set()
433
+ done: set[str] = set()
434
+ for path in sorted(metadata_dir.glob(metadata_glob)):
435
+ with path.open("r", encoding="utf-8") as f:
436
+ for line in f:
437
+ try:
438
+ row = json.loads(line)
439
+ except json.JSONDecodeError:
440
+ continue
441
+ if row.get("ok") and row.get("image_id"):
442
+ done.add(row["image_id"])
443
+ return done
444
+
445
+
446
+ def read_image_any(path: str) -> Any:
447
+ if "::" not in path:
448
+ return read_image(Path(path))
449
+
450
+ tar_path, member_name = path.split("::", 1)
451
+ with tarfile.open(tar_path, "r:*") as tf:
452
+ member = tf.getmember(member_name)
453
+ fp = tf.extractfile(member)
454
+ if fp is None:
455
+ raise FileNotFoundError(path)
456
+ data = fp.read()
457
+ arr = np.frombuffer(data, dtype=np.uint8)
458
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
459
+ if img is None:
460
+ raise ValueError(f"failed to decode image: {path}")
461
+ return img
462
+
463
+
464
+ def load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]:
465
+ if not path.exists():
466
+ return {}
467
+ import pandas as pd
468
+
469
+ meta = pd.read_csv(path)
470
+ out: dict[str, dict[str, Any]] = {}
471
+ for row in meta.itertuples(index=False):
472
+ filename = str(row.filename)
473
+ sex = {"男": "M", "女": "F"}.get(str(row.sex), None)
474
+ age = None if pd.isna(row.age) else int(row.age)
475
+ eye = eye_from_seq(row.eye_seq)
476
+ out[filename] = {k: v for k, v in {"age": age, "sex": sex, "eye": eye}.items() if v is not None}
477
+ return out
478
+
479
+
480
+ def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]:
481
+ if row.get("cohort") != "tongren_fundus":
482
+ return {}
483
+ name = str(row.get("rel_path") or "")
484
+ if not name:
485
+ path = str(row.get("train_path") or row.get("file_path") or "")
486
+ name = path.split("::", 1)[1] if "::" in path else Path(path).name
487
+ return tongren_meta.get(name, {})
488
+
489
+
490
+ def eye_from_seq(value: Any) -> str | None:
491
+ if value is None or (isinstance(value, float) and math.isnan(value)):
492
+ return None
493
+ text = str(int(value)) if isinstance(value, float) else str(value)
494
+ if text == "1":
495
+ return "OD"
496
+ if text == "2":
497
+ return "OS"
498
+ return None
499
+
500
+
501
+ def existing_ocr_meta(row: dict[str, Any]) -> dict[str, int | str]:
502
+ meta: dict[str, int | str] = {}
503
+ for src_key, dst_key in [("ocr_age", "age"), ("ocr_sex", "sex"), ("ocr_eye", "eye")]:
504
+ value = row.get(src_key)
505
+ if value is None:
506
+ continue
507
+ if isinstance(value, float) and math.isnan(value):
508
+ continue
509
+ if value == "":
510
+ continue
511
+ if dst_key == "age":
512
+ value = int(value)
513
+ meta[dst_key] = value
514
+ return meta
515
+
516
+
517
+ if __name__ == "__main__":
518
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
519
+ main()
data_processing/01_deidentification/deidentify_trial.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): deidentify_trial.py
4
+ 原本用途 (Original Purpose):
5
+ 眼底隐私脱敏算法核心算子实现库。包含圆形掩模生成算法(Otsu 阈值与形态学轮廓提取)、背景暗角检测、基于正则模式的敏感字符识别与局部高斯模糊/黑框遮盖算子。
6
+ 适用数据集 (Target Dataset):
7
+ 通用彩色眼底相片(CFP)脱敏算法开发与单图试算评估。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 单张或小批量眼底图像
12
+ 输出结果 (Output):
13
+ 脱敏处理后的图像对象及掩模蒙版
14
+ 依赖环境 (Dependencies):
15
+ opencv-python, easyocr, numpy, pillow
16
+ ================================================================================
17
+ """
18
+
19
+ """Small visual trial for burned-in PII handling.
20
+
21
+ This script is intentionally sample-only. It never edits source images and never
22
+ saves raw OCR text. It writes comparison sheets so the cohort-level policy can be
23
+ chosen by eye before a full preprocessing run.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import random
31
+ import re
32
+ from pathlib import Path
33
+ import cv2
34
+ import numpy as np
35
+ from PIL import Image, ImageDraw, ImageFont
36
+
37
+ import cohorts as C
38
+
39
+
40
+ IMG_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp"}
41
+
42
+
43
+ def parse_ocr_metadata(text: str) -> dict[str, int | str]:
44
+ """Keep only non-identifier fields from OCR text."""
45
+ meta: dict[str, int | str] = {}
46
+
47
+ age_match = re.search(r"(?<!\d)(\d{1,3})\s*岁", text)
48
+ if age_match:
49
+ age = int(age_match.group(1))
50
+ if 0 <= age <= 120:
51
+ meta["age"] = age
52
+
53
+ if "男" in text:
54
+ meta["sex"] = "M"
55
+ elif "女" in text:
56
+ meta["sex"] = "F"
57
+
58
+ eye_match = re.search(r"\b(O[DSU])\b", text.upper())
59
+ if eye_match:
60
+ meta["eye"] = eye_match.group(1)
61
+
62
+ return meta
63
+
64
+
65
+ def blackout_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
66
+ """Mask the top horizontal metadata bar while preserving image size."""
67
+ out = img.copy()
68
+ rows = _rows_from_ratio(img, ratio)
69
+ out[:rows, :] = 0
70
+ return out
71
+
72
+
73
+ def crop_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
74
+ """Remove the top horizontal metadata bar."""
75
+ rows = _rows_from_ratio(img, ratio)
76
+ return img[rows:, :].copy()
77
+
78
+
79
+ def blackout_frame(img: np.ndarray, *, top: float, bottom: float, right: float) -> np.ndarray:
80
+ """Mask fixed device UI bands while preserving the scan geometry."""
81
+ out = img.copy()
82
+ top_rows = _rows_from_ratio(img, top) if top > 0 else 0
83
+ bottom_rows = _rows_from_ratio(img, bottom) if bottom > 0 else 0
84
+ right_cols = _cols_from_ratio(img, right) if right > 0 else 0
85
+ if top_rows:
86
+ out[:top_rows, :] = 0
87
+ if bottom_rows:
88
+ out[-bottom_rows:, :] = 0
89
+ if right_cols:
90
+ out[:, -right_cols:] = 0
91
+ return out
92
+
93
+
94
+ def deidentify_fundus_circle(
95
+ img: np.ndarray,
96
+ *,
97
+ radius_ratio: float = 0.97,
98
+ threshold: int = 25,
99
+ open_kernel: int = 25,
100
+ fallback_top_ratio: float = 0.25,
101
+ ) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
102
+ """Keep the detected retinal circle and black out everything outside it."""
103
+ circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
104
+ if circle_info is None:
105
+ return _fundus_fallback(img, fallback_top_ratio, "no_component")
106
+ cx, cy, radius, area = circle_info
107
+ h, w = img.shape[:2]
108
+ if area < int(h * w * 0.08):
109
+ return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
110
+ radius = float(radius) * radius_ratio
111
+ if radius < min(h, w) * 0.20:
112
+ return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
113
+
114
+ circle = np.zeros((h, w), dtype=np.uint8)
115
+ cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
116
+ out = np.zeros_like(img)
117
+ out[circle > 0] = img[circle > 0]
118
+ return out, True, {"cx": int(cx), "cy": int(cy), "radius": int(radius), "area": area}
119
+
120
+
121
+ def deidentify_fundus_left_outside_circle(
122
+ img: np.ndarray,
123
+ *,
124
+ radius_ratio: float = 0.985,
125
+ left_ratio: float = 0.55,
126
+ threshold: int = 25,
127
+ open_kernel: int = 25,
128
+ fallback_top_ratio: float = 0.25,
129
+ ) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
130
+ """Black out only left-side pixels outside the detected fundus field of view."""
131
+ circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
132
+ if circle_info is None:
133
+ return _fundus_fallback(img, fallback_top_ratio, "no_component")
134
+
135
+ cx, cy, radius, area = circle_info
136
+ h, w = img.shape[:2]
137
+ if area < int(h * w * 0.08):
138
+ return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
139
+
140
+ radius = float(radius) * radius_ratio
141
+ if radius < min(h, w) * 0.20:
142
+ return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
143
+
144
+ circle = np.zeros((h, w), dtype=np.uint8)
145
+ cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
146
+ left_limit = max(int(cx), int(round(w * left_ratio)))
147
+ left_limit = min(w, max(1, left_limit))
148
+ left_mask = np.zeros((h, w), dtype=bool)
149
+ left_mask[:, :left_limit] = True
150
+
151
+ out = img.copy()
152
+ out[(circle == 0) & left_mask] = 0
153
+ return out, True, {
154
+ "cx": int(cx),
155
+ "cy": int(cy),
156
+ "radius": int(radius),
157
+ "area": area,
158
+ "left_limit": int(left_limit),
159
+ }
160
+
161
+
162
+ def read_image(path: Path) -> np.ndarray:
163
+ data = np.fromfile(str(path), dtype=np.uint8)
164
+ img = cv2.imdecode(data, cv2.IMREAD_COLOR)
165
+ if img is None:
166
+ raise ValueError(f"failed to decode image: {path}")
167
+ return img
168
+
169
+
170
+ def write_image(path: Path, img: np.ndarray, quality: int = 92) -> None:
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ ext = path.suffix.lower()
173
+ params = []
174
+ if ext in {".jpg", ".jpeg"}:
175
+ params = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
176
+ ok, data = cv2.imencode(ext, img, params)
177
+ if not ok:
178
+ raise ValueError(f"failed to encode image: {path}")
179
+ data.tofile(str(path))
180
+
181
+
182
+ def sample_paths(cohort_key: str, n: int, seed: int, scan_limit: int | None) -> list[Path]:
183
+ cohort = _cohort(cohort_key)
184
+ root = Path(C.read_path(cohort))
185
+ exts = set(cohort.get("exts") or IMG_EXTS)
186
+ files: list[Path] = []
187
+ for path in root.rglob("*"):
188
+ if path.is_file() and path.suffix.lower() in exts:
189
+ files.append(path)
190
+ if scan_limit and len(files) >= scan_limit:
191
+ break
192
+ if not files:
193
+ raise FileNotFoundError(f"no images found for {cohort_key} under {root}")
194
+ rng = random.Random(seed)
195
+ return rng.sample(files, min(n, len(files)))
196
+
197
+
198
+ def maybe_ocr_metadata(img: np.ndarray, reader: object | None) -> dict[str, int | str]:
199
+ if reader is None:
200
+ return {}
201
+ h = img.shape[0]
202
+ crop = img[: int(h * 0.55), :]
203
+ rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
204
+ results = reader.readtext(rgb, detail=0)
205
+ return parse_ocr_metadata(" ".join(str(item) for item in results))
206
+
207
+
208
+ def load_easyocr_reader(enable: bool) -> object | None:
209
+ if not enable:
210
+ return None
211
+ try:
212
+ import easyocr
213
+ except Exception as exc: # pragma: no cover - depends on h100 environment
214
+ print(f"[warn] easyocr unavailable; OCR metadata disabled: {exc}")
215
+ return None
216
+ try:
217
+ return easyocr.Reader(["ch_sim", "en"], gpu=True)
218
+ except Exception as exc: # pragma: no cover - depends on h100 environment
219
+ print(f"[warn] easyocr reader failed; OCR metadata disabled: {exc}")
220
+ return None
221
+
222
+
223
+ def make_sheet(
224
+ groups: list[list[np.ndarray]],
225
+ labels: list[str],
226
+ out_path: Path,
227
+ *,
228
+ cell: int = 256,
229
+ header: int = 24,
230
+ ) -> None:
231
+ rows = len(groups)
232
+ cols = len(labels)
233
+ sheet = Image.new("RGB", (cols * cell, rows * (cell + header)), (18, 18, 18))
234
+ draw = ImageDraw.Draw(sheet)
235
+ font = ImageFont.load_default()
236
+ for row, imgs in enumerate(groups):
237
+ for col, label in enumerate(labels):
238
+ x = col * cell
239
+ y = row * (cell + header)
240
+ draw.text((x + 5, y + 5), label, fill=(230, 230, 230), font=font)
241
+ thumb = _thumb_bgr(imgs[col], cell)
242
+ sheet.paste(thumb, (x, y + header))
243
+ out_path.parent.mkdir(parents=True, exist_ok=True)
244
+ sheet.save(out_path, quality=92)
245
+
246
+
247
+ def run_fundus_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
248
+ reader = load_easyocr_reader(args.ocr)
249
+ paths = sample_paths(args.fundus_cohort, args.n, args.seed, args.scan_limit)
250
+ groups: list[list[np.ndarray]] = []
251
+ for i, path in enumerate(paths):
252
+ img = read_image(path)
253
+ meta = maybe_ocr_metadata(img, reader)
254
+ masked, ok, info = deidentify_fundus_circle(
255
+ img,
256
+ radius_ratio=args.fundus_radius_ratio,
257
+ threshold=args.fundus_threshold,
258
+ open_kernel=args.fundus_open_kernel,
259
+ )
260
+ groups.append([img, masked])
261
+ write_image(args.out / "fundus" / f"sample_{i:03d}_masked.jpg", masked)
262
+ metadata_rows.append(
263
+ {
264
+ "sample_idx": i,
265
+ "cohort": args.fundus_cohort,
266
+ "kind": "fundus",
267
+ "method": "circle_mask",
268
+ "circle_ok": ok,
269
+ "circle_info": info,
270
+ "ocr_meta": meta,
271
+ }
272
+ )
273
+ make_sheet(groups, ["original", "circle_mask"], args.out / "fundus_compare.jpg")
274
+
275
+
276
+ def run_bscan_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
277
+ paths = sample_paths(args.bscan_cohort, args.n, args.seed + 1, args.scan_limit)
278
+ ratios = [float(part) for part in args.bscan_ratios.split(",") if part.strip()]
279
+ frame_specs = _parse_frame_specs(args.bscan_frame_specs)
280
+
281
+ blackout_groups: list[list[np.ndarray]] = []
282
+ crop_groups: list[list[np.ndarray]] = []
283
+ frame_groups: list[list[np.ndarray]] = []
284
+ blackout_labels = ["original"] + [f"black_{int(r * 100)}pct" for r in ratios]
285
+ crop_labels = ["original"] + [f"crop_{int(r * 100)}pct" for r in ratios]
286
+ frame_labels = ["original"] + [
287
+ f"top{int(top * 100)}_bot{int(bottom * 100)}_right{int(right * 100)}"
288
+ for top, bottom, right in frame_specs
289
+ ]
290
+
291
+ for i, path in enumerate(paths):
292
+ img = read_image(path)
293
+ blackout_imgs = [img] + [blackout_top_bar(img, r) for r in ratios]
294
+ crop_imgs = [img] + [crop_top_bar(img, r) for r in ratios]
295
+ frame_imgs = [img] + [
296
+ blackout_frame(img, top=top, bottom=bottom, right=right)
297
+ for top, bottom, right in frame_specs
298
+ ]
299
+ blackout_groups.append(blackout_imgs)
300
+ crop_groups.append(crop_imgs)
301
+ frame_groups.append(frame_imgs)
302
+ for label, out_img in zip(blackout_labels[1:], blackout_imgs[1:], strict=True):
303
+ write_image(args.out / "bscan_blackout" / f"sample_{i:03d}_{label}.jpg", out_img)
304
+ for label, out_img in zip(crop_labels[1:], crop_imgs[1:], strict=True):
305
+ write_image(args.out / "bscan_crop" / f"sample_{i:03d}_{label}.jpg", out_img)
306
+ for label, out_img in zip(frame_labels[1:], frame_imgs[1:], strict=True):
307
+ write_image(args.out / "bscan_frame" / f"sample_{i:03d}_{label}.jpg", out_img)
308
+ metadata_rows.append(
309
+ {
310
+ "sample_idx": i,
311
+ "cohort": args.bscan_cohort,
312
+ "kind": "bscan",
313
+ "methods": {"blackout": ratios, "crop": ratios, "frame": frame_specs},
314
+ }
315
+ )
316
+
317
+ make_sheet(blackout_groups, blackout_labels, args.out / "bscan_blackout_compare.jpg")
318
+ make_sheet(crop_groups, crop_labels, args.out / "bscan_crop_compare.jpg")
319
+ make_sheet(frame_groups, frame_labels, args.out / "bscan_frame_compare.jpg")
320
+
321
+
322
+ def main() -> None:
323
+ args = parse_args()
324
+ args.out.mkdir(parents=True, exist_ok=True)
325
+ metadata_rows: list[dict[str, object]] = []
326
+
327
+ if args.fundus:
328
+ run_fundus_trial(args, metadata_rows)
329
+ if args.bscan:
330
+ run_bscan_trial(args, metadata_rows)
331
+
332
+ with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f:
333
+ for row in metadata_rows:
334
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
335
+ print(f"DONE -> {args.out}")
336
+
337
+
338
+ def parse_args() -> argparse.Namespace:
339
+ parser = argparse.ArgumentParser()
340
+ parser.add_argument("--out", type=Path, default=Path("/data/team/lisicheng/deid_trial"))
341
+ parser.add_argument("--n", type=int, default=12)
342
+ parser.add_argument("--seed", type=int, default=0)
343
+ parser.add_argument("--scan-limit", type=int, default=50000)
344
+ parser.add_argument("--fundus", action=argparse.BooleanOptionalAction, default=True)
345
+ parser.add_argument("--bscan", action=argparse.BooleanOptionalAction, default=True)
346
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
347
+ parser.add_argument("--fundus-cohort", default="tongren_95disease_fundus")
348
+ parser.add_argument("--bscan-cohort", default="xiangya_bscan")
349
+ parser.add_argument("--fundus-radius-ratio", type=float, default=0.97)
350
+ parser.add_argument("--fundus-threshold", type=int, default=25)
351
+ parser.add_argument("--fundus-open-kernel", type=int, default=25)
352
+ parser.add_argument("--bscan-ratios", default="0.06,0.08,0.10")
353
+ parser.add_argument("--bscan-frame-specs", default="0.08,0.05,0.02;0.10,0.05,0.02")
354
+ return parser.parse_args()
355
+
356
+
357
+ def _cohort(key: str) -> dict[str, object]:
358
+ for cohort in C.INCLUDE:
359
+ if cohort["key"] == key:
360
+ return cohort
361
+ raise KeyError(f"unknown cohort: {key}")
362
+
363
+
364
+ def _rows_from_ratio(img: np.ndarray, ratio: float) -> int:
365
+ if not 0 < ratio < 1:
366
+ raise ValueError(f"ratio must be between 0 and 1: {ratio}")
367
+ return max(1, min(img.shape[0] - 1, int(round(img.shape[0] * ratio))))
368
+
369
+
370
+ def _cols_from_ratio(img: np.ndarray, ratio: float) -> int:
371
+ if not 0 < ratio < 1:
372
+ raise ValueError(f"ratio must be between 0 and 1: {ratio}")
373
+ return max(1, min(img.shape[1] - 1, int(round(img.shape[1] * ratio))))
374
+
375
+
376
+ def _parse_frame_specs(raw: str) -> list[tuple[float, float, float]]:
377
+ specs: list[tuple[float, float, float]] = []
378
+ for item in raw.split(";"):
379
+ item = item.strip()
380
+ if not item:
381
+ continue
382
+ parts = [float(part) for part in item.split(",")]
383
+ if len(parts) != 3:
384
+ raise ValueError(f"frame spec must be top,bottom,right: {item}")
385
+ specs.append((parts[0], parts[1], parts[2]))
386
+ return specs
387
+
388
+
389
+ def _to_gray(img: np.ndarray) -> np.ndarray:
390
+ if img.ndim == 2:
391
+ return img
392
+ return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
393
+
394
+
395
+ def _detect_fundus_circle(
396
+ img: np.ndarray, *, threshold: int, open_kernel: int
397
+ ) -> tuple[float, float, float, int] | None:
398
+ gray = _to_gray(img)
399
+ _, th = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
400
+ kernel = np.ones((open_kernel, open_kernel), np.uint8)
401
+ th = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)
402
+
403
+ n_labels, labels, stats, _ = cv2.connectedComponentsWithStats(th)
404
+ if n_labels <= 1:
405
+ return None
406
+
407
+ areas = stats[1:, cv2.CC_STAT_AREA]
408
+ largest = 1 + int(np.argmax(areas))
409
+ area = int(stats[largest, cv2.CC_STAT_AREA])
410
+ mask = (labels == largest).astype("uint8") * 255
411
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
412
+ if not contours:
413
+ return None
414
+
415
+ contour = max(contours, key=cv2.contourArea)
416
+ (cx, cy), radius = cv2.minEnclosingCircle(contour)
417
+ return cx, cy, radius, area
418
+
419
+
420
+ def _fundus_fallback(
421
+ img: np.ndarray, top_ratio: float, reason: str
422
+ ) -> tuple[np.ndarray, bool, dict[str, str]]:
423
+ return blackout_top_bar(img, top_ratio), False, {"reason": reason}
424
+
425
+
426
+ def _thumb_bgr(img: np.ndarray, cell: int) -> Image.Image:
427
+ if img.ndim == 2:
428
+ rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
429
+ else:
430
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
431
+ im = Image.fromarray(rgb)
432
+ im.thumbnail((cell, cell), Image.Resampling.LANCZOS)
433
+ canvas = Image.new("RGB", (cell, cell), (0, 0, 0))
434
+ canvas.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2))
435
+ return canvas
436
+
437
+
438
+ if __name__ == "__main__":
439
+ main()
data_processing/01_deidentification/fundus_pii_trial.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): fundus_pii_trial.py
4
+ 原本用途 (Original Purpose):
5
+ 烧录文字(Burned-in PII)交互式与样本可视化抽检工具,可在图像上直接叠加脱敏边界与 OCR 识别候选框,方便人工快速比对与算法调优。
6
+ 适用数据集 (Target Dataset):
7
+ 含有设备硬烧录文字的各类眼底相机原始图像(Topcon, Canon, Zeiss 等)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 样本眼底图像路径
12
+ 输出结果 (Output):
13
+ 交互式可视化检验窗口与标注覆盖图
14
+ 依赖环境 (Dependencies):
15
+ opencv-python, matplotlib, numpy, pillow
16
+ ================================================================================
17
+ """
18
+
19
+ """Small QC trial for fundus-like left-corner PII de-identification.
20
+
21
+ Reads samples from the final manifest, masks the detected circular field of view, and writes
22
+ comparison sheets plus non-identifying metadata. Source images are never modified.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import math
30
+ import tarfile
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ import cv2
35
+ import numpy as np
36
+ import pandas as pd
37
+ from PIL import Image
38
+
39
+ from deidentify_trial import (
40
+ deidentify_fundus_circle,
41
+ deidentify_fundus_left_outside_circle,
42
+ load_easyocr_reader,
43
+ make_sheet,
44
+ )
45
+
46
+
47
+ DEFAULT_MANIFEST = Path(
48
+ "/data/team/lisicheng/new_data_manifest/"
49
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
50
+ )
51
+ DEFAULT_TONGREN_META = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv")
52
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/fundus_pii_trial_20260702")
53
+ COHORTS = [
54
+ "tongren_fundus",
55
+ "tongren_external_fundus",
56
+ "fq_testfundus",
57
+ "fq_rawfundus",
58
+ "fq_validfundus",
59
+ ]
60
+
61
+
62
+ def main() -> None:
63
+ args = parse_args()
64
+ args.out.mkdir(parents=True, exist_ok=True)
65
+ reader = load_easyocr_reader(args.ocr)
66
+ tongren_meta = load_tongren_metadata(args.tongren_metadata)
67
+ df = pd.read_parquet(
68
+ args.manifest,
69
+ columns=["image_id", "cohort", "modality", "train_path", "file_path", "rel_path"],
70
+ )
71
+ df = df[df["cohort"].isin(args.cohorts)].copy()
72
+ records = []
73
+ for cohort, group in df.groupby("cohort", sort=True):
74
+ sample = group.sample(n=min(args.per_cohort, len(group)), random_state=args.seed)
75
+ rows = []
76
+ for idx, row in enumerate(sample.to_dict("records")):
77
+ img = read_image_any(str(row.get("train_path") or row.get("file_path")))
78
+ meta = metadata_for_row(row, tongren_meta)
79
+ if not meta and reader is not None:
80
+ meta = ocr_metadata(img, reader)
81
+ masked, ok, info = deidentify_fundus_circle(
82
+ img,
83
+ radius_ratio=args.radius_ratio,
84
+ threshold=args.threshold,
85
+ open_kernel=args.open_kernel,
86
+ )
87
+ left_masked, left_ok, left_info = deidentify_fundus_left_outside_circle(
88
+ img,
89
+ radius_ratio=args.left_radius_ratio,
90
+ left_ratio=args.left_ratio,
91
+ threshold=args.threshold,
92
+ open_kernel=args.open_kernel,
93
+ )
94
+ rows.append([img, masked, left_masked])
95
+ rec = {
96
+ "image_id": row["image_id"],
97
+ "cohort": cohort,
98
+ "source_path": row.get("train_path") or row.get("file_path"),
99
+ "circle_ok": ok,
100
+ "circle_info": info,
101
+ "left_circle_ok": left_ok,
102
+ "left_circle_info": left_info,
103
+ "ocr_age": meta.get("age"),
104
+ "ocr_sex": meta.get("sex"),
105
+ "ocr_eye": meta.get("eye"),
106
+ }
107
+ records.append(rec)
108
+ save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_masked.jpg", masked)
109
+ save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_left_masked.jpg", left_masked)
110
+ make_sheet(
111
+ rows,
112
+ ["source", "full_circle", "left_only_circle"],
113
+ args.out / f"{cohort}_compare.jpg",
114
+ cell=args.cell,
115
+ )
116
+ with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f:
117
+ for rec in records:
118
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
119
+ print(f"DONE -> {args.out} ({len(records)} samples)")
120
+
121
+
122
+ def load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]:
123
+ if not path.exists():
124
+ return {}
125
+ meta = pd.read_csv(path)
126
+ out: dict[str, dict[str, Any]] = {}
127
+ for row in meta.itertuples(index=False):
128
+ sex = {"男": "M", "女": "F"}.get(str(row.sex), None)
129
+ age = None if pd.isna(row.age) else int(row.age)
130
+ eye = eye_from_seq(row.eye_seq)
131
+ out[str(row.filename)] = {"age": age, "sex": sex, "eye": eye}
132
+ return out
133
+
134
+
135
+ def eye_from_seq(value: Any) -> str | None:
136
+ if value is None or (isinstance(value, float) and math.isnan(value)):
137
+ return None
138
+ text = str(int(value)) if isinstance(value, float) else str(value)
139
+ if text == "1":
140
+ return "OD"
141
+ if text == "2":
142
+ return "OS"
143
+ return None
144
+
145
+
146
+ def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]:
147
+ name = str(row.get("rel_path") or Path(str(row.get("train_path") or "")).name)
148
+ return {k: v for k, v in tongren_meta.get(name, {}).items() if v is not None}
149
+
150
+
151
+ def ocr_metadata(img: np.ndarray, reader: object) -> dict[str, Any]:
152
+ from deidentify_trial import parse_ocr_metadata
153
+
154
+ h = img.shape[0]
155
+ crop = img[: int(h * 0.55), :]
156
+ rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
157
+ results = reader.readtext(rgb, detail=0)
158
+ return parse_ocr_metadata(" ".join(str(item) for item in results))
159
+
160
+
161
+ def read_image_any(path: str) -> np.ndarray:
162
+ if "::" in path:
163
+ tar_path, member = path.split("::", 1)
164
+ with tarfile.open(tar_path) as tf:
165
+ fp = tf.extractfile(member)
166
+ if fp is None:
167
+ raise FileNotFoundError(path)
168
+ data = fp.read()
169
+ arr = np.frombuffer(data, dtype=np.uint8)
170
+ else:
171
+ arr = np.fromfile(path, dtype=np.uint8)
172
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
173
+ if img is None:
174
+ raise ValueError(f"failed to decode image: {path}")
175
+ return img
176
+
177
+
178
+ def save_rgb(path: Path, img: np.ndarray) -> None:
179
+ path.parent.mkdir(parents=True, exist_ok=True)
180
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
181
+ Image.fromarray(rgb).save(path, quality=92)
182
+
183
+
184
+ def parse_args() -> argparse.Namespace:
185
+ parser = argparse.ArgumentParser()
186
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
187
+ parser.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_META)
188
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
189
+ parser.add_argument("--cohorts", nargs="+", default=COHORTS)
190
+ parser.add_argument("--per-cohort", type=int, default=8)
191
+ parser.add_argument("--seed", type=int, default=20260702)
192
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
193
+ parser.add_argument("--cell", type=int, default=320)
194
+ parser.add_argument("--radius-ratio", type=float, default=0.97)
195
+ parser.add_argument("--left-radius-ratio", type=float, default=0.985)
196
+ parser.add_argument("--left-ratio", type=float, default=0.55)
197
+ parser.add_argument("--threshold", type=int, default=25)
198
+ parser.add_argument("--open-kernel", type=int, default=25)
199
+ return parser.parse_args()
200
+
201
+
202
+ if __name__ == "__main__":
203
+ main()
data_processing/01_deidentification/test_deidentify_trial.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): test_deidentify_trial.py
4
+ 原本用途 (Original Purpose):
5
+ 几何掩模提取与脱敏算法单元回归测试套件。确保不同长宽比、不同黑边占比的眼底图像在裁切脱敏时视网膜有效组织不会被误切。
6
+ 适用数据集 (Target Dataset):
7
+ 典型异常尺寸、强眩光、偏心光照的测试集样本。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 合成与极端边界用例图像
12
+ 输出结果 (Output):
13
+ 单元测试断言与通过性报告
14
+ 依赖环境 (Dependencies):
15
+ pytest, opencv-python, numpy
16
+ ================================================================================
17
+ """
18
+
19
+ import unittest
20
+ from argparse import Namespace
21
+ from pathlib import Path
22
+ import sys
23
+ import tarfile
24
+ from tempfile import TemporaryDirectory
25
+
26
+ import cv2
27
+ import numpy as np
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
30
+
31
+ from deidentify_batch import metadata_for_row, process_one
32
+ from deidentify_trial import (
33
+ blackout_frame,
34
+ blackout_top_bar,
35
+ crop_top_bar,
36
+ deidentify_fundus_circle,
37
+ deidentify_fundus_left_outside_circle,
38
+ parse_ocr_metadata,
39
+ )
40
+
41
+
42
+ class DeidentifyTrialTest(unittest.TestCase):
43
+ def test_parse_ocr_metadata_keeps_only_non_identifier_fields(self):
44
+ meta = parse_ocr_metadata("张三 61岁 男 OD 2021/05/21 15:15")
45
+
46
+ self.assertEqual(meta, {"age": 61, "sex": "M", "eye": "OD"})
47
+
48
+ def test_fundus_circle_mask_blacks_corner_and_keeps_retina(self):
49
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
50
+ yy, xx = np.ogrid[:160, :160]
51
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
52
+ img[circle] = (90, 80, 70)
53
+ img[:16, :35] = (255, 255, 255)
54
+
55
+ out, ok, _ = deidentify_fundus_circle(img, radius_ratio=0.94, open_kernel=9)
56
+
57
+ self.assertTrue(ok)
58
+ self.assertTrue(np.all(out[4, 4] == 0))
59
+ self.assertTrue(np.all(out[80, 80] == img[80, 80]))
60
+
61
+ def test_left_only_circle_mask_keeps_right_outside_circle(self):
62
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
63
+ yy, xx = np.ogrid[:160, :160]
64
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
65
+ img[circle] = (90, 80, 70)
66
+ img[4, 4] = (255, 255, 255)
67
+ img[4, 150] = (123, 45, 67)
68
+
69
+ out, ok, _ = deidentify_fundus_left_outside_circle(
70
+ img, radius_ratio=0.985, left_ratio=0.55, open_kernel=9
71
+ )
72
+
73
+ self.assertTrue(ok)
74
+ self.assertTrue(np.all(out[4, 4] == 0))
75
+ self.assertTrue(np.all(out[80, 80] == img[80, 80]))
76
+ self.assertTrue(np.array_equal(out[4, 150], img[4, 150]))
77
+
78
+ def test_blackout_top_bar_preserves_shape_and_masks_top_rows(self):
79
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
80
+
81
+ out = blackout_top_bar(img, ratio=0.12)
82
+
83
+ self.assertEqual(out.shape, img.shape)
84
+ self.assertTrue(np.all(out[:12] == 0))
85
+ self.assertTrue(np.all(out[12:] == 128))
86
+
87
+ def test_blackout_frame_masks_top_bottom_and_right_without_resizing(self):
88
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
89
+
90
+ out = blackout_frame(img, top=0.08, bottom=0.05, right=0.02)
91
+
92
+ self.assertEqual(out.shape, img.shape)
93
+ self.assertTrue(np.all(out[:8, :] == 0))
94
+ self.assertTrue(np.all(out[95:, :] == 0))
95
+ self.assertTrue(np.all(out[:, 78:] == 0))
96
+ self.assertTrue(np.all(out[8:95, :78] == 128))
97
+
98
+ def test_crop_top_bar_removes_requested_fraction(self):
99
+ img = np.arange(100 * 80 * 3, dtype=np.uint8).reshape(100, 80, 3)
100
+
101
+ out = crop_top_bar(img, ratio=0.12)
102
+
103
+ self.assertEqual(out.shape, (88, 80, 3))
104
+ self.assertTrue(np.array_equal(out[0], img[12]))
105
+
106
+ def test_process_one_bscan_writes_opaque_jpeg_and_metadata(self):
107
+ with TemporaryDirectory() as tmp:
108
+ tmp_path = Path(tmp)
109
+ src = tmp_path / "source.bmp"
110
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
111
+ ok, encoded = cv2.imencode(".bmp", img)
112
+ self.assertTrue(ok)
113
+ encoded.tofile(str(src))
114
+
115
+ args = Namespace(
116
+ out_root=tmp_path / "out",
117
+ bscan_top=0.10,
118
+ bscan_bottom=0.05,
119
+ bscan_right=0.02,
120
+ overwrite_images=False,
121
+ jpeg_quality=95,
122
+ )
123
+ row = {
124
+ "image_id": "xiangya_bscan_00000001",
125
+ "cohort": "xiangya_bscan",
126
+ "file_path": str(src),
127
+ }
128
+
129
+ result = process_one(row, args, reader=None)
130
+
131
+ out_path = tmp_path / "out" / "images" / "xiangya_bscan" / "xiangya_bscan_00000001.jpg"
132
+ self.assertTrue(out_path.exists())
133
+ self.assertEqual(result["deid_path"], str(out_path))
134
+ self.assertEqual(result["deid_method"], "bscan_blackout_top10_bottom5_right2")
135
+ self.assertTrue(result["pii_masked"])
136
+
137
+ def test_process_one_left_fundus_reads_tar_member(self):
138
+ with TemporaryDirectory() as tmp:
139
+ tmp_path = Path(tmp)
140
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
141
+ yy, xx = np.ogrid[:160, :160]
142
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
143
+ img[circle] = (90, 80, 70)
144
+ img[4, 4] = (255, 255, 255)
145
+ ok, encoded = cv2.imencode(".png", img)
146
+ self.assertTrue(ok)
147
+
148
+ tar_path = tmp_path / "sample.tar"
149
+ png_path = tmp_path / "sample.png"
150
+ encoded.tofile(str(png_path))
151
+ with tarfile.open(tar_path, "w") as tf:
152
+ tf.add(png_path, arcname="sample.png")
153
+
154
+ args = Namespace(
155
+ out_root=tmp_path / "out",
156
+ overwrite_images=False,
157
+ jpeg_quality=95,
158
+ fundus_threshold=25,
159
+ fundus_open_kernel=9,
160
+ left_fundus_radius_ratio=0.985,
161
+ left_fundus_ratio=0.55,
162
+ )
163
+ row = {
164
+ "image_id": "tongren_fundus_00000001",
165
+ "cohort": "tongren_fundus",
166
+ "train_path": f"{tar_path}::sample.png",
167
+ "file_path": f"{tar_path}::sample.png",
168
+ "ocr_age": 61,
169
+ "ocr_sex": "F",
170
+ "ocr_eye": "OD",
171
+ }
172
+
173
+ result = process_one(row, args, reader=None)
174
+
175
+ self.assertTrue(Path(result["deid_path"]).exists())
176
+ self.assertEqual(result["deid_method"], "fundus_left_outside_circle_mask_r0985_l055")
177
+ self.assertEqual(result["ocr_age"], 61)
178
+ self.assertEqual(result["ocr_sex"], "F")
179
+
180
+ def test_tongren_metadata_is_not_applied_to_fq_rows(self):
181
+ meta = {"1005653-1.png": {"age": 63, "sex": "F", "eye": "OD"}}
182
+
183
+ self.assertEqual(
184
+ metadata_for_row(
185
+ {
186
+ "cohort": "fq_rawfundus",
187
+ "rel_path": "1005653-1.png",
188
+ "train_path": "/nfs01/FQ_Datasets/data/rawFundus/1005653-1.png",
189
+ },
190
+ meta,
191
+ ),
192
+ {},
193
+ )
194
+ self.assertEqual(
195
+ metadata_for_row(
196
+ {
197
+ "cohort": "tongren_fundus",
198
+ "rel_path": "1005653-1.png",
199
+ "train_path": "/data/team/lisicheng/Dataser/shards_tongren/fundus/a.tar::1005653-1.png",
200
+ },
201
+ meta,
202
+ ),
203
+ {"age": 63, "sex": "F", "eye": "OD"},
204
+ )
205
+
206
+
207
+ if __name__ == "__main__":
208
+ unittest.main()
data_processing/02_quality_control/asrm_preprocess.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): asrm_preprocess.py
4
+ 原本用途 (Original Purpose):
5
+ 基于 ASRMNet 深度卷积网络的眼底图像质量自动评估与质控前处理。评估眼底相片的照明均匀度、模糊伪影、屈光介质浑浊以及临床可诊断性(Gradability),输出质量分级并拦截不可评样本。
6
+ 适用数据集 (Target Dataset):
7
+ 全库彩色眼底图像(CFP),包括单中心门诊及大规模筛查图像。
8
+ 作者与归属 (Author/Provenance):
9
+ 张焕 (Zhanghuan), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 待评测的彩色眼底相片(JPG/PNG)
12
+ 输出结果 (Output):
13
+ 图像质量评分(可诊断/可疑/不可诊断)及预处理归一化图像
14
+ 依赖环境 (Dependencies):
15
+ torch, torchvision, opencv-python, numpy, pillow
16
+ ================================================================================
17
+ """
18
+
19
+ import os
20
+ import cv2
21
+ import torch
22
+ import numpy as np
23
+ from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
24
+ from torchvision import transforms
25
+ from typing import List, Tuple, Dict
26
+ import random
27
+
28
+
29
+ class FundusQualityDataset(Dataset):
30
+ """
31
+ Dataset for fundus quality classification
32
+ Combines:
33
+ - Labeled invalid images
34
+ - Labeled valid images
35
+ - Unlabeled raw images (optional)
36
+ """
37
+ def __init__(
38
+ self,
39
+ invalid_dir: str,
40
+ valid_dir: str,
41
+ raw_dir: str = None,
42
+ img_size: int = 512,
43
+ transform=None,
44
+ use_raw: bool = False,
45
+ raw_pseudo_label_threshold: float = 0.5
46
+ ):
47
+ self.img_size = img_size
48
+ self.transform = transform
49
+ self.use_raw = use_raw
50
+ self.raw_pseudo_label_threshold = raw_pseudo_label_threshold
51
+
52
+ # Load labeled data
53
+ self.invalid_paths = self._load_image_paths(invalid_dir)
54
+ self.valid_paths = self._load_image_paths(valid_dir)
55
+
56
+ # Load unlabeled raw data
57
+ self.raw_paths = []
58
+ if use_raw and raw_dir is not None:
59
+ self.raw_paths = self._load_image_paths(raw_dir)
60
+
61
+ # Combine all paths and create labels
62
+ self.image_paths = []
63
+ self.labels = []
64
+ self.is_labeled = []
65
+
66
+ # Invalid images (label=0)
67
+ for path in self.invalid_paths:
68
+ self.image_paths.append(path)
69
+ self.labels.append(0)
70
+ self.is_labeled.append(True)
71
+
72
+ # Valid images (label=1)
73
+ for path in self.valid_paths:
74
+ self.image_paths.append(path)
75
+ self.labels.append(1)
76
+ self.is_labeled.append(True)
77
+
78
+ # Raw images (unlabeled, label=-1 initially)
79
+ if use_raw:
80
+ for path in self.raw_paths:
81
+ self.image_paths.append(path)
82
+ self.labels.append(-1) # Pseudo label placeholder
83
+ self.is_labeled.append(False)
84
+
85
+ # Pseudo labels dict (for raw images)
86
+ self.pseudo_labels = {}
87
+
88
+ print(f"Dataset loaded: {len(self.invalid_paths)} invalid, "
89
+ f"{len(self.valid_paths)} valid, "
90
+ f"{len(self.raw_paths)} raw")
91
+
92
+ # f:\oinn\image_filter\FQ-ManifoldNet\model_ASRMNet\asrm_preprocess.py
93
+
94
+ # 修改第30行附近的 _load_image_paths 函数
95
+ def _load_image_paths(self, directory: str) -> List[str]:
96
+ """Load all image paths from directory"""
97
+ if not os.path.exists(directory):
98
+ print(f"⚠️ 目录不存在: {directory}")
99
+ return []
100
+
101
+ image_paths = []
102
+ # 支持的扩展名(包含DICOM格式)
103
+ valid_extensions = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.bmp', '.dcm')
104
+
105
+ # 列出所有文件进行调试
106
+ all_files = os.listdir(directory)
107
+ print(f"📂 {os.path.basename(directory)}: 找到 {len(all_files)} 个文件")
108
+
109
+ # 尝试多种方式扫描
110
+ for filename in all_files:
111
+ # 方法1: 检查小写扩展名
112
+ if filename.lower().endswith(valid_extensions):
113
+ image_paths.append(os.path.join(directory, filename))
114
+
115
+ print(f"✅ {os.path.basename(directory)}: 成功加载 {len(image_paths)} 张图像")
116
+
117
+ # 如果还是0,尝试直接使用所有文件(跳过目录)
118
+ if len(image_paths) == 0:
119
+ print(f"🔍 {os.path.basename(directory)}: 尝试直接使用所有文件...")
120
+ for filename in all_files:
121
+ filepath = os.path.join(directory, filename)
122
+ if os.path.isfile(filepath):
123
+ image_paths.append(filepath)
124
+ print(f" 第二次尝试: 加载了 {len(image_paths)} 张")
125
+
126
+ return image_paths
127
+
128
+ def set_pseudo_labels(self, pseudo_label_dict: Dict[str, float]):
129
+ """
130
+ Set pseudo labels for raw images
131
+ Args:
132
+ pseudo_label_dict: {image_path: quality_score} (0-1)
133
+ """
134
+ self.pseudo_labels = pseudo_label_dict
135
+
136
+ def __len__(self) -> int:
137
+ return len(self.image_paths)
138
+
139
+ def __getitem__(self, idx: int) -> Dict:
140
+ img_path = self.image_paths[idx]
141
+
142
+ # Load image
143
+ img = cv2.imread(img_path)
144
+ if img is None:
145
+ # Return empty image if loading fails
146
+ img = np.zeros((self.img_size, self.img_size, 3), dtype=np.uint8)
147
+
148
+ # Convert to RGB
149
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
150
+
151
+ # Resize
152
+ img = cv2.resize(img, (self.img_size, self.img_size))
153
+
154
+ # Apply transforms
155
+ if self.transform is not None:
156
+ img = self.transform(img)
157
+
158
+ # Get label
159
+ if self.is_labeled[idx]:
160
+ label = self.labels[idx]
161
+ else:
162
+ # Use pseudo label if available, else return -1
163
+ if img_path in self.pseudo_labels:
164
+ score = self.pseudo_labels[img_path]
165
+ label = 1 if score > self.raw_pseudo_label_threshold else 0
166
+ else:
167
+ label = -1
168
+
169
+ return {
170
+ 'image': img,
171
+ 'label': label,
172
+ 'is_labeled': self.is_labeled[idx],
173
+ 'path': img_path
174
+ }
175
+
176
+
177
+ def get_train_transforms(img_size: int = 512):
178
+ """Training data transforms with augmentation"""
179
+ return transforms.Compose([
180
+ transforms.ToPILImage(),
181
+ transforms.RandomHorizontalFlip(p=0.5),
182
+ transforms.RandomRotation(degrees=15),
183
+ transforms.ColorJitter(
184
+ brightness=0.2,
185
+ contrast=0.2,
186
+ saturation=0.2,
187
+ hue=0.1
188
+ ),
189
+ transforms.ToTensor(),
190
+ transforms.Normalize(
191
+ mean=[0.485, 0.456, 0.406],
192
+ std=[0.229, 0.224, 0.225]
193
+ )
194
+ ])
195
+
196
+
197
+ def get_val_transforms(img_size: int = 512):
198
+ """Validation/test data transforms (no augmentation)"""
199
+ return transforms.Compose([
200
+ transforms.ToPILImage(),
201
+ transforms.ToTensor(),
202
+ transforms.Normalize(
203
+ mean=[0.485, 0.456, 0.406],
204
+ std=[0.229, 0.224, 0.225]
205
+ )
206
+ ])
207
+
208
+
209
+ def create_data_loaders(
210
+ invalid_dir: str,
211
+ valid_dir: str,
212
+ raw_dir: str = None,
213
+ img_size: int = 512,
214
+ batch_size: int = 32,
215
+ num_workers: int = 8,
216
+ use_raw: bool = False,
217
+ use_weighted_sampler: bool = True
218
+ ) -> Tuple[DataLoader, DataLoader]:
219
+ """
220
+ Create train and validation data loaders
221
+ Args:
222
+ invalid_dir: Directory with invalid fundus images
223
+ valid_dir: Directory with valid fundus images
224
+ raw_dir: Directory with raw unlabeled images (optional)
225
+ img_size: Target image size
226
+ batch_size: Batch size
227
+ num_workers: Number of data loading workers
228
+ use_raw: Whether to include raw unlabeled images
229
+ use_weighted_sampler: Whether to use weighted sampler for class imbalance
230
+ Returns:
231
+ (train_loader, val_loader)
232
+ """
233
+ # Create train dataset
234
+ train_dataset = FundusQualityDataset(
235
+ invalid_dir=invalid_dir,
236
+ valid_dir=valid_dir,
237
+ raw_dir=raw_dir,
238
+ img_size=img_size,
239
+ transform=get_train_transforms(img_size),
240
+ use_raw=use_raw
241
+ )
242
+
243
+ # Split into train/val
244
+ dataset_size = len(train_dataset)
245
+ val_size = int(0.2 * dataset_size)
246
+ train_size = dataset_size - val_size
247
+
248
+ from torch.utils.data import random_split
249
+ train_subset, val_subset = random_split(
250
+ train_dataset,
251
+ [train_size, val_size],
252
+ generator=torch.Generator().manual_seed(42)
253
+ )
254
+
255
+ # Create samplers
256
+ if use_weighted_sampler:
257
+ # Weighted sampler to handle class imbalance
258
+ labeled_indices = [i for i in range(len(train_dataset))
259
+ if train_dataset.is_labeled[i]]
260
+
261
+ if len(labeled_indices) > 0:
262
+ labeled_labels = [train_dataset.labels[i] for i in labeled_indices]
263
+ class_counts = np.bincount(labeled_labels, minlength=2)
264
+ class_weights = 1.0 / (class_counts + 1e-8)
265
+
266
+ # Create weights for all samples (unlabeled get weight 1)
267
+ weights = torch.ones(len(train_subset))
268
+ for idx_in_subset, idx_in_dataset in enumerate(train_subset.indices):
269
+ if train_dataset.is_labeled[idx_in_dataset]:
270
+ label = train_dataset.labels[idx_in_dataset]
271
+ weights[idx_in_subset] = class_weights[label]
272
+
273
+ sampler = WeightedRandomSampler(weights, len(weights))
274
+ else:
275
+ sampler = None
276
+ else:
277
+ sampler = None
278
+
279
+ # Create data loaders
280
+ train_loader = DataLoader(
281
+ train_subset,
282
+ batch_size=batch_size,
283
+ sampler=sampler,
284
+ shuffle=(sampler is None),
285
+ num_workers=num_workers,
286
+ pin_memory=True,
287
+ drop_last=True
288
+ )
289
+
290
+ val_loader = DataLoader(
291
+ val_subset,
292
+ batch_size=batch_size,
293
+ shuffle=False,
294
+ num_workers=num_workers,
295
+ pin_memory=True
296
+ )
297
+
298
+ return train_loader, val_loader
data_processing/02_quality_control/build_hcw_semantic_patch.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): build_hcw_semantic_patch.py
4
+ 原本用途 (Original Purpose):
5
+ 隐私安全的 HCW 眼底诊断侧卡(Sidecar Patch)与 Caption 生成脚本。完全剥离患者住院号、就诊日期、自由病历文本等隐私字段,只保留合规图像 ID、ICD 编码与主诊断,生成轻量化 Parquet 标签集。
6
+ 适用数据集 (Target Dataset):
7
+ archives/data0410/ 中的 fundus_hcw / hcw_fundus 眼底大集。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 胡成伟清洗后的原始工作簿与 release manifest
12
+ 输出结果 (Output):
13
+ 去隐私后的结构化诊断 Parquet 侧卡(包含 image_name, diag_name, diag_icd 等)
14
+ 依赖环境 (Dependencies):
15
+ pandas, pyarrow, json
16
+ ================================================================================
17
+ """
18
+
19
+ """Build a privacy-safe HCW fundus diagnosis sidecar and caption patch.
20
+
21
+ Only image identifiers and clinical label fields are exported. Patient, visit,
22
+ date and free-report columns in the source workbooks are never copied.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import re
30
+ from collections import Counter
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ import pandas as pd
35
+ import pyarrow.parquet as pq
36
+
37
+
38
+ COHORT = "hcw_fundus"
39
+ BASE_PROMPT = "ophthalmic image, color fundus photography, standard field of view, retina"
40
+ SAFE_SOURCE_COLUMNS = {"image_name", "diag_name", "diag_icd", "is_primary"}
41
+
42
+
43
+ def _clean(value: Any) -> str:
44
+ if value is None:
45
+ return ""
46
+ try:
47
+ if pd.isna(value):
48
+ return ""
49
+ except (TypeError, ValueError):
50
+ pass
51
+ return re.sub(r"\s+", " ", str(value)).strip(" ,,;;")
52
+
53
+
54
+ def _unique(values: list[str]) -> list[str]:
55
+ result: list[str] = []
56
+ seen: set[str] = set()
57
+ for value in values:
58
+ value = _clean(value)
59
+ key = value.casefold()
60
+ if value and key not in seen:
61
+ result.append(value)
62
+ seen.add(key)
63
+ return result
64
+
65
+
66
+ def _load_release(path: Path, batch_size: int) -> pd.DataFrame:
67
+ parts: list[pd.DataFrame] = []
68
+ parquet = pq.ParquetFile(path)
69
+ columns = ["image_id", "file_path", "cohort", "diagnosis_group_clean"]
70
+ missing = set(columns) - set(parquet.schema_arrow.names)
71
+ if missing:
72
+ raise ValueError(f"release manifest missing columns: {sorted(missing)}")
73
+ for batch in parquet.iter_batches(columns=columns, batch_size=batch_size):
74
+ frame = batch.to_pandas()
75
+ frame = frame[frame["cohort"].eq(COHORT)]
76
+ if not frame.empty:
77
+ parts.append(frame)
78
+ if not parts:
79
+ raise ValueError(f"release manifest contains no {COHORT} rows")
80
+ release = pd.concat(parts, ignore_index=True)
81
+ if len(release) != release["image_id"].nunique():
82
+ raise ValueError("release HCW image_id is not unique")
83
+ release["stem"] = release["file_path"].map(lambda value: Path(str(value)).stem)
84
+ if release["stem"].duplicated().any():
85
+ raise ValueError("release HCW file stems are not unique")
86
+ return release
87
+
88
+
89
+ def _load_workbook(path: Path, source_name: str) -> pd.DataFrame:
90
+ frame = pd.read_excel(path, keep_default_na=False)
91
+ missing = SAFE_SOURCE_COLUMNS - set(frame.columns)
92
+ if missing:
93
+ raise ValueError(f"{path} missing columns: {sorted(missing)}")
94
+ safe = frame[list(SAFE_SOURCE_COLUMNS)].copy()
95
+ safe["stem"] = safe["image_name"].map(lambda value: Path(str(value)).stem)
96
+ safe["diag_name"] = safe["diag_name"].map(_clean)
97
+ safe["diag_icd"] = safe["diag_icd"].map(_clean)
98
+ safe["is_primary"] = safe["is_primary"].astype(str).str.strip().eq("是")
99
+ safe["source_table"] = source_name
100
+ safe = safe[safe["stem"].ne("") & safe["diag_name"].ne("")]
101
+ return safe.drop(columns=["image_name"])
102
+
103
+
104
+ def _dram_labels(name: str, icd: str) -> tuple[list[str], list[str], list[str]]:
105
+ text = f"{name} {icd}".casefold()
106
+ families: list[str] = []
107
+ subtypes: list[str] = []
108
+ findings: list[str] = []
109
+ if "糖尿病" in text or "糖尿病视网膜" in text or "h36" in text:
110
+ families.append("diabetic retinopathy")
111
+ if "增殖" in text:
112
+ subtypes.append("proliferative diabetic retinopathy")
113
+ elif "背景" in text or "斑点" in text:
114
+ subtypes.append("non-proliferative diabetic retinopathy")
115
+ if "分支静脉阻塞" in text:
116
+ families.append("retinal vein occlusion")
117
+ subtypes.append("branch retinal vein occlusion")
118
+ elif "中心性静脉阻塞" in text or "中央静脉阻塞" in text:
119
+ families.append("retinal vein occlusion")
120
+ subtypes.append("central retinal vein occlusion")
121
+ elif "静脉阻塞" in text:
122
+ families.append("retinal vein occlusion")
123
+ if "老年性黄斑变性" in text:
124
+ families.append("age-related macular degeneration")
125
+ if "渗出性" in text:
126
+ subtypes.append("neovascular age-related macular degeneration")
127
+ elif "萎缩性" in text:
128
+ subtypes.append("non-neovascular age-related macular degeneration")
129
+ if "黄斑水肿" in text or "视网膜增厚" in text:
130
+ findings.append("macular edema")
131
+ if "牵拉性视网膜脱离" in text:
132
+ findings.append("tractional retinal detachment")
133
+ if "玻璃体出血" in text:
134
+ findings.append("vitreous hemorrhage")
135
+ return _unique(families), _unique(subtypes), _unique(findings)
136
+
137
+
138
+ GLAUCOMA_TERMS = re.compile(
139
+ r"青光眼|闭角|开角|新生血管|继发|先天|青少年|发育|正常眼压|色素|"
140
+ r"睫状体炎|眼压失控|恶性|无晶状体|晶状体脱位|血影细胞"
141
+ )
142
+
143
+
144
+ def _glaucoma_labels(name: str, icd: str) -> tuple[list[str], list[str], list[str]]:
145
+ text = f"{name} {icd}".casefold()
146
+ glaucoma_evidence = bool(
147
+ GLAUCOMA_TERMS.search(text)
148
+ or re.search(r"\b(?:h40|h42|q15)", text, re.I)
149
+ )
150
+ if not glaucoma_evidence:
151
+ return [], [], []
152
+ families = ["glaucoma"]
153
+ subtypes: list[str] = []
154
+ if "新生血管" in text:
155
+ subtypes.append("neovascular glaucoma")
156
+ if "闭角" in text:
157
+ subtypes.append("angle-closure glaucoma")
158
+ if "开角" in text:
159
+ subtypes.append("open-angle glaucoma")
160
+ if "继发" in text:
161
+ subtypes.append("secondary glaucoma")
162
+ if "先天" in text or "发育" in text or "青少年" in text or icd.upper().startswith("Q15"):
163
+ subtypes.append("developmental glaucoma")
164
+ if "正常眼压" in text:
165
+ subtypes.append("normal-tension glaucoma")
166
+ if "色素" in text:
167
+ subtypes.append("pigmentary glaucoma")
168
+ return families, _unique(subtypes), []
169
+
170
+
171
+ def _aggregate_labels(group: pd.DataFrame) -> dict[str, Any]:
172
+ families: list[str] = []
173
+ subtypes: list[str] = []
174
+ findings: list[str] = []
175
+ for row in group.itertuples(index=False):
176
+ if row.source_table == "dramdrvo_cleaned.xlsx":
177
+ result = _dram_labels(row.diag_name, row.diag_icd)
178
+ else:
179
+ result = _glaucoma_labels(row.diag_name, row.diag_icd)
180
+ families.extend(result[0])
181
+ subtypes.extend(result[1])
182
+ findings.extend(result[2])
183
+ primary = group[group["is_primary"]]
184
+ primary_row = primary.iloc[0] if not primary.empty else group.iloc[0]
185
+ return {
186
+ "source_tables": _unique(group["source_table"].tolist()),
187
+ "diagnosis_raw": _unique(group["diag_name"].tolist()),
188
+ "diagnosis_icd": _unique(group["diag_icd"].tolist()),
189
+ "primary_diagnosis_raw": _clean(primary_row["diag_name"]),
190
+ "primary_diagnosis_icd": _clean(primary_row["diag_icd"]),
191
+ "diagnosis_families": _unique(families),
192
+ "diagnosis_subtypes": _unique(subtypes),
193
+ "finding_tags": _unique(findings),
194
+ }
195
+
196
+
197
+ def _prompt_rows(row: pd.Series) -> list[dict[str, str]]:
198
+ families = list(row["diagnosis_families"])
199
+ subtypes = list(row["diagnosis_subtypes"])
200
+ findings = list(row["finding_tags"])
201
+ medium_parts = [BASE_PROMPT, *(f"diagnosis: {value}" for value in families)]
202
+ dense_parts = [
203
+ *medium_parts,
204
+ *(f"subtype: {value}" for value in subtypes),
205
+ *findings,
206
+ ]
207
+ prompts = {
208
+ "short": BASE_PROMPT,
209
+ "medium": ", ".join(_unique(medium_parts)),
210
+ "dense": ", ".join(_unique(dense_parts)),
211
+ }
212
+ image_id = str(row["image_id"])
213
+ return [
214
+ {
215
+ "caption_id": f"{image_id}_{level}",
216
+ "image_id": image_id,
217
+ "level": level,
218
+ "prompt_text": prompt,
219
+ "language": "en",
220
+ "generator": "ophgen_semantic_patch_hcw_v1",
221
+ "grounded_in": "v10.1+hcw_cleaned_diagnosis_tables+canonical_taxonomy_v1",
222
+ }
223
+ for level, prompt in prompts.items()
224
+ ]
225
+
226
+
227
+ def build(args: argparse.Namespace) -> None:
228
+ args.out.mkdir(parents=True, exist_ok=True)
229
+ release = _load_release(args.release_manifest, args.batch_size)
230
+ workbooks = pd.concat(
231
+ [
232
+ _load_workbook(args.dramdrvo, "dramdrvo_cleaned.xlsx"),
233
+ _load_workbook(args.glaucoma, "glaucoma_cleaned.xlsx"),
234
+ ],
235
+ ignore_index=True,
236
+ )
237
+ release_stems = set(release["stem"])
238
+ workbooks = workbooks[workbooks["stem"].isin(release_stems)].copy()
239
+ workbook_stems = set(workbooks["stem"])
240
+ missing_stems = release_stems - workbook_stems
241
+ if missing_stems:
242
+ raise ValueError(f"{len(missing_stems)} release HCW images lack a cleaned diagnosis join")
243
+
244
+ records: list[dict[str, Any]] = []
245
+ for stem, group in workbooks.groupby("stem", sort=False):
246
+ records.append({"stem": stem, **_aggregate_labels(group)})
247
+ semantics = release.merge(
248
+ pd.DataFrame(records), on="stem", how="left", validate="one_to_one"
249
+ )
250
+ semantics["prompt_eligible"] = semantics["diagnosis_families"].map(bool)
251
+ eligible = semantics[semantics["prompt_eligible"]].copy()
252
+ if eligible.empty:
253
+ raise ValueError("no HCW images have prompt-eligible canonical diagnoses")
254
+
255
+ safe_columns = [
256
+ "image_id",
257
+ "cohort",
258
+ "source_tables",
259
+ "diagnosis_raw",
260
+ "diagnosis_icd",
261
+ "primary_diagnosis_raw",
262
+ "primary_diagnosis_icd",
263
+ "diagnosis_families",
264
+ "diagnosis_subtypes",
265
+ "finding_tags",
266
+ "diagnosis_group_clean",
267
+ "prompt_eligible",
268
+ ]
269
+ semantics[safe_columns].to_parquet(args.out / "hcw_image_semantics.parquet", index=False)
270
+
271
+ caption_rows: list[dict[str, str]] = []
272
+ for _, row in eligible.iterrows():
273
+ caption_rows.extend(_prompt_rows(row))
274
+ captions = pd.DataFrame(caption_rows)
275
+ captions.to_parquet(args.out / "hcw_caption_patch.parquet", index=False)
276
+
277
+ family_counts = Counter(
278
+ family for families in eligible["diagnosis_families"] for family in families
279
+ )
280
+ subtype_counts = Counter(
281
+ subtype for subtypes in eligible["diagnosis_subtypes"] for subtype in subtypes
282
+ )
283
+ summary_rows = [
284
+ {"label_type": "family", "label": label, "images": count}
285
+ for label, count in family_counts.items()
286
+ ] + [
287
+ {"label_type": "subtype", "label": label, "images": count}
288
+ for label, count in subtype_counts.items()
289
+ ]
290
+ pd.DataFrame(summary_rows).sort_values(
291
+ ["label_type", "images", "label"], ascending=[True, False, True]
292
+ ).to_csv(args.out / "hcw_class_summary.csv", index=False)
293
+
294
+ source_stems = {
295
+ source: int(workbooks.loc[workbooks["source_table"].eq(source), "stem"].nunique())
296
+ for source in sorted(workbooks["source_table"].unique())
297
+ }
298
+ level_counts = captions["level"].value_counts().to_dict()
299
+ validation = {
300
+ "source_read_only": True,
301
+ "release_hcw_images": int(len(release)),
302
+ "release_hcw_unique_stems": int(release["stem"].nunique()),
303
+ "cleaned_workbook_joined_stems": source_stems,
304
+ "cleaned_workbook_union_stems": int(workbooks["stem"].nunique()),
305
+ "cleaned_workbook_overlap_stems": int(
306
+ workbooks.groupby("stem")["source_table"].nunique().gt(1).sum()
307
+ ),
308
+ "prompt_eligible_images": int(len(eligible)),
309
+ "prompt_ineligible_images": int(len(semantics) - len(eligible)),
310
+ "current_diagnosis_nonempty": int(
311
+ semantics["diagnosis_group_clean"].fillna("").astype(str).str.strip().ne("").sum()
312
+ ),
313
+ "patched_caption_rows": int(len(captions)),
314
+ "patched_caption_level_counts": {key: int(value) for key, value in level_counts.items()},
315
+ "output_columns": safe_columns,
316
+ "pii_columns_exported": False,
317
+ "output_type": "privacy-safe sidecar and caption delta; source files were not modified",
318
+ }
319
+ (args.out / "validation.json").write_text(
320
+ json.dumps(validation, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
321
+ )
322
+ print(json.dumps(validation, ensure_ascii=False, indent=2))
323
+
324
+
325
+ def parse_args() -> argparse.Namespace:
326
+ parser = argparse.ArgumentParser()
327
+ parser.add_argument("--release-manifest", type=Path, required=True)
328
+ parser.add_argument("--dramdrvo", type=Path, required=True)
329
+ parser.add_argument("--glaucoma", type=Path, required=True)
330
+ parser.add_argument("--out", type=Path, required=True)
331
+ parser.add_argument("--batch-size", type=int, default=250_000)
332
+ return parser.parse_args()
333
+
334
+
335
+ if __name__ == "__main__":
336
+ build(parse_args())
data_processing/02_quality_control/build_quality_risk_review.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): build_quality_risk_review.py
4
+ 原本用途 (Original Purpose):
5
+ 多中心全量图像质量风险综合排查工具。全库扫描破损图像文件头、极端长宽比(Aspect ratio)、纯黑/纯白曝光异常样本,产出风险样本审计清单。
6
+ 适用数据集 (Target Dataset):
7
+ 全库 430 万+ 图文资产,覆盖 7 大影像模态(CFP, OCT, UBM, UWF, B-Scan 等)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 全量图像索引 Manifest(Parquet 格式)
12
+ 输出结果 (Output):
13
+ 质量风险审计报告与离群点待复审清单
14
+ 依赖环境 (Dependencies):
15
+ pyarrow, pandas, pillow, numpy
16
+ ================================================================================
17
+ """
18
+
19
+ """Build an embedded HTML review page for high-risk training rows.
20
+
21
+ This is a targeted human-QC sampler for prompt-adapter manifests. It does not
22
+ modify source images or training manifests.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import base64
29
+ import csv
30
+ import html
31
+ import io
32
+ import json
33
+ import math
34
+ import random
35
+ import tarfile
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+ import pandas as pd
40
+ from PIL import Image
41
+
42
+
43
+ DEFAULT_MANIFEST = Path(
44
+ "/data/team/lisicheng/new_data_manifest/"
45
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/adapter_manifest_mixed_v6.parquet"
46
+ )
47
+ DEFAULT_CAPTIONS = Path(
48
+ "/data/team/lisicheng/new_data_manifest/"
49
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/captions_v2.parquet"
50
+ )
51
+ DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/v6_quality_risk_review_20260709")
52
+
53
+ HIGH_RISK_COHORTS = [
54
+ "data0410_master_fundus",
55
+ "chengdu_shiyi_ubm",
56
+ "eryuan_ubm",
57
+ "yinhai_ubm",
58
+ "yinhai_bscan",
59
+ "xiangya_bscan",
60
+ "chengdu_bscan",
61
+ "yinhai_uwf",
62
+ "eryuan_ffa",
63
+ "eryuan_t17_fundus",
64
+ "hcw_fundus",
65
+ ]
66
+ DEID_SANITY_COHORTS = [
67
+ "fundus90wer",
68
+ "tongren_fundus",
69
+ "tongren_95disease_fundus",
70
+ "tongren_external_fundus",
71
+ "fq_rawfundus",
72
+ "fq_testfundus",
73
+ ]
74
+ RARE_OR_CONFUSABLE_SUBTYPES = [
75
+ "octa_enface",
76
+ "oct_enface",
77
+ "slit_lamp_anterior_segment",
78
+ "reflectance_slo_gray",
79
+ "fundus_fluorescein_angiography",
80
+ "uwf_color_fundus",
81
+ "external_anterior_segment_photo",
82
+ "ocular_bscan_ultrasound",
83
+ "ubm_anterior_segment",
84
+ ]
85
+
86
+
87
+ class ImageOpener:
88
+ def __init__(self) -> None:
89
+ self._tar_cache: dict[str, tarfile.TarFile] = {}
90
+
91
+ def close(self) -> None:
92
+ for tf in self._tar_cache.values():
93
+ tf.close()
94
+ self._tar_cache.clear()
95
+
96
+ def open(self, path: str) -> Image.Image:
97
+ if "::" not in path:
98
+ return Image.open(path).convert("RGB")
99
+ tar_path, member = path.split("::", 1)
100
+ tf = self._tar_cache.get(tar_path)
101
+ if tf is None:
102
+ tf = tarfile.open(tar_path, "r:*")
103
+ self._tar_cache[tar_path] = tf
104
+ fh = tf.extractfile(member)
105
+ if fh is None:
106
+ raise FileNotFoundError(member)
107
+ return Image.open(io.BytesIO(fh.read())).convert("RGB")
108
+
109
+
110
+ def clean(value: Any) -> Any:
111
+ if value is None:
112
+ return None
113
+ if isinstance(value, float) and math.isnan(value):
114
+ return None
115
+ return value
116
+
117
+
118
+ def json_safe(value: Any) -> Any:
119
+ if isinstance(value, dict):
120
+ return {str(k): json_safe(v) for k, v in value.items()}
121
+ if isinstance(value, list | tuple):
122
+ return [json_safe(v) for v in value]
123
+ if value is None:
124
+ return None
125
+ if isinstance(value, float):
126
+ return value if math.isfinite(value) else None
127
+ try:
128
+ if pd.isna(value):
129
+ return None
130
+ except (TypeError, ValueError):
131
+ pass
132
+ return value
133
+
134
+
135
+ def sample_group(group: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:
136
+ if len(group) <= n:
137
+ return group
138
+ return group.sample(n=n, random_state=seed)
139
+
140
+
141
+ def add_samples(
142
+ selected: dict[str, dict[str, Any]],
143
+ frame: pd.DataFrame,
144
+ reason: str,
145
+ n: int,
146
+ seed: int,
147
+ group_col: str | None = None,
148
+ ) -> None:
149
+ if len(frame) == 0:
150
+ return
151
+ if group_col:
152
+ pieces = [sample_group(g, n, seed) for _, g in frame.groupby(group_col, sort=True)]
153
+ rows = pd.concat(pieces, ignore_index=True) if pieces else frame.head(0)
154
+ else:
155
+ rows = sample_group(frame, n, seed)
156
+ for row in rows.to_dict("records"):
157
+ image_id = str(row["image_id"])
158
+ if image_id in selected:
159
+ selected[image_id]["risk_reason"] += f"; {reason}"
160
+ else:
161
+ row["risk_reason"] = reason
162
+ selected[image_id] = row
163
+
164
+
165
+ def build_review_rows(args: argparse.Namespace) -> tuple[list[dict[str, Any]], dict[str, Any]]:
166
+ cols = [
167
+ "image_id",
168
+ "cohort",
169
+ "hospital_domain",
170
+ "modality",
171
+ "modality_family",
172
+ "modality_subtype",
173
+ "view_or_projection",
174
+ "field_of_view",
175
+ "image_quality_band",
176
+ "image_quality_score",
177
+ "image_height_px",
178
+ "image_width_px",
179
+ "file_path",
180
+ "prompt_modality_phrase",
181
+ "diagnosis_group_clean",
182
+ ]
183
+ df = pd.read_parquet(args.manifest, columns=cols)
184
+ rng_seed = args.seed
185
+ selected: dict[str, dict[str, Any]] = {}
186
+
187
+ add_samples(
188
+ selected,
189
+ df[df["image_quality_band"].fillna("").astype(str).eq("poor")],
190
+ "显式 poor quality",
191
+ args.poor_per_modality,
192
+ rng_seed,
193
+ "modality_subtype",
194
+ )
195
+ add_samples(
196
+ selected,
197
+ df[df["cohort"].astype(str).isin(HIGH_RISK_COHORTS)],
198
+ "私有原始路径或水印/PII 高风险 cohort",
199
+ args.high_risk_per_cohort,
200
+ rng_seed + 1,
201
+ "cohort",
202
+ )
203
+ add_samples(
204
+ selected,
205
+ df[df["cohort"].astype(str).isin(DEID_SANITY_COHORTS)],
206
+ "已脱敏大 cohort 抽查",
207
+ args.deid_sanity_per_cohort,
208
+ rng_seed + 2,
209
+ "cohort",
210
+ )
211
+ add_samples(
212
+ selected,
213
+ df[df["modality_subtype"].astype(str).isin(RARE_OR_CONFUSABLE_SUBTYPES)],
214
+ "稀有或易混淆 subtype 抽查",
215
+ args.rare_per_subtype,
216
+ rng_seed + 3,
217
+ "modality_subtype",
218
+ )
219
+ top_cohorts = df["cohort"].value_counts().head(args.top_cohorts).index
220
+ add_samples(
221
+ selected,
222
+ df[df["cohort"].astype(str).isin(top_cohorts.astype(str))],
223
+ "大 cohort 随机兜底抽查",
224
+ args.top_per_cohort,
225
+ rng_seed + 4,
226
+ "cohort",
227
+ )
228
+
229
+ rows = list(selected.values())
230
+ random.Random(args.seed).shuffle(rows)
231
+ if args.max_rows and len(rows) > args.max_rows:
232
+ rows = rows[: args.max_rows]
233
+
234
+ ids = [str(r["image_id"]) for r in rows]
235
+ captions = pd.read_parquet(args.captions, columns=["image_id", "level", "prompt_text"])
236
+ captions["image_id"] = captions["image_id"].astype(str)
237
+ wide = captions[captions["image_id"].isin(ids)].pivot(index="image_id", columns="level", values="prompt_text")
238
+
239
+ opener = ImageOpener()
240
+ records: list[dict[str, Any]] = []
241
+ try:
242
+ for idx, row in enumerate(rows, start=1):
243
+ image_id = str(row["image_id"])
244
+ thumb, open_error = thumbnail(opener, str(row["file_path"]), args.thumb_size)
245
+ record = {
246
+ "review_seq": idx,
247
+ **{k: clean(v) for k, v in row.items()},
248
+ "short_prompt": clean(wide["short"].get(image_id)) if "short" in wide else None,
249
+ "medium_prompt": clean(wide["medium"].get(image_id)) if "medium" in wide else None,
250
+ "dense_prompt": clean(wide["dense"].get(image_id)) if "dense" in wide else None,
251
+ "thumb_data": thumb,
252
+ "open_error": open_error,
253
+ }
254
+ records.append(record)
255
+ finally:
256
+ opener.close()
257
+
258
+ summary = {
259
+ "manifest": str(args.manifest),
260
+ "captions": str(args.captions),
261
+ "rows_in_manifest": int(len(df)),
262
+ "review_rows": int(len(records)),
263
+ "risk_reason_counts": pd.Series([r["risk_reason"] for r in records]).value_counts().astype(int).to_dict(),
264
+ "review_by_cohort": pd.Series([r["cohort"] for r in records]).value_counts().astype(int).to_dict(),
265
+ "review_by_modality_subtype": pd.Series([r["modality_subtype"] for r in records]).value_counts().astype(int).to_dict(),
266
+ "poor_quality_rows": int(df["image_quality_band"].fillna("").astype(str).eq("poor").sum()),
267
+ "high_risk_cohort_rows": int(df["cohort"].astype(str).isin(HIGH_RISK_COHORTS).sum()),
268
+ }
269
+ return records, summary
270
+
271
+
272
+ def thumbnail(opener: ImageOpener, path: str, size: int) -> tuple[str, str]:
273
+ try:
274
+ im = opener.open(path)
275
+ im.thumbnail((size, size), Image.Resampling.LANCZOS)
276
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
277
+ canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
278
+ err = ""
279
+ except Exception as exc:
280
+ canvas = Image.new("RGB", (size, size), (100, 15, 15))
281
+ err = repr(exc)
282
+ buf = io.BytesIO()
283
+ canvas.save(buf, format="JPEG", quality=88)
284
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii"), err
285
+
286
+
287
+ def write_csv(records: list[dict[str, Any]], out: Path) -> None:
288
+ cols = [
289
+ "review_seq",
290
+ "risk_reason",
291
+ "image_id",
292
+ "cohort",
293
+ "hospital_domain",
294
+ "modality",
295
+ "modality_family",
296
+ "modality_subtype",
297
+ "view_or_projection",
298
+ "field_of_view",
299
+ "image_quality_band",
300
+ "image_quality_score",
301
+ "image_height_px",
302
+ "image_width_px",
303
+ "prompt_modality_phrase",
304
+ "diagnosis_group_clean",
305
+ "short_prompt",
306
+ "medium_prompt",
307
+ "dense_prompt",
308
+ "file_path",
309
+ "open_error",
310
+ ]
311
+ with out.open("w", newline="", encoding="utf-8-sig") as handle:
312
+ writer = csv.DictWriter(handle, fieldnames=cols)
313
+ writer.writeheader()
314
+ for row in records:
315
+ writer.writerow({col: row.get(col) for col in cols})
316
+
317
+
318
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
319
+ rows_json = json.dumps(json_safe(records), ensure_ascii=False, allow_nan=False).replace("</", "<\\/")
320
+ css = """:root{--bg:#f5f6f8;--panel:#fff;--line:#d8dee8;--text:#1f2937;--muted:#667085;--blue:#0f62fe;--green:#177245;--red:#b42318;--amber:#9a5b00}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:Arial,"Noto Sans CJK SC","Microsoft YaHei",sans-serif}header{position:sticky;top:0;z-index:10;background:var(--panel);border-bottom:1px solid var(--line);padding:12px 16px;box-shadow:0 1px 8px rgba(15,23,42,.07)}h1{font-size:18px;margin:0 0 8px}.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.progress{font-size:13px;min-width:260px;color:var(--muted)}button,select,input,textarea{font-size:13px;border:1px solid #b8c0cc;border-radius:4px;background:#fff;padding:7px 9px}button{cursor:pointer}button.primary{background:var(--blue);border-color:var(--blue);color:#fff}button.ok{background:#e9f7ef;color:var(--green);border-color:#a8ddb9}button.bad{background:#fff1f0;color:var(--red);border-color:#ffccc7}button.warn{background:#fff7e6;color:var(--amber);border-color:#ffd591}.hint{font-size:12px;color:var(--muted);margin-top:6px}.viewer{display:grid;grid-template-columns:minmax(440px,52vw) 1fr;gap:14px;padding:14px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:12px}.imgbox{height:min(68vh,720px);min-height:420px;background:#050505;display:flex;align-items:center;justify-content:center;overflow:hidden}.imgbox img{max-width:100%;max-height:100%;object-fit:contain}.badge{display:inline-block;border-radius:999px;padding:3px 8px;margin:0 5px 6px 0;font-size:12px;background:#edf2ff;color:#173b8f}.badge.warn{background:#fff7e6;color:#8a4b00}.badge.bad{background:#ffecec;color:#9b1c1c}.meta{font-size:13px;line-height:1.5;word-break:break-word}.prompt{font-size:13px;line-height:1.45;margin-top:8px;padding:8px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:4px}.review{border-top:1px solid var(--line);margin-top:10px;padding-top:10px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0}textarea{width:100%;height:72px;resize:vertical}.path{font-family:monospace;font-size:12px;color:#334155}@media(max-width:1000px){.viewer{grid-template-columns:1fr}.imgbox{height:520px}}"""
321
+ js = """
322
+ const rows = JSON.parse(document.getElementById('rows-data').textContent);
323
+ const storageKey = 'octflow_v6_quality_risk_review_20260709';
324
+ function loadState(key, fallback) { try { return localStorage.getItem(key) ?? fallback; } catch (_) { return fallback; } }
325
+ let idx = Number(loadState(storageKey + ':idx', '0') || 0);
326
+ let edits = JSON.parse(loadState(storageKey, '{}') || '{}');
327
+ idx = Math.max(0, Math.min(idx, rows.length - 1));
328
+ function esc(v) { return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
329
+ function edit(id) { return edits[id] || {status:'unreviewed', issue:'', note:''}; }
330
+ function save() { try { localStorage.setItem(storageKey, JSON.stringify(edits)); localStorage.setItem(storageKey + ':idx', String(idx)); } catch (_) {} }
331
+ function counts() { const c={unreviewed:0,keep:0,watermark:0,pii:0,wrong_modality:0,low_quality:0,drop:0}; rows.forEach(r=>{ const s=edit(r.image_id).status || 'unreviewed'; c[s]=(c[s]||0)+1; }); return c; }
332
+ function go(delta) { idx=Math.max(0, Math.min(rows.length-1, idx+delta)); save(); render(); }
333
+ function gotoIndex(v) { const n=Number(v); if (Number.isFinite(n)) { idx=Math.max(0, Math.min(rows.length-1, n-1)); save(); render(); } }
334
+ function setStatus(status, advance=true) { const r=rows[idx]; edits[r.image_id]={...edit(r.image_id),status}; save(); if (advance) go(1); else render(); }
335
+ function updateNote(v) { const r=rows[idx]; edits[r.image_id]={...edit(r.image_id),note:v}; save(); }
336
+ function mergedRows() { return rows.map(r=>{ const x={...r, ...edit(r.image_id)}; delete x.thumb_data; return x; }); }
337
+ function download(name, text, type) { const blob=new Blob([text],{type}); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }
338
+ function exportCSV() { const out=mergedRows(); const cols=['review_seq','status','note','risk_reason','image_id','cohort','hospital_domain','modality','modality_family','modality_subtype','view_or_projection','field_of_view','image_quality_band','image_quality_score','prompt_modality_phrase','diagnosis_group_clean','short_prompt','file_path','open_error']; const csv=[cols.join(',')].concat(out.map(o=>cols.map(c=>'"'+String(o[c]??'').replaceAll('"','""')+'"').join(','))).join('\\n'); download('octflow_v6_quality_risk_review_edits.csv', csv, 'text/csv'); }
339
+ function exportJSON() { download('octflow_v6_quality_risk_review_edits.json', JSON.stringify(mergedRows(), null, 2), 'application/json'); }
340
+ function render() {
341
+ if (!rows.length) { document.getElementById('root').innerHTML='<div class=viewer><div class=panel>没有审核样本。</div></div>'; return; }
342
+ const r=rows[idx], e=edit(r.image_id), c=counts();
343
+ document.getElementById('progress').textContent=`第 ${idx+1} / ${rows.length} 张;保留 ${c.keep||0},水印 ${c.watermark||0},PII ${c.pii||0},错模态 ${c.wrong_modality||0},低质 ${c.low_quality||0},丢弃 ${c.drop||0},未看 ${c.unreviewed||0}`;
344
+ document.getElementById('jump').value=idx+1;
345
+ document.getElementById('root').innerHTML=`<section class="viewer"><div class="panel"><div class="imgbox"><img src="${esc(r.thumb_data)}" loading="eager"></div></div><div class="panel"><div><span class="badge warn">${esc(r.risk_reason)}</span><span class="badge">${esc(r.modality_subtype)}</span><span class="badge">${esc(r.cohort)}</span>${r.open_error ? '<span class="badge bad">读取错误</span>' : ''}</div><div class="meta"><b>图像 ID</b>:${esc(r.image_id)}<br><b>cohort</b>:${esc(r.cohort)};<b>center</b>:${esc(r.hospital_domain)}<br><b>modality</b>:${esc(r.modality)};<b>family</b>:${esc(r.modality_family)};<b>subtype</b>:${esc(r.modality_subtype)}<br><b>view/fov</b>:${esc(r.view_or_projection)} / ${esc(r.field_of_view)}<br><b>quality</b>:${esc(r.image_quality_band)} / ${esc(r.image_quality_score)};<b>size</b>:${esc(r.image_width_px)} x ${esc(r.image_height_px)}<br><b>diagnosis</b>:${esc(r.diagnosis_group_clean)}<br><b>路径</b>:<span class="path">${esc(r.file_path)}</span>${r.open_error ? '<br><b>读取错误</b>:'+esc(r.open_error) : ''}</div><div class="prompt"><b>短 prompt</b>:${esc(r.short_prompt)}</div><div class="prompt"><b>中 prompt</b>:${esc(r.medium_prompt)}</div><div class="review"><div class="row"><button class="ok" onclick="setStatus('keep')">1 保留</button><button class="warn" onclick="setStatus('watermark')">2 水印</button><button class="bad" onclick="setStatus('pii')">3 PII</button><button class="warn" onclick="setStatus('wrong_modality', false)">4 错模态</button><button class="warn" onclick="setStatus('low_quality')">5 低质</button><button class="bad" onclick="setStatus('drop')">6 丢弃</button><button onclick="setStatus('unreviewed', false)">清空</button></div><textarea placeholder="备注" oninput="updateNote(this.value)">${esc(e.note || '')}</textarea></div><div class="hint">快捷键:1 保留,2 水印,3 PII,4 错模态,5 低质,6 丢弃,←/→ 翻页,C 导出 CSV,J 导出 JSON。备注框内不会触发快捷键。</div></div></section>`;
346
+ }
347
+ document.addEventListener('keydown', ev => {
348
+ const tag=(ev.target && ev.target.tagName || '').toLowerCase();
349
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
350
+ if (ev.key === 'ArrowRight') go(1);
351
+ else if (ev.key === 'ArrowLeft') go(-1);
352
+ else if (ev.key === '1') setStatus('keep');
353
+ else if (ev.key === '2') setStatus('watermark');
354
+ else if (ev.key === '3') setStatus('pii');
355
+ else if (ev.key === '4') setStatus('wrong_modality', false);
356
+ else if (ev.key === '5') setStatus('low_quality');
357
+ else if (ev.key === '6') setStatus('drop');
358
+ else if (ev.key.toLowerCase() === 'c') exportCSV();
359
+ else if (ev.key.toLowerCase() === 'j') exportJSON();
360
+ });
361
+ render();
362
+ """
363
+ doc = f"""<!doctype html><html><head><meta charset="utf-8"><title>OCTFlow v6 风险样本审核</title><style>{css}</style></head>
364
+ <body><header><h1>OCTFlow v6 风险样本审核</h1><div class="bar"><span id="progress" class="progress"></span><button onclick="go(-1)">上一张</button><button class="primary" onclick="go(1)">下一张</button><label>跳转 <input id="jump" type="number" min="1" max="{len(records)}" onchange="gotoIndex(this.value)" style="width:80px"></label><button onclick="exportCSV()">导出 CSV</button><button onclick="exportJSON()">导出 JSON</button></div><div class="hint">风险导向抽样:poor quality、私有原始路径/水印高风险 cohort、已脱敏大 cohort 抽查、稀有或易混淆 subtype、大 cohort 兜底抽查。这里只用于人工 QC,不修改训练数据。</div></header><main id="root"></main><script type="application/json" id="rows-data">{rows_json}</script><script>{js}</script></body></html>"""
365
+ out.write_text(doc, encoding="utf-8")
366
+
367
+
368
+ def parse_args() -> argparse.Namespace:
369
+ parser = argparse.ArgumentParser(description=__doc__)
370
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
371
+ parser.add_argument("--captions", type=Path, default=DEFAULT_CAPTIONS)
372
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
373
+ parser.add_argument("--seed", type=int, default=20260709)
374
+ parser.add_argument("--thumb-size", type=int, default=512)
375
+ parser.add_argument("--poor-per-modality", type=int, default=20)
376
+ parser.add_argument("--high-risk-per-cohort", type=int, default=6)
377
+ parser.add_argument("--deid-sanity-per-cohort", type=int, default=4)
378
+ parser.add_argument("--rare-per-subtype", type=int, default=8)
379
+ parser.add_argument("--top-cohorts", type=int, default=20)
380
+ parser.add_argument("--top-per-cohort", type=int, default=2)
381
+ parser.add_argument("--max-rows", type=int, default=180)
382
+ return parser.parse_args()
383
+
384
+
385
+ def main() -> None:
386
+ args = parse_args()
387
+ args.out.mkdir(parents=True, exist_ok=True)
388
+ records, summary = build_review_rows(args)
389
+ write_csv(records, args.out / "risk_review_rows.csv")
390
+ (args.out / "risk_review_rows.json").write_text(
391
+ json.dumps(json_safe(records), ensure_ascii=False, indent=2, allow_nan=False),
392
+ encoding="utf-8",
393
+ )
394
+ (args.out / "summary.json").write_text(
395
+ json.dumps(summary, ensure_ascii=False, indent=2, allow_nan=False),
396
+ encoding="utf-8",
397
+ )
398
+ write_html(records, args.out / "OPEN_THIS_V6_QUALITY_RISK_REVIEW.html")
399
+ print(json.dumps({"out": str(args.out), **summary}, ensure_ascii=False), flush=True)
400
+
401
+
402
+ if __name__ == "__main__":
403
+ main()
data_processing/02_quality_control/clean_excel.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): clean_excel.py
4
+ 原本用途 (Original Purpose):
5
+ 临床多源诊断 Excel 表格清洗与跨表核验脚本。解决临床原始导出表格中存在的空行、非法特殊字符、格式不规范、合并单元格及双重合并症(Dual Comorbidity)问题,校验图片 ID 与表格记录的一致性。
6
+ 适用数据集 (Target Dataset):
7
+ archives/data0410/ 中的 fundus_hcw.zip 图像集伴随的多中心原始临床诊断 Excel 表。
8
+ 作者与归属 (Author/Provenance):
9
+ 胡成伟 (Huchengwei), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 原始临床科室导出的非规范 Excel 诊断表格及图像文件列表
12
+ 输出结果 (Output):
13
+ 结构化清洗后的诊断数据表(CSV/Excel),保证每张图像具有明确临床诊断映射
14
+ 依赖环境 (Dependencies):
15
+ pandas, openpyxl, re
16
+ ================================================================================
17
+ """
18
+
19
+ import os
20
+ import pandas as pd
21
+
22
+
23
+ def main():
24
+ # --- 1. 路径配置 ---
25
+ original_excel_path = "/data/team/huchengwei/fundus/fundus_csv/paired_fundus_image_dramdrvo.xlsx"
26
+ missing_log_path = "/data/team/huchengwei/fundus/fundus_csv/missing_images_dramdrvo.txt" # 上一步脚本自动生成的缺失名单
27
+ # 新的干净表格保存路径
28
+ new_excel_path = "/data/team/huchengwei/fundus/fundus_csv/dramdrvo_cleaned.xlsx"
29
+
30
+ # --- 2. 加载缺失黑名单 ---
31
+ if not os.path.exists(missing_log_path):
32
+ raise FileNotFoundError(f"找不到 {missing_log_path},请确认上一步脚本是否正确生成了该文件。")
33
+
34
+ with open(missing_log_path, "r", encoding="utf-8") as f:
35
+ # 去除换行符并存入哈希集合 (Set) 以获得 O(1) 的查询速度
36
+ missing_basenames = set(line.strip() for line in f if line.strip())
37
+
38
+ print(f"[*] 成功加载缺失名单,共计 {len(missing_basenames)} 个目标。")
39
+
40
+ # --- 3. 读取原始 DataFrame ---
41
+ print(f"[*] 正在读取原始 Excel 表格...")
42
+ df = pd.read_excel(original_excel_path)
43
+ original_len = len(df)
44
+
45
+ # --- 4. 核心清洗逻辑 ---
46
+ # 定义过滤条件:提取 image_name 的无后缀基础名,判断其是否在黑名单中
47
+ def is_valid_row(image_name):
48
+ basename = os.path.splitext(str(image_name))[0]
49
+ return basename not in missing_basenames
50
+
51
+ # 应用掩码 (Boolean Mask) 过滤
52
+ mask = df['image_name'].apply(is_valid_row)
53
+ df_cleaned = df[mask]
54
+
55
+ cleaned_len = len(df_cleaned)
56
+ removed_count = original_len - cleaned_len
57
+
58
+ # --- 5. 校验与保存 ---
59
+ print(f"[*] 清洗完成!")
60
+ print(f" -> 原始数据行数: {original_len}")
61
+ print(f" -> 清洗后数据行数: {cleaned_len} (正好对应你成功复制的 5505 张图)")
62
+ print(f" -> 实际排除行数: {removed_count}")
63
+
64
+ # 保存新的 Excel
65
+ df_cleaned.to_excel(new_excel_path, index=False)
66
+ print(f"[*] 新的干净表格已生成并保存至:\n {new_excel_path}")
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
data_processing/02_quality_control/filter_prompt_artifacts.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): filter_prompt_artifacts.py
4
+ 原本用途 (Original Purpose):
5
+ 多模态生成与微调 Prompt 文本去噪与规范化工具。剔除自由文本病历转提示词过程中的格式噪点、标点混乱、多重重复标签与非法字符。
6
+ 适用数据集 (Target Dataset):
7
+ 多中心图文配对中生成的文本提示词(Prompts)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 原始提取的未清洗 Prompts 文本文件或 Parquet 列
12
+ 输出结果 (Output):
13
+ 清洗后的纯净标准多模态提示词文件
14
+ 依赖环境 (Dependencies):
15
+ re, json, pandas, pyarrow
16
+ ================================================================================
17
+ """
18
+
19
+ """Filter prompt-adapter manifest/caption artifacts without touching images.
20
+
21
+ The script removes selected cohorts from a prompt-adapter directory and writes a
22
+ new manifest/caption pair plus an audit summary. It is intended for quality or
23
+ privacy exclusions after prompt construction.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ from pathlib import Path
31
+
32
+ import pandas as pd
33
+
34
+
35
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6")
36
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6_exclude_octbuckets_octa")
37
+
38
+
39
+ def _status_from_counts(subtype: str, counts: pd.Series) -> str:
40
+ count = int(counts.get(subtype, 0))
41
+ if count >= 2000:
42
+ return "formal"
43
+ if count >= 500:
44
+ return "supplemental"
45
+ return "tiny"
46
+
47
+
48
+ def _count_dict(frame: pd.DataFrame, column: str) -> dict[str, int]:
49
+ if column not in frame.columns:
50
+ return {}
51
+ return frame[column].fillna("unknown").astype(str).value_counts().astype(int).to_dict()
52
+
53
+
54
+ def _write_readme(out: Path, summary: dict) -> None:
55
+ excluded = ", ".join(summary["excluded_cohorts"])
56
+ text = f"""# Prompt Adapter Filtered Artifacts
57
+
58
+ Source: `{summary["input_dir"]}`
59
+
60
+ Output: `{summary["out_dir"]}`
61
+
62
+ Excluded cohorts: `{excluded}`
63
+
64
+ Reason: manual review found pervasive watermark/low-quality/ambiguous images in
65
+ the excluded cohort, so the whole cohort is removed from training artifacts.
66
+
67
+ Manifest rows:
68
+
69
+ - before: {summary["manifest_rows_before"]}
70
+ - excluded: {summary["manifest_rows_excluded"]}
71
+ - after: {summary["manifest_rows_after"]}
72
+
73
+ Caption rows:
74
+
75
+ - before: {summary["caption_rows_before"]}
76
+ - excluded: {summary["caption_rows_excluded"]}
77
+ - after: {summary["caption_rows_after"]}
78
+
79
+ Files:
80
+
81
+ - `adapter_manifest_mixed_v6.parquet`: filtered training manifest
82
+ - `captions_v2.parquet`: filtered prompts/captions
83
+ - `excluded_rows.parquet`: removed manifest rows
84
+ - `excluded_image_ids.txt`: removed image IDs, one per line
85
+ - `summary.json`: counts and distribution checks
86
+ """
87
+ (out / "README.md").write_text(text, encoding="utf-8")
88
+
89
+
90
+ def parse_args() -> argparse.Namespace:
91
+ parser = argparse.ArgumentParser(description=__doc__)
92
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
93
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
94
+ parser.add_argument("--manifest-name", default="adapter_manifest_mixed_v6.parquet")
95
+ parser.add_argument("--captions-name", default="captions_v2.parquet")
96
+ parser.add_argument("--exclude-cohort", action="append", default=["octbuckets_octa"])
97
+ parser.add_argument("--overwrite", action="store_true")
98
+ return parser.parse_args()
99
+
100
+
101
+ def main() -> None:
102
+ args = parse_args()
103
+ args.out.mkdir(parents=True, exist_ok=True)
104
+ manifest_out = args.out / args.manifest_name
105
+ captions_out = args.out / args.captions_name
106
+ if not args.overwrite:
107
+ for path in [manifest_out, captions_out]:
108
+ if path.exists():
109
+ raise FileExistsError(f"{path} exists; pass --overwrite")
110
+
111
+ manifest_in = args.input / args.manifest_name
112
+ captions_in = args.input / args.captions_name
113
+ manifest = pd.read_parquet(manifest_in)
114
+ captions = pd.read_parquet(captions_in)
115
+ exclude_cohorts = set(args.exclude_cohort)
116
+
117
+ if "cohort" not in manifest.columns:
118
+ raise KeyError("manifest must contain a 'cohort' column")
119
+ if "image_id" not in manifest.columns:
120
+ raise KeyError("manifest must contain an 'image_id' column")
121
+ if "image_id" not in captions.columns:
122
+ raise KeyError("captions must contain an 'image_id' column")
123
+
124
+ cohort_values = manifest["cohort"].fillna("").astype(str)
125
+ excluded_mask = cohort_values.isin(exclude_cohorts)
126
+ excluded = manifest.loc[excluded_mask].copy()
127
+ kept = manifest.loc[~excluded_mask].copy()
128
+
129
+ if "modality_subtype" in kept.columns and "subtype_sample_status" in kept.columns:
130
+ subtype_counts = kept["modality_subtype"].fillna("unknown").astype(str).value_counts()
131
+ kept["subtype_sample_status"] = [
132
+ _status_from_counts(subtype, subtype_counts)
133
+ for subtype in kept["modality_subtype"].fillna("unknown").astype(str)
134
+ ]
135
+
136
+ keep_ids = set(kept["image_id"].astype(str))
137
+ caption_image_ids = captions["image_id"].astype(str)
138
+ kept_captions = captions.loc[caption_image_ids.isin(keep_ids)].copy()
139
+ excluded_caption_rows = int(len(captions) - len(kept_captions))
140
+
141
+ kept.to_parquet(manifest_out, index=False, compression="zstd")
142
+ kept_captions.to_parquet(captions_out, index=False, compression="zstd")
143
+ excluded.to_parquet(args.out / "excluded_rows.parquet", index=False, compression="zstd")
144
+ (args.out / "excluded_image_ids.txt").write_text(
145
+ "\n".join(excluded["image_id"].astype(str).tolist()) + ("\n" if len(excluded) else ""),
146
+ encoding="utf-8",
147
+ )
148
+
149
+ summary = {
150
+ "input_dir": str(args.input),
151
+ "out_dir": str(args.out),
152
+ "excluded_cohorts": sorted(exclude_cohorts),
153
+ "manifest_rows_before": int(len(manifest)),
154
+ "manifest_rows_excluded": int(len(excluded)),
155
+ "manifest_rows_after": int(len(kept)),
156
+ "caption_rows_before": int(len(captions)),
157
+ "caption_rows_excluded": excluded_caption_rows,
158
+ "caption_rows_after": int(len(kept_captions)),
159
+ "excluded_by_modality": _count_dict(excluded, "modality"),
160
+ "excluded_by_modality_family": _count_dict(excluded, "modality_family"),
161
+ "excluded_by_modality_subtype": _count_dict(excluded, "modality_subtype"),
162
+ "after_by_modality": _count_dict(kept, "modality"),
163
+ "after_by_modality_family": _count_dict(kept, "modality_family"),
164
+ "after_by_modality_subtype": _count_dict(kept, "modality_subtype"),
165
+ "after_by_subtype_sample_status": _count_dict(kept, "subtype_sample_status"),
166
+ }
167
+ (args.out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
168
+ _write_readme(args.out, summary)
169
+ print(json.dumps(summary, ensure_ascii=False), flush=True)
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()
data_processing/02_quality_control/prompt_qc.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): prompt_qc.py
4
+ 原本用途 (Original Purpose):
5
+ 临床诊断提示词解剖结构与语义层级一致性校验脚本。核验各模态提示词是否符合“检查类型-解剖部位-眼别-病变特征”的标准层级语法。
6
+ 适用数据集 (Target Dataset):
7
+ 全库用于生成式基座与指令微调的多模态 Prompts。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 结构化提示词 Manifest
12
+ 输出结果 (Output):
13
+ 语法合规性检查日志与不合规提示词告警清单
14
+ 依赖环境 (Dependencies):
15
+ re, pandas, pyarrow
16
+ ================================================================================
17
+ """
18
+
19
+ """Build prompt QC samples for the de-identified new-data manifest."""
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import html
25
+ import io
26
+ import math
27
+ import re
28
+ import tarfile
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ import pandas as pd
33
+ from PIL import Image, ImageOps
34
+
35
+
36
+ DEFAULT_MANIFEST = Path(
37
+ "/data/team/lisicheng/new_data_manifest/"
38
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
39
+ )
40
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_qc")
41
+
42
+ MODALITY_TEXT = {
43
+ "fundus_color": "color fundus photograph",
44
+ "oct_bscan": "OCT B-scan",
45
+ "octa": "optical coherence tomography angiography image",
46
+ "ffa": "fluorescein fundus angiography image",
47
+ "bscan_us": "ocular B-scan ultrasound image",
48
+ "ubm": "ultrasound biomicroscopy image",
49
+ "uwf": "ultra-widefield fundus photograph",
50
+ }
51
+
52
+ BANNED_PROMPT_TERMS = {
53
+ "tongren",
54
+ "xiangya",
55
+ "yinhai",
56
+ "chengdu",
57
+ "eryuan",
58
+ "handan",
59
+ "data0410",
60
+ "hcw",
61
+ "fq_unlabeled",
62
+ "mixed_unlabeled",
63
+ "octbuckets",
64
+ "train",
65
+ "test",
66
+ "internal_test",
67
+ "external_test",
68
+ "unlabeled",
69
+ }
70
+
71
+ DIAG_MAP = {
72
+ "amd": "age-related macular degeneration",
73
+ "年龄相关性黄斑变性": "age-related macular degeneration",
74
+ "老年性黄斑变性": "age-related macular degeneration",
75
+ "dr": "diabetic retinopathy",
76
+ "糖尿病视网膜病变": "diabetic retinopathy",
77
+ "糖网": "diabetic retinopathy",
78
+ "normal": "normal",
79
+ "正常": "normal",
80
+ "rvo": "retinal vein occlusion",
81
+ "视网膜静脉阻塞": "retinal vein occlusion",
82
+ "csc": "central serous chorioretinopathy",
83
+ "中心性浆液性脉络膜视网膜病变": "central serous chorioretinopathy",
84
+ "中浆": "central serous chorioretinopathy",
85
+ "erm": "epiretinal membrane",
86
+ "黄斑前膜": "epiretinal membrane",
87
+ "mh": "macular hole",
88
+ "黄斑裂孔": "macular hole",
89
+ "rao": "retinal artery occlusion",
90
+ "视网膜动脉阻塞": "retinal artery occlusion",
91
+ "rd": "retinal detachment",
92
+ "视网膜脱离": "retinal detachment",
93
+ "vkh": "Vogt-Koyanagi-Harada disease",
94
+ "葡萄膜炎": "uveitis",
95
+ "青光眼": "glaucoma",
96
+ "白内障": "cataract",
97
+ }
98
+
99
+ FINDING_RULES = [
100
+ (re.compile(r"玻璃体混浊|中低回声光点|中低回声光斑"), "vitreous opacity"),
101
+ (re.compile(r"玻璃体积血"), "vitreous hemorrhage"),
102
+ (re.compile(r"玻璃体后脱离"), "posterior vitreous detachment"),
103
+ (re.compile(r"后巩膜葡萄肿"), "posterior staphyloma"),
104
+ (re.compile(r"视网膜脱离"), "retinal detachment"),
105
+ (re.compile(r"视网膜裂孔"), "retinal tear"),
106
+ (re.compile(r"眼内占位|占位性病变"), "intraocular mass"),
107
+ (re.compile(r"脉络膜黑色素瘤"), "choroidal melanoma"),
108
+ (re.compile(r"硅油眼"), "silicone oil eye"),
109
+ (re.compile(r"黄斑囊样水肿|黄斑水肿|囊样水肿"), "macular edema"),
110
+ (re.compile(r"黄斑前膜"), "epiretinal membrane"),
111
+ (re.compile(r"黄斑裂孔"), "macular hole"),
112
+ (re.compile(r"分支静脉阻塞"), "branch retinal vein occlusion"),
113
+ (re.compile(r"视网膜静脉阻塞|静脉阻塞"), "retinal vein occlusion"),
114
+ (re.compile(r"视网膜动脉阻塞|动脉阻塞"), "retinal artery occlusion"),
115
+ (re.compile(r"糖尿病视网膜病变|糖网"), "diabetic retinopathy"),
116
+ (re.compile(r"高血压视网膜病变"), "hypertensive retinopathy"),
117
+ (re.compile(r"新生血管|CNV", re.I), "neovascularization"),
118
+ (re.compile(r"荧光渗漏|渗漏"), "fluorescein leakage"),
119
+ (re.compile(r"无灌注"), "capillary nonperfusion"),
120
+ (re.compile(r"微动脉瘤"), "microaneurysms"),
121
+ (re.compile(r"硬性渗出|硬渗"), "hard exudates"),
122
+ (re.compile(r"棉絮斑"), "cotton-wool spots"),
123
+ (re.compile(r"出血"), "retinal hemorrhage"),
124
+ (re.compile(r"视盘.*高荧光|视盘.*渗漏"), "optic disc leakage"),
125
+ (re.compile(r"房角开放"), "open anterior chamber angle"),
126
+ (re.compile(r"房角偏窄|窄房角|房角狭窄"), "narrow anterior chamber angle"),
127
+ (re.compile(r"虹膜平坦"), "flat iris configuration"),
128
+ (re.compile(r"睫状体.*囊|囊样暗区|囊样无回声区"), "ciliary body cyst"),
129
+ (re.compile(r"晶体内回声增强"), "lens opacity"),
130
+ (re.compile(r"前房.*浅"), "shallow anterior chamber"),
131
+ ]
132
+
133
+ PII_PATTERNS = [
134
+ re.compile(r"(姓名|患者姓名|病人姓名|name)\s*[::]?\s*[\u4e00-\u9fffA-Za-z·]{1,8}", re.I),
135
+ re.compile(r"(ID号|\bID\b|编号|住院号|门诊号|检查号|patient\s*id)\s*[::]?\s*[A-Za-z0-9_-]+", re.I),
136
+ re.compile(r"(检查日期|出生日期|DOB)\s*[::]?\s*\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?", re.I),
137
+ re.compile(r"\b\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?\b"),
138
+ re.compile(r"\b\d{8,}\b"),
139
+ ]
140
+
141
+
142
+ def clean_text(text: Any) -> str:
143
+ if text is None:
144
+ return ""
145
+ if isinstance(text, float) and math.isnan(text):
146
+ return ""
147
+ out = str(text)
148
+ for pattern in PII_PATTERNS:
149
+ out = pattern.sub("", out)
150
+ out = re.sub(r"(医师签名|医生签名|签名|建议门诊|门诊时间).*", "", out, flags=re.I)
151
+ out = re.sub(r"(待删|删除)", "", out)
152
+ out = re.sub(r"\s+", " ", out)
153
+ out = re.sub(r"[,。;;,\s]+$", "", out)
154
+ return out.strip(" ,。;;,")
155
+
156
+
157
+ def build_prompts(row: dict[str, Any]) -> dict[str, str]:
158
+ modality = str(row.get("modality") or "")
159
+ base = base_prompt(row, modality)
160
+ descriptors = _clinical_descriptors(row)
161
+ demographics = _demographics(row)
162
+
163
+ short_parts = [base]
164
+ medium_parts = [base] + demographics + descriptors[:3]
165
+ dense_parts = [base] + demographics + descriptors[:8]
166
+
167
+ return {
168
+ "short": _join(short_parts),
169
+ "medium": _join(medium_parts),
170
+ "dense": _join(dense_parts),
171
+ }
172
+
173
+
174
+ def base_prompt(row: dict[str, Any], modality: str) -> str:
175
+ if str(row.get("cohort") or "") == "tongren_external_fundus":
176
+ return "anterior segment photograph"
177
+ return MODALITY_TEXT.get(modality, f"{modality.replace('_', ' ')} ophthalmic image")
178
+
179
+
180
+ def main() -> None:
181
+ args = parse_args()
182
+ args.out.mkdir(parents=True, exist_ok=True)
183
+ (args.out / "imgs").mkdir(exist_ok=True)
184
+
185
+ df = pd.read_parquet(args.manifest)
186
+ df = df[df.get("split", "train") == "train"].copy() if "split" in df.columns else df.copy()
187
+ for col in ["center", "modality"]:
188
+ if col not in df.columns:
189
+ raise KeyError(f"manifest missing {col!r}")
190
+
191
+ samples = sample_by_center_modality(df, args.per_group, args.seed)
192
+ records = []
193
+ caption_rows = []
194
+ for idx, row in enumerate(samples.to_dict("records")):
195
+ prompts = build_prompts(row)
196
+ for level, prompt in prompts.items():
197
+ caption_rows.append(
198
+ {"image_id": row["image_id"], "level": level, "prompt_text": prompt}
199
+ )
200
+ image_rel = render_thumb(row, args.out / "imgs", idx, args.thumb)
201
+ record = {
202
+ "idx": idx,
203
+ "image_rel": image_rel,
204
+ "prompts": prompts,
205
+ **{k: row.get(k) for k in [
206
+ "image_id",
207
+ "center",
208
+ "modality",
209
+ "cohort",
210
+ "diagnosis_raw",
211
+ "group_raw",
212
+ "diagnosis_group",
213
+ "caption",
214
+ "train_path",
215
+ "pii_masked",
216
+ "ocr_age",
217
+ "ocr_sex",
218
+ "ocr_eye",
219
+ ]},
220
+ }
221
+ records.append(record)
222
+
223
+ caps = pd.DataFrame(caption_rows)
224
+ caps.to_parquet(args.out / "prompt_qc_captions.parquet", index=False)
225
+ caps.to_csv(args.out / "prompt_qc_captions.csv", index=False)
226
+ write_html(records, args.out / "prompt_qc.html")
227
+ write_design(args.out / "prompt_design.md")
228
+ print(f"DONE -> {args.out / 'prompt_qc.html'} ({len(records)} samples)")
229
+
230
+
231
+ def sample_by_center_modality(df: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:
232
+ groups = []
233
+ for (_, _), group in df.groupby(["center", "modality"], dropna=False):
234
+ groups.append(group.sample(n=min(n, len(group)), random_state=seed))
235
+ out = pd.concat(groups, ignore_index=True)
236
+ return out.sort_values(["modality", "center", "cohort", "image_id"]).reset_index(drop=True)
237
+
238
+
239
+ def render_thumb(row: dict[str, Any], img_dir: Path, idx: int, size: int) -> str:
240
+ path = str(row.get("train_path") or row.get("file_path"))
241
+ name = f"{idx:04d}_{safe_name(row.get('modality'))}_{safe_name(row.get('center'))}.jpg"
242
+ out = img_dir / name
243
+ try:
244
+ if "::" in path:
245
+ im = open_wds_member(path).convert("RGB")
246
+ else:
247
+ im = Image.open(path).convert("RGB")
248
+ im.thumbnail((size, size), Image.Resampling.LANCZOS)
249
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
250
+ canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
251
+ im = canvas
252
+ im.save(out, quality=90)
253
+ except Exception:
254
+ im = Image.new("RGB", (size, size), (80, 20, 20))
255
+ im = ImageOps.expand(im, border=2, fill=(255, 0, 0))
256
+ im.save(out, quality=90)
257
+ return f"imgs/{name}"
258
+
259
+
260
+ def open_wds_member(path: str) -> Image.Image:
261
+ tar_path, member_name = path.split("::", 1)
262
+ with tarfile.open(tar_path, "r:*") as tf:
263
+ member = tf.getmember(member_name)
264
+ fp = tf.extractfile(member)
265
+ if fp is None:
266
+ raise FileNotFoundError(path)
267
+ data = fp.read()
268
+ return Image.open(io.BytesIO(data))
269
+
270
+
271
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
272
+ css = """
273
+ body{font-family:Arial,sans-serif;margin:20px;background:#f7f7f7;color:#222}
274
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(460px,1fr));gap:14px}
275
+ .card{background:white;border:1px solid #ddd;border-radius:6px;padding:12px}
276
+ img{width:180px;height:180px;object-fit:contain;background:#000;float:left;margin-right:12px}
277
+ .meta{font-size:12px;color:#555;line-height:1.35}
278
+ .prompt{font-size:13px;margin:6px 0}.level{font-weight:bold;color:#333}
279
+ .caption{clear:both;font-size:12px;color:#555;border-top:1px solid #eee;margin-top:10px;padding-top:8px}
280
+ h1{margin-bottom:4px}.note{color:#555;margin-bottom:18px}
281
+ """
282
+ parts = [
283
+ "<!doctype html><html><head><meta charset='utf-8'>",
284
+ f"<style>{css}</style></head><body>",
285
+ "<h1>New-data prompt QC</h1>",
286
+ "<div class='note'>Grouped by center × modality, sampled 5 rows per group. "
287
+ "Prompts intentionally exclude center/cohort names and raw identifiers.</div>",
288
+ "<div class='grid'>",
289
+ ]
290
+ for r in records:
291
+ parts.append("<div class='card'>")
292
+ parts.append(f"<img src='{html.escape(r['image_rel'])}'>")
293
+ parts.append("<div class='meta'>")
294
+ for k in ["image_id", "modality", "center", "cohort", "pii_masked", "ocr_age", "ocr_sex", "ocr_eye"]:
295
+ parts.append(f"<b>{k}</b>: {html.escape(str(r.get(k)))}<br>")
296
+ parts.append(f"<b>train_path</b>: {html.escape(str(r.get('train_path'))[:180])}</div>")
297
+ for level in ["short", "medium", "dense"]:
298
+ parts.append(
299
+ f"<div class='prompt'><span class='level'>{level}</span>: "
300
+ f"{html.escape(r['prompts'][level])}</div>"
301
+ )
302
+ parts.append("<div class='caption'>")
303
+ for k in ["diagnosis_raw", "group_raw", "diagnosis_group", "caption"]:
304
+ v = r.get(k)
305
+ if v is not None and not (isinstance(v, float) and math.isnan(v)):
306
+ parts.append(f"<b>{k}</b>: {html.escape(str(v)[:400])}<br>")
307
+ parts.append("</div></div>")
308
+ parts.append("</div></body></html>")
309
+ out.write_text("\n".join(parts), encoding="utf-8")
310
+
311
+
312
+ def write_design(out: Path) -> None:
313
+ text = """# Prompt design logic
314
+
315
+ The training prompt space follows the previous private-data SD3 logic: each image has
316
+ multiple candidate prompts (`short`, `medium`, `dense`), and training samples one
317
+ prompt level at random per step.
318
+
319
+ Prompt levels:
320
+ - `short`: modality phrase only, matching the old private-data minimal prompt style.
321
+ - `medium`: modality phrase plus age/sex/eye if available and up to three English labels.
322
+ - `dense`: modality phrase plus age/sex/eye if available and up to eight English labels.
323
+
324
+ Modality phrases:
325
+ - `fundus_color`: color fundus photograph
326
+ - `tongren_external_fundus`: anterior segment photograph, overriding the
327
+ `fundus_color` modality phrase because these images are external/anterior-eye photos.
328
+ - `uwf`: ultra-widefield fundus photograph
329
+ - `ffa`: fluorescein fundus angiography image
330
+ - `octa`: optical coherence tomography angiography image
331
+ - `bscan_us`: ocular B-scan ultrasound image
332
+ - `ubm`: ultrasound biomicroscopy image
333
+
334
+ Safety rules:
335
+ - Never include center, hospital, cohort, dataset name, file name, ID, exact date, DOB, or raw OCR text.
336
+ - Store only non-identifying OCR-derived attributes: age, sex, eye laterality.
337
+ - Rows without labels still receive a modality-only prompt.
338
+ - Long free-text reports are never copied into prompts; they are reduced to English finding labels.
339
+ """
340
+ out.write_text(text, encoding="utf-8")
341
+
342
+
343
+ def _clinical_descriptors(row: dict[str, Any]) -> list[str]:
344
+ desc: list[str] = []
345
+ for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
346
+ val = clean_text(row.get(key))
347
+ val = translate_diag(val)
348
+ candidates = [val] if _is_prompt_ready_label(val) else extract_finding_tags(val)
349
+ _extend_unique(desc, candidates)
350
+ cap = clean_text(row.get("caption"))
351
+ _extend_unique(desc, extract_finding_tags(cap))
352
+ return desc
353
+
354
+
355
+ def extract_finding_tags(text: str) -> list[str]:
356
+ if not text:
357
+ return []
358
+ tags = [label for pattern, label in FINDING_RULES if pattern.search(text)]
359
+ return _unique(tags)
360
+
361
+
362
+ def _extend_unique(out: list[str], values: list[str]) -> None:
363
+ seen = {v.lower() for v in out}
364
+ for value in values:
365
+ if _allowed_descriptor(value) and value.lower() not in seen:
366
+ out.append(value)
367
+ seen.add(value.lower())
368
+
369
+
370
+ def _unique(values: list[str]) -> list[str]:
371
+ out = []
372
+ seen = set()
373
+ for value in values:
374
+ key = value.lower()
375
+ if key not in seen:
376
+ out.append(value)
377
+ seen.add(key)
378
+ return out
379
+
380
+
381
+ def _is_prompt_ready_label(text: str) -> bool:
382
+ if not _allowed_descriptor(text):
383
+ return False
384
+ if re.search(r"[\u4e00-\u9fff]", text):
385
+ return False
386
+ return _is_concise_label(text)
387
+
388
+
389
+ def _allowed_descriptor(text: str) -> bool:
390
+ if not text:
391
+ return False
392
+ lowered = text.lower().strip()
393
+ if lowered in BANNED_PROMPT_TERMS:
394
+ return False
395
+ if "_" in text or re.match(r"^group\d+\b", lowered):
396
+ return False
397
+ return not any(term in lowered for term in BANNED_PROMPT_TERMS)
398
+
399
+
400
+ def _is_concise_label(text: str) -> bool:
401
+ if len(text) > 80:
402
+ return False
403
+ return not re.search(r"[。;;]|提示|所见|检查", text)
404
+
405
+
406
+ def _clip_text(text: str, max_chars: int) -> str:
407
+ if len(text) <= max_chars:
408
+ return text
409
+ return text[: max_chars - 3].rstrip(" ,。;;,") + "..."
410
+
411
+
412
+ def _demographics(row: dict[str, Any]) -> list[str]:
413
+ out: list[str] = []
414
+ age = row.get("ocr_age")
415
+ if age is not None and not (isinstance(age, float) and math.isnan(age)):
416
+ bucket = age_bucket(age)
417
+ if bucket:
418
+ out.append(bucket)
419
+ sex = str(row.get("ocr_sex") or "").upper()
420
+ if sex == "M":
421
+ out.append("male")
422
+ elif sex == "F":
423
+ out.append("female")
424
+ eye = str(row.get("ocr_eye") or "").upper()
425
+ if eye == "OD":
426
+ out.append("right eye")
427
+ elif eye == "OS":
428
+ out.append("left eye")
429
+ elif eye == "OU":
430
+ out.append("both eyes")
431
+ if len(out) >= 2 and out[1] in {"male", "female"}:
432
+ out = [f"{out[1]} patient {out[0]}"] + out[2:]
433
+ return out
434
+
435
+
436
+ def age_bucket(age: Any) -> str:
437
+ try:
438
+ value = int(age)
439
+ except (TypeError, ValueError):
440
+ return ""
441
+ if value < 0 or value > 120:
442
+ return ""
443
+ if value < 2:
444
+ return "infant"
445
+ if value < 13:
446
+ return "child"
447
+ if value < 20:
448
+ return "teenage patient"
449
+ decade = min((value // 10) * 10, 90)
450
+ return f"in their {decade}s"
451
+
452
+
453
+ def _join(parts: list[str]) -> str:
454
+ clean = [p for p in (clean_text(part) for part in parts) if p]
455
+ return ", ".join(clean)
456
+
457
+
458
+ def translate_diag(text: str) -> str:
459
+ if not text:
460
+ return ""
461
+ key = text.strip().lower()
462
+ return DIAG_MAP.get(key, text.strip())
463
+
464
+
465
+ def safe_name(value: Any) -> str:
466
+ return re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "na"))[:80]
467
+
468
+
469
+ def parse_args() -> argparse.Namespace:
470
+ parser = argparse.ArgumentParser()
471
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
472
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
473
+ parser.add_argument("--per-group", type=int, default=5)
474
+ parser.add_argument("--seed", type=int, default=20260701)
475
+ parser.add_argument("--thumb", type=int, default=320)
476
+ return parser.parse_args()
477
+
478
+
479
+ if __name__ == "__main__":
480
+ main()
data_processing/02_quality_control/resize_mode_qc.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): resize_mode_qc.py
4
+ 原本用途 (Original Purpose):
5
+ 图像分辨率与缩放变形模式验证脚本。监控不同设备(Optos, Topcon, Heidelberg)在下采样至训练分辨率时的纵横比失真情况,提供安全缩放模式建议。
6
+ 适用数据集 (Target Dataset):
7
+ 全库跨硬件厂商的多分辨率图像。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 图像文件集合及目标模型输入分辨率设定
12
+ 输出结果 (Output):
13
+ 纵横比失真直方图与适配缩放建议方案
14
+ 依赖环境 (Dependencies):
15
+ pillow, numpy, pandas
16
+ ================================================================================
17
+ """
18
+
19
+ """Build a visual QC sheet comparing center-crop vs aspect-preserving padding."""
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import io
25
+ import tarfile
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import pandas as pd
30
+ from PIL import Image, ImageDraw, ImageFont
31
+
32
+ import sys
33
+ import types
34
+
35
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
36
+ omegaconf_stub = types.ModuleType("omegaconf")
37
+ omegaconf_stub.DictConfig = object
38
+ sys.modules.setdefault("omegaconf", omegaconf_stub)
39
+ from utils.train_utils import center_crop_arr, resize_pad_arr
40
+
41
+
42
+ DEFAULT_MANIFEST = Path(
43
+ "/data/team/lisicheng/new_data_manifest/"
44
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
45
+ )
46
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/resize_mode_qc_20260702")
47
+
48
+
49
+ def main() -> None:
50
+ args = parse_args()
51
+ args.out.mkdir(parents=True, exist_ok=True)
52
+ df = pd.read_parquet(args.manifest, columns=["image_id", "cohort", "modality", "train_path", "file_path"])
53
+ samples = []
54
+ for (_, _), group in df.groupby(["modality", "cohort"], sort=True):
55
+ samples.append(group.sample(n=min(args.per_group, len(group)), random_state=args.seed))
56
+ sample = pd.concat(samples, ignore_index=True).sort_values(["modality", "cohort", "image_id"])
57
+
58
+ rows = []
59
+ records = []
60
+ for row in sample.to_dict("records"):
61
+ path = str(row.get("train_path") or row.get("file_path"))
62
+ try:
63
+ im = open_image(path).convert("RGB")
64
+ crop = center_crop_arr(im, args.size)
65
+ pad = resize_pad_arr(im, args.size)
66
+ rows.append((row, im, crop, pad))
67
+ records.append({**row, "width": im.width, "height": im.height})
68
+ except Exception as exc:
69
+ records.append({**row, "error": repr(exc)})
70
+ write_sheet(rows, args.out / "resize_mode_qc.jpg", args.size)
71
+ pd.DataFrame(records).to_csv(args.out / "resize_mode_qc.csv", index=False)
72
+ print(f"DONE -> {args.out / 'resize_mode_qc.jpg'} ({len(rows)} images)")
73
+
74
+
75
+ def open_image(path: str) -> Image.Image:
76
+ if "::" in path:
77
+ tar_path, member = path.split("::", 1)
78
+ with tarfile.open(tar_path) as tf:
79
+ fp = tf.extractfile(member)
80
+ if fp is None:
81
+ raise FileNotFoundError(path)
82
+ data = fp.read()
83
+ return Image.open(io.BytesIO(data))
84
+ return Image.open(path)
85
+
86
+
87
+ def write_sheet(rows: list[tuple[dict[str, Any], Image.Image, Image.Image, Image.Image]], out: Path, cell: int) -> None:
88
+ header = 52
89
+ cols = 3
90
+ sheet = Image.new("RGB", (cols * cell, len(rows) * (cell + header)), (20, 20, 20))
91
+ draw = ImageDraw.Draw(sheet)
92
+ font = ImageFont.load_default()
93
+ for r, (meta, original, crop, pad) in enumerate(rows):
94
+ y = r * (cell + header)
95
+ label = f"{meta.get('modality')} | {meta.get('cohort')} | {meta.get('image_id')}"
96
+ draw.text((6, y + 4), label[:140], fill=(235, 235, 235), font=font)
97
+ for c, (name, im) in enumerate([("original", original), ("center_crop", crop), ("resize_pad", pad)]):
98
+ x = c * cell
99
+ draw.text((x + 6, y + 22), name, fill=(210, 210, 210), font=font)
100
+ thumb = fit_thumb(im, cell)
101
+ sheet.paste(thumb, (x, y + header))
102
+ out.parent.mkdir(parents=True, exist_ok=True)
103
+ sheet.save(out, quality=92)
104
+
105
+
106
+ def fit_thumb(im: Image.Image, cell: int) -> Image.Image:
107
+ im = im.copy()
108
+ im.thumbnail((cell, cell), Image.Resampling.LANCZOS)
109
+ canvas = Image.new("RGB", (cell, cell), (0, 0, 0))
110
+ canvas.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2))
111
+ return canvas
112
+
113
+
114
+ def parse_args() -> argparse.Namespace:
115
+ parser = argparse.ArgumentParser()
116
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
117
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
118
+ parser.add_argument("--per-group", type=int, default=2)
119
+ parser.add_argument("--seed", type=int, default=20260702)
120
+ parser.add_argument("--size", type=int, default=320)
121
+ return parser.parse_args()
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
data_processing/02_quality_control/scan_eyepacs_edge_artifact.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ================================================================================
4
+ 脚本名称 (Script Name): scan_eyepacs_edge_artifact.py
5
+ 原本用途 (Original Purpose):
6
+ EyePACS 图像边缘冷冻灰边伪影(Frozen Gray-edge Artifact)专用扫描与滤除工具。利用四角亮度(corner luma)、饱和度(mean saturation)与非黑像素比例(nonblack fraction)精确定位历史数字化扫描底片中的灰阶边框瑕疵。
7
+ 适用数据集 (Target Dataset):
8
+ EyePACS(大规模糖尿病视网膜病变筛查数据集)。
9
+ 作者与归属 (Author/Provenance):
10
+ 李思成 / 团队, 浙江大学多模态眼科团队
11
+ 输入要求 (Input):
12
+ EyePACS 原始 tar.zst 分卷压缩包或图像目录
13
+ 输出结果 (Output):
14
+ 边缘灰边伪影定量度量指标 Parquet 表与瑕疵样本过滤清单
15
+ 依赖环境 (Dependencies):
16
+ pyarrow, numpy, pillow, tarfile
17
+ ================================================================================
18
+ """
19
+
20
+ """Scan one archive-owned EyePACS shard for the frozen gray-edge artifact rule."""
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ from datetime import datetime, timezone
26
+ import hashlib
27
+ from io import BytesIO
28
+ import json
29
+ import os
30
+ from pathlib import Path
31
+ import tarfile
32
+ import time
33
+ from typing import Any, Mapping
34
+ import uuid
35
+
36
+ import numpy as np
37
+ from PIL import Image
38
+ import pyarrow as pa
39
+ import pyarrow.compute as pc
40
+ import pyarrow.parquet as pq
41
+
42
+
43
+ METRIC_SCHEMA_VERSION = "eyepacs-edge-metrics-v1"
44
+ RULE_VERSION = "eyepacs-gray-edge-strict-v1"
45
+ MANIFEST_FIELDS = [
46
+ "image_id",
47
+ "cohort",
48
+ "file_path",
49
+ "modality",
50
+ "modality_subtype",
51
+ "severity",
52
+ "diagnosis_group",
53
+ "study_id",
54
+ "patient_hash",
55
+ ]
56
+ REQUIRED_MANIFEST_FIELDS = {"image_id", "cohort", "file_path"}
57
+
58
+ SELECTED_SCHEMA = pa.schema(
59
+ [
60
+ ("image_id", pa.string()),
61
+ ("cohort", pa.string()),
62
+ ("file_path", pa.string()),
63
+ ("archive_path", pa.string()),
64
+ ("archive_member", pa.string()),
65
+ ("modality", pa.string()),
66
+ ("modality_subtype", pa.string()),
67
+ ("severity", pa.string()),
68
+ ("diagnosis_group", pa.string()),
69
+ ("study_id", pa.string()),
70
+ ("patient_hash", pa.string()),
71
+ ]
72
+ )
73
+ RESULT_SCHEMA = pa.schema(
74
+ [
75
+ *SELECTED_SCHEMA,
76
+ ("nonblack_frac", pa.float64()),
77
+ ("corner_luma", pa.float64()),
78
+ ("mean_saturation", pa.float64()),
79
+ ("foreground_luma_std", pa.float64()),
80
+ ("mean_foreground_luma", pa.float64()),
81
+ ("strict_rule_hit", pa.bool_()),
82
+ ("washed_low_information_hit", pa.bool_()),
83
+ ("decode_ok", pa.bool_()),
84
+ ("decode_error", pa.string()),
85
+ ("rule_version", pa.string()),
86
+ ("metric_schema_version", pa.string()),
87
+ ("source_manifest_fingerprint", pa.string()),
88
+ ]
89
+ )
90
+
91
+
92
+ def _sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str:
93
+ digest = hashlib.sha256()
94
+ with path.open("rb") as handle:
95
+ while chunk := handle.read(chunk_size):
96
+ digest.update(chunk)
97
+ return digest.hexdigest()
98
+
99
+
100
+ def _fsync_directory(path: Path) -> None:
101
+ descriptor = os.open(path, os.O_RDONLY)
102
+ try:
103
+ os.fsync(descriptor)
104
+ finally:
105
+ os.close(descriptor)
106
+
107
+
108
+ def _write_json_atomic(path: Path, payload: Mapping[str, Any]) -> None:
109
+ path.parent.mkdir(parents=True, exist_ok=True)
110
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
111
+ try:
112
+ with temporary.open("x", encoding="utf-8") as handle:
113
+ json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True)
114
+ handle.write("\n")
115
+ handle.flush()
116
+ os.fsync(handle.fileno())
117
+ os.replace(temporary, path)
118
+ _fsync_directory(path.parent)
119
+ finally:
120
+ temporary.unlink(missing_ok=True)
121
+
122
+
123
+ def _write_parquet_atomic(table: pa.Table, path: Path) -> str:
124
+ path.parent.mkdir(parents=True, exist_ok=True)
125
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
126
+ try:
127
+ with temporary.open("xb") as handle:
128
+ pq.write_table(table.cast(RESULT_SCHEMA), handle, compression="zstd")
129
+ handle.flush()
130
+ os.fsync(handle.fileno())
131
+ checked = pq.read_table(temporary)
132
+ if checked.schema != RESULT_SCHEMA or checked.num_rows != table.num_rows:
133
+ raise RuntimeError(f"Parquet readback mismatch: {temporary}")
134
+ checksum = _sha256(temporary)
135
+ os.replace(temporary, path)
136
+ _fsync_directory(path.parent)
137
+ return checksum
138
+ finally:
139
+ temporary.unlink(missing_ok=True)
140
+
141
+
142
+ def _manifest_fingerprint_payload(path: Path, cohort: str) -> dict[str, Any]:
143
+ path = Path(path)
144
+ stat = path.stat()
145
+ parquet = pq.ParquetFile(path)
146
+ if "cohort" not in parquet.schema_arrow.names:
147
+ raise ValueError("manifest missing required fields: ['cohort']")
148
+ cohort_rows = 0
149
+ for batch in parquet.iter_batches(columns=["cohort"], batch_size=131_072):
150
+ values = pa.Table.from_batches([batch])["cohort"]
151
+ cohort_rows += int(pc.sum(pc.equal(values, pa.scalar(cohort))).as_py() or 0)
152
+ return {
153
+ "path": str(path.resolve()),
154
+ "size": stat.st_size,
155
+ "mtime_ns": stat.st_mtime_ns,
156
+ "row_count": parquet.metadata.num_rows,
157
+ "schema": str(parquet.schema_arrow),
158
+ "selected_cohort": cohort,
159
+ "selected_cohort_rows": cohort_rows,
160
+ "rule_version": RULE_VERSION,
161
+ "metric_schema_version": METRIC_SCHEMA_VERSION,
162
+ }
163
+
164
+
165
+ def manifest_fingerprint(path: Path, cohort: str) -> str:
166
+ payload = _manifest_fingerprint_payload(Path(path), cohort)
167
+ serialized = json.dumps(
168
+ payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
169
+ )
170
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
171
+
172
+
173
+ def parse_archive_uri(value: object) -> tuple[str, str]:
174
+ if value is None:
175
+ raise ValueError("malformed archive URI: null")
176
+ text = str(value)
177
+ if "::" not in text:
178
+ raise ValueError(f"malformed archive URI: {text!r}")
179
+ archive_path, archive_member = text.split("::", 1)
180
+ if (
181
+ not archive_path.strip()
182
+ or not archive_member.strip()
183
+ or "\x00" in archive_path
184
+ or "\x00" in archive_member
185
+ ):
186
+ raise ValueError(f"malformed archive URI: {text!r}")
187
+ return archive_path, archive_member
188
+
189
+
190
+ def _text(value: object) -> str | None:
191
+ return None if value is None else str(value)
192
+
193
+
194
+ def _read_filtered_cohort_table(manifest: Path, cohort: str) -> pa.Table:
195
+ parquet = pq.ParquetFile(manifest)
196
+ schema_names = set(parquet.schema_arrow.names)
197
+ missing = REQUIRED_MANIFEST_FIELDS - schema_names
198
+ if missing:
199
+ raise ValueError(f"manifest missing required fields: {sorted(missing)}")
200
+ columns = [name for name in MANIFEST_FIELDS if name in schema_names]
201
+ return pq.read_table(
202
+ manifest,
203
+ columns=columns,
204
+ filters=[("cohort", "=", cohort)],
205
+ )
206
+
207
+
208
+ def _load_cohort_rows(manifest: Path, cohort: str) -> list[dict[str, Any]]:
209
+ table = _read_filtered_cohort_table(manifest, cohort)
210
+ rows = table.to_pylist()
211
+
212
+ seen: set[str] = set()
213
+ normalized: list[dict[str, Any]] = []
214
+ for row in rows:
215
+ image_id = _text(row.get("image_id"))
216
+ if image_id is None or not image_id.strip():
217
+ raise ValueError("empty image_id in selected cohort")
218
+ if image_id in seen:
219
+ raise ValueError(f"duplicate image_id in selected cohort: {image_id}")
220
+ seen.add(image_id)
221
+ archive_path, archive_member = parse_archive_uri(row.get("file_path"))
222
+ normalized.append(
223
+ {
224
+ "image_id": image_id,
225
+ "cohort": cohort,
226
+ "file_path": str(row["file_path"]),
227
+ "archive_path": archive_path,
228
+ "archive_member": archive_member,
229
+ **{
230
+ name: _text(row.get(name))
231
+ for name in MANIFEST_FIELDS
232
+ if name not in REQUIRED_MANIFEST_FIELDS
233
+ },
234
+ }
235
+ )
236
+ return normalized
237
+
238
+
239
+ def select_shard_rows(
240
+ manifest: Path,
241
+ cohort: str,
242
+ shard_index: int,
243
+ num_shards: int,
244
+ shard_by: str,
245
+ ) -> pa.Table:
246
+ if shard_by != "archive":
247
+ raise ValueError("shard_by must be 'archive'")
248
+ if num_shards <= 0:
249
+ raise ValueError("num_shards must be positive")
250
+ if not 0 <= shard_index < num_shards:
251
+ raise ValueError("shard_index must satisfy 0 <= shard_index < num_shards")
252
+ rows = _load_cohort_rows(Path(manifest), cohort)
253
+ archive_owner = {
254
+ archive_path: index % num_shards
255
+ for index, archive_path in enumerate(
256
+ sorted({row["archive_path"] for row in rows})
257
+ )
258
+ }
259
+ selected = [
260
+ row for row in rows if archive_owner[row["archive_path"]] == shard_index
261
+ ]
262
+ selected.sort(
263
+ key=lambda row: (row["archive_path"], row["image_id"], row["archive_member"])
264
+ )
265
+ return pa.Table.from_pylist(selected, schema=SELECTED_SCHEMA)
266
+
267
+
268
+ def strict_rule_hit(metrics: Mapping[str, float]) -> bool:
269
+ return bool(
270
+ float(metrics["nonblack_frac"]) >= 0.995
271
+ and 0.48 <= float(metrics["corner_luma"]) <= 0.53
272
+ and float(metrics["mean_saturation"]) <= 0.15
273
+ and float(metrics["foreground_luma_std"]) <= 0.08
274
+ )
275
+
276
+
277
+ def compute_image_metrics(image: Image.Image) -> dict[str, float | bool]:
278
+ resized = image.convert("RGB").resize((256, 256), resample=Image.Resampling.BICUBIC)
279
+ rgb = np.asarray(resized, dtype=np.float64) / 255.0
280
+ luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
281
+ foreground = luma > 0.04
282
+ if not bool(foreground.any()):
283
+ raise ValueError("empty foreground after frozen luma threshold")
284
+ corners = np.concatenate(
285
+ (
286
+ luma[:16, :16].ravel(),
287
+ luma[:16, -16:].ravel(),
288
+ luma[-16:, :16].ravel(),
289
+ luma[-16:, -16:].ravel(),
290
+ )
291
+ )
292
+ channel_max = rgb.max(axis=2)
293
+ channel_min = rgb.min(axis=2)
294
+ saturation = (channel_max - channel_min) / (channel_max + 1e-6)
295
+ foreground_luma = luma[foreground]
296
+ mean_foreground_luma = float(foreground_luma.mean())
297
+ foreground_luma_std = float(foreground_luma.std())
298
+ metrics: dict[str, float | bool] = {
299
+ "nonblack_frac": float(foreground.mean()),
300
+ "corner_luma": float(corners.mean()),
301
+ "mean_saturation": float(saturation[foreground].mean()),
302
+ "foreground_luma_std": foreground_luma_std,
303
+ "mean_foreground_luma": mean_foreground_luma,
304
+ "washed_low_information_hit": bool(
305
+ mean_foreground_luma > 0.62 and foreground_luma_std < 0.13
306
+ ),
307
+ }
308
+ return metrics
309
+
310
+
311
+ class ArchiveImageReader:
312
+ """Read tar members without extraction while keeping only one archive open."""
313
+
314
+ def __init__(self) -> None:
315
+ self._archive_path: str | None = None
316
+ self._archive: tarfile.TarFile | None = None
317
+
318
+ def read(self, archive_path: str, archive_member: str) -> Image.Image:
319
+ if archive_path != self._archive_path:
320
+ self.close()
321
+ self._archive = tarfile.open(archive_path, "r:*")
322
+ self._archive_path = archive_path
323
+ if self._archive is None:
324
+ raise RuntimeError("archive reader is not open")
325
+ extracted = self._archive.extractfile(archive_member)
326
+ if extracted is None:
327
+ raise KeyError(f"archive member not found: {archive_member}")
328
+ payload = extracted.read()
329
+ with Image.open(BytesIO(payload)) as image:
330
+ image.load()
331
+ return image.convert("RGB")
332
+
333
+ def close(self) -> None:
334
+ if self._archive is not None:
335
+ self._archive.close()
336
+ self._archive = None
337
+ self._archive_path = None
338
+
339
+ def __enter__(self) -> ArchiveImageReader:
340
+ return self
341
+
342
+ def __exit__(self, *_: object) -> None:
343
+ self.close()
344
+
345
+
346
+ def _scan_row(
347
+ row: Mapping[str, Any],
348
+ reader: ArchiveImageReader,
349
+ fingerprint: str,
350
+ ) -> dict[str, Any]:
351
+ result = dict(row)
352
+ result.update(
353
+ {
354
+ "nonblack_frac": None,
355
+ "corner_luma": None,
356
+ "mean_saturation": None,
357
+ "foreground_luma_std": None,
358
+ "mean_foreground_luma": None,
359
+ "strict_rule_hit": False,
360
+ "washed_low_information_hit": False,
361
+ "decode_ok": False,
362
+ "decode_error": "",
363
+ "rule_version": RULE_VERSION,
364
+ "metric_schema_version": METRIC_SCHEMA_VERSION,
365
+ "source_manifest_fingerprint": fingerprint,
366
+ }
367
+ )
368
+ try:
369
+ image = reader.read(str(row["archive_path"]), str(row["archive_member"]))
370
+ metrics = compute_image_metrics(image)
371
+ result.update(metrics)
372
+ result["strict_rule_hit"] = strict_rule_hit(metrics)
373
+ result["decode_ok"] = True
374
+ except Exception as error:
375
+ result["decode_error"] = f"{type(error).__name__}: {error}"
376
+ return result
377
+
378
+
379
+ def _part_paths(
380
+ output_dir: Path,
381
+ shard_index: int,
382
+ num_shards: int,
383
+ ) -> tuple[Path, Path]:
384
+ stem = f"part-{shard_index:05d}-of-{num_shards:05d}"
385
+ return output_dir / f"{stem}.parquet", output_dir / f"{stem}.summary.json"
386
+
387
+
388
+ def scan_shard(
389
+ manifest: Path,
390
+ cohort: str,
391
+ shard_index: int,
392
+ num_shards: int,
393
+ shard_by: str,
394
+ output_dir: Path,
395
+ *,
396
+ overwrite: bool = False,
397
+ ) -> dict[str, Any]:
398
+ manifest = Path(manifest)
399
+ output_dir = Path(output_dir)
400
+ if shard_by != "archive":
401
+ raise ValueError("shard_by must be 'archive'")
402
+ fingerprint_payload = _manifest_fingerprint_payload(manifest, cohort)
403
+ fingerprint = hashlib.sha256(
404
+ json.dumps(
405
+ fingerprint_payload,
406
+ ensure_ascii=False,
407
+ sort_keys=True,
408
+ separators=(",", ":"),
409
+ ).encode("utf-8")
410
+ ).hexdigest()
411
+ output_path, summary_path = _part_paths(output_dir, shard_index, num_shards)
412
+ expected = {
413
+ "manifest_fingerprint": fingerprint,
414
+ "cohort": cohort,
415
+ "shard_index": shard_index,
416
+ "num_shards": num_shards,
417
+ "shard_by": shard_by,
418
+ "rule_version": RULE_VERSION,
419
+ "metric_schema_version": METRIC_SCHEMA_VERSION,
420
+ }
421
+ if summary_path.exists() and not overwrite:
422
+ try:
423
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
424
+ except (OSError, json.JSONDecodeError) as error:
425
+ raise RuntimeError(
426
+ "existing shard summary is unreadable; use --overwrite"
427
+ ) from error
428
+ if any(summary.get(key) != value for key, value in expected.items()):
429
+ raise RuntimeError("existing shard configuration drift; use --overwrite")
430
+ if (
431
+ summary.get("state") != "committed"
432
+ or not output_path.is_file()
433
+ or summary.get("output_sha256") != _sha256(output_path)
434
+ ):
435
+ raise RuntimeError("existing shard is not reusable; use --overwrite")
436
+ return {**summary, "reused": True}
437
+ if output_path.exists() and not overwrite:
438
+ raise FileExistsError(
439
+ f"output exists without reusable summary; use --overwrite: {output_path}"
440
+ )
441
+
442
+ started = time.perf_counter()
443
+ selected = select_shard_rows(
444
+ manifest,
445
+ cohort,
446
+ shard_index,
447
+ num_shards,
448
+ shard_by,
449
+ )
450
+ output_dir.mkdir(parents=True, exist_ok=True)
451
+ running = {
452
+ **expected,
453
+ "state": "running",
454
+ "manifest": str(manifest),
455
+ "manifest_fingerprint_payload": fingerprint_payload,
456
+ "input_rows": selected.num_rows,
457
+ "output_path": str(output_path),
458
+ "summary_path": str(summary_path),
459
+ "started_at_utc": datetime.now(timezone.utc).isoformat(),
460
+ }
461
+ _write_json_atomic(summary_path, running)
462
+ with ArchiveImageReader() as reader:
463
+ result_rows = [
464
+ _scan_row(row, reader, fingerprint) for row in selected.to_pylist()
465
+ ]
466
+ result = pa.Table.from_pylist(result_rows, schema=RESULT_SCHEMA)
467
+ output_sha256 = _write_parquet_atomic(result, output_path)
468
+ elapsed = time.perf_counter() - started
469
+ decoded_rows = sum(bool(row["decode_ok"]) for row in result_rows)
470
+ failures = len(result_rows) - decoded_rows
471
+ summary = {
472
+ **running,
473
+ "state": "committed",
474
+ "decoded_rows": decoded_rows,
475
+ "failures": failures,
476
+ "decode_failures": failures,
477
+ "strict_hits": sum(bool(row["strict_rule_hit"]) for row in result_rows),
478
+ "washed_hits": sum(
479
+ bool(row["washed_low_information_hit"]) for row in result_rows
480
+ ),
481
+ "elapsed_seconds": elapsed,
482
+ "throughput_images_per_second": (
483
+ len(result_rows) / elapsed if elapsed else 0.0
484
+ ),
485
+ "output_sha256": output_sha256,
486
+ "committed_at_utc": datetime.now(timezone.utc).isoformat(),
487
+ "reused": False,
488
+ }
489
+ _write_json_atomic(summary_path, summary)
490
+ return summary
491
+
492
+
493
+ def _parse_args() -> argparse.Namespace:
494
+ parser = argparse.ArgumentParser(description=__doc__)
495
+ parser.add_argument("--manifest", type=Path, required=True)
496
+ parser.add_argument("--cohort", required=True)
497
+ parser.add_argument("--shard-index", type=int, required=True)
498
+ parser.add_argument("--num-shards", type=int, required=True)
499
+ parser.add_argument("--shard-by", choices=("archive",), required=True)
500
+ parser.add_argument("--output-dir", type=Path, required=True)
501
+ parser.add_argument("--overwrite", action="store_true")
502
+ return parser.parse_args()
503
+
504
+
505
+ def main() -> None:
506
+ args = _parse_args()
507
+ summary = scan_shard(
508
+ args.manifest,
509
+ args.cohort,
510
+ args.shard_index,
511
+ args.num_shards,
512
+ args.shard_by,
513
+ args.output_dir,
514
+ overwrite=args.overwrite,
515
+ )
516
+ print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
517
+
518
+
519
+ if __name__ == "__main__":
520
+ main()
data_processing/03_report_parsing/attach_labels.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): attach_labels.py
4
+ 原本用途 (Original Purpose):
5
+ 非结构化临床文本诊断报告与图像索引记录的自动化匹配合并脚本。通过影像检查流水号或脱敏 ID 实现文本病历与多图像序列的准确关联。
6
+ 适用数据集 (Target Dataset):
7
+ 北京同仁医院、浙二眼科、成都市一等包含伴随文本报告的临床队列。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 自由文本病历表与图像 Manifest 表
12
+ 输出结果 (Output):
13
+ 图文完整绑定的多模态训练清单
14
+ 依赖环境 (Dependencies):
15
+ pandas, pyarrow, re
16
+ ================================================================================
17
+ """
18
+
19
+ """Attach clinical captions / dx to the manifest for FILE-labeled cohorts (json/jsonl/xlsx).
20
+ Folder-labeled cohorts (eryuan/eryuan_t17/tongren_95disease/dual/eyfrd6) are already labeled by
21
+ build_manifest (diagnosis_raw=parent dir). Join keys verified by the 2026-06-30 label-schema recon.
22
+
23
+ PII discipline: ONLY clinical findings/impression/dx text -> caption. Names/IDs/DOB/exam-dates/
24
+ doctor-signatures are NEVER read into caption (separate fields, dropped); embedded scheduling/
25
+ signature/boilerplate tails in free text are stripped by clean_caption().
26
+
27
+ All joins are STUDY/scan-level except data0410 (image-level 1:1) and hcw (image-level) -> a scan's
28
+ caption is fanned out to all its frames.
29
+
30
+ Output: adds `caption` + `diagnosis_group` columns -> <manifest>_labeled.parquet
31
+ Usage: /data/team/lisicheng/octdata_venv/bin/python attach_labels.py --manifest .../new_data_manifest.parquet [--only k1,k2]
32
+ """
33
+ import argparse, json, re, os
34
+ from collections import Counter
35
+ from pathlib import Path
36
+ import pandas as pd
37
+ import cohorts as C
38
+
39
+ NFS = "/nfs01/datasetsBackup"
40
+ LBL = {
41
+ "handan": f"{NFS}/ffa/handan_ffa/data.json",
42
+ "chengdu_ffa": f"{NFS}/ffa/chengdu_ffa/visionoph4.jsonl",
43
+ "yinhai_ffa": f"{NFS}/ffa/yinhai_ffa/output2.jsonl",
44
+ "yinhai_bscan": f"{NFS}/pretrainNewDS/BUltrasound/YinhaiBscan/YinhaiBscan.json", # RAW (has findings)
45
+ "xiangya_bscan":f"{NFS}/pretrainNewDS/BUltrasound/XiangyaBscan/xiangyaBUltrasound_cleanedv3.json",
46
+ "chengdu_ubm": f"{NFS}/pretrainNewDS/ubm/ChengduShiyiUBM/ChengdushiyiUBM_cleanedv3.json",
47
+ "yinhai_ubm": f"{NFS}/pretrainNewDS/ubm/YinhaiUBM/YinHaiUBM_cleanedv3.json",
48
+ }
49
+
50
+ _TAIL = re.compile(r'(建议[::]|门诊时间[::]|医[师生]签[名字]|签[名字][::]|医师[::]|检查者|报告医[师生]|TOPCON|Corporation).*$', re.S)
51
+ def clean_caption(t):
52
+ if t is None: return None
53
+ t = str(t).strip()
54
+ if not t or t == "18": return None # chengdu_ubm degenerate
55
+ t = _TAIL.split(t)[0] # drop scheduling/signature tail (PII)
56
+ t = re.sub(r'请结合临床[。.]?\s*$', '', t) # UBM boilerplate
57
+ t = t.replace("&&", " ").replace("\n", " ") # yinhai_ubm per-eye joiner / newlines
58
+ t = re.sub(r'\s+', ' ', t).strip(" >]")
59
+ return t or None
60
+
61
+ def _basename(p): return os.path.basename(str(p))
62
+ def _stem(p): return Path(str(p)).stem
63
+ def _load_array(path, tolerant=False):
64
+ s = open(path, encoding="utf-8", errors="replace").read()
65
+ if tolerant: s = re.sub(r',(\s*[}\]])', r'\1', s) # xiangya malformed trailing commas
66
+ return json.loads(s)
67
+
68
+ # each builder returns (lookup_dict, key_fn) ; lookup value = caption_str OR (caption, dx)
69
+ def b_handan():
70
+ recs = json.load(open(LBL["handan"]))["data"]
71
+ dup = {k for k, c in Counter(r.get("ID号", "").strip() for r in recs if r.get("ID号", "").strip()).items() if c > 1}
72
+ m = {}
73
+ for r in recs:
74
+ i = r.get("ID号", "").strip()
75
+ if not i or i in dup: continue # drop ambiguous/empty
76
+ m[i] = clean_caption(" ".join(x for x in [r.get("影像所见"), r.get("印象")] if x))
77
+ def key(p):
78
+ idp = _basename(p).rsplit("_", 1)[0]
79
+ return idp if idp in m else re.sub(r'\D+$', '', idp) # strip trailing non-digit (e.g. 1809243Coats)
80
+ return m, key
81
+
82
+ def b_chengdu_ffa():
83
+ m = {}
84
+ for r in _load_array(LBL["chengdu_ffa"]):
85
+ cap = clean_caption(r.get("description"))
86
+ dx = ";".join(dict.fromkeys(d for d in (r.get("diagnosis") or []) if d)) or None
87
+ for im in r.get("images", []):
88
+ b = re.split(r'[\\/]', im.get("image_path", ""))[-1] # basename, NO cleanup (mangled names are real)
89
+ if b and b not in m: m[b] = (cap, dx)
90
+ return m, _basename
91
+
92
+ def b_yinhai_ffa():
93
+ recs = [json.loads(l) for l in open(LBL["yinhai_ffa"]) if l.strip()]
94
+ m = {}
95
+ for r in recs:
96
+ f = r.get("file", ""); stem = f[:-4] if f.endswith(".csv") else f
97
+ if stem: m[stem] = clean_caption(r.get("second_column2"))
98
+ return m, lambda p: _basename(p).rsplit("-", 1)[0] # <stem>-<frame>.bmp
99
+
100
+ def b_by_images(path, tolerant=False, ubm_clean=False):
101
+ m = {}
102
+ for r in _load_array(path, tolerant=tolerant):
103
+ cap = r.get("description")
104
+ if ubm_clean and cap and not (cap[:1].isdigit() or ("一" <= cap[:1] <= "鿿")):
105
+ cap = cap[1:] # strip 1 leading junk char (chengdu_ubm)
106
+ cap = clean_caption(cap)
107
+ for im in r.get("images", []):
108
+ b = _basename(re.split(r'[\\/]', im.get("image_path", ""))[-1])
109
+ if b and b not in m: m[b] = cap
110
+ return m, _basename
111
+
112
+ def b_hcw():
113
+ rp = Path(C.EXTRACT_ROOT) / "hcw_fundus" / "fundus" / "fundus_csv"
114
+ frames = [pd.read_excel(rp / x) for x in ["dramdrvo_cleaned.xlsx", "glaucoma_cleaned.xlsx"] if (rp / x).exists()]
115
+ if not frames: print(" [hcw] xlsx missing -> run extract.sh (needs fundus_csv glob)"); return {}, _stem
116
+ lab = pd.concat(frames, ignore_index=True)
117
+ lab["stem"] = lab["image_name"].map(_stem)
118
+ m = {}
119
+ for stem, g in lab.groupby("stem"):
120
+ prim = g[g["is_primary"] == "是"]
121
+ names = ";".join(dict.fromkeys(g["diag_name"].dropna().astype(str)))
122
+ main = (prim.iloc[0] if len(prim) else g.iloc[0]).get("diag_name")
123
+ m[stem] = (clean_caption(names), str(main) if pd.notna(main) else None)
124
+ return m, _stem
125
+
126
+ def b_data0410():
127
+ fp = Path(C.EXTRACT_ROOT) / "data0410_master_fundus" / "data" / "reports_2020_2025_cleaned.xlsx"
128
+ if not fp.exists(): print(" [data0410] xlsx missing -> run extract.sh"); return {}, _basename
129
+ df = pd.read_excel(fp)
130
+ return {str(n): clean_caption(c) for n, c in zip(df["ImageName"], df["Notes_clean"])}, _basename
131
+
132
+ BUILDERS = {
133
+ "handan_fundus": b_handan, "handan_ffa": b_handan,
134
+ "chengdu_ffa": b_chengdu_ffa, "yinhai_ffa": b_yinhai_ffa,
135
+ "yinhai_bscan": lambda: b_by_images(LBL["yinhai_bscan"]),
136
+ "xiangya_bscan": lambda: b_by_images(LBL["xiangya_bscan"], tolerant=True),
137
+ "chengdu_shiyi_ubm": lambda: b_by_images(LBL["chengdu_ubm"], ubm_clean=True),
138
+ "yinhai_ubm": lambda: b_by_images(LBL["yinhai_ubm"], ubm_clean=True),
139
+ "hcw_fundus": b_hcw, "data0410_master_fundus": b_data0410,
140
+ }
141
+
142
+
143
+ def main():
144
+ ap = argparse.ArgumentParser()
145
+ ap.add_argument("--manifest", required=True)
146
+ ap.add_argument("--only", default=None)
147
+ args = ap.parse_args()
148
+ df = pd.read_parquet(args.manifest)
149
+ for col in ("caption", "diagnosis_group"):
150
+ if col not in df: df[col] = None
151
+ only = set(args.only.split(",")) if args.only else None
152
+
153
+ for cohort, builder in BUILDERS.items():
154
+ if only and cohort not in only: continue
155
+ sub = df[df["cohort"] == cohort]
156
+ if not len(sub): continue
157
+ try:
158
+ lookup, key_fn = builder()
159
+ except Exception as e:
160
+ print(f"[{cohort}] builder FAILED: {e}"); continue
161
+ # vectorized: build aligned Series on sub.index (preserves df index) -> O(N), not O(N^2)
162
+ caps, dxs = [], []
163
+ for k in sub["file_path"].map(key_fn):
164
+ v = lookup.get(k)
165
+ if v is None: caps.append(None); dxs.append(None); continue
166
+ c, d = v if isinstance(v, tuple) else (v, None)
167
+ caps.append(c); dxs.append(d)
168
+ caps = pd.Series(caps, index=sub.index); dxs = pd.Series(dxs, index=sub.index)
169
+ df.loc[sub.index, "caption"] = caps
170
+ df.loc[sub.index, "diagnosis_group"] = dxs
171
+ nhit = int((caps.notna() | dxs.notna()).sum())
172
+ print(f"[{cohort}] {len(sub)} imgs -> {nhit} captioned ({100*nhit/max(1,len(sub)):.0f}%)")
173
+
174
+ outp = args.manifest.replace(".parquet", "_labeled.parquet")
175
+ df.to_parquet(outp, index=False)
176
+ cov = df["caption"].notna().sum()
177
+ print(f"\n=== {len(df)} rows, {cov} with caption -> {outp} ===")
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
data_processing/03_report_parsing/batch_retrieve_reports.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): batch_retrieve_reports.py
4
+ 原本用途 (Original Purpose):
5
+ 基于 RoBERTa-SigLIP 多模态大模型的零样本(Zero-shot)图像-报告跨模态匹配检索脚本。针对图文未严格配对的 OCT B-scan 切片与病灶描述,通过视觉-语言联合特征空间计算余弦相似度并自动对齐。
6
+ 适用数据集 (Target Dataset):
7
+ OCT_LES_CW_V1(OCT 视网膜病灶图文配对子集)。
8
+ 作者与归属 (Author/Provenance):
9
+ 张焕 (Zhanghuan), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ OCT B-scan 图像批次与待匹配的临床病灶描述文本库
12
+ 输出结果 (Output):
13
+ 图文相似度矩阵与 Top-1 / Top-k 最佳匹配对映射文件
14
+ 依赖环境 (Dependencies):
15
+ torch, transformers, pillow, numpy, tqdm
16
+ ================================================================================
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ import math
22
+ import sys
23
+ from collections import Counter
24
+ from pathlib import Path
25
+
26
+ import pandas as pd
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import yaml
30
+ from PIL import Image
31
+ from torch.utils.data import DataLoader, Dataset
32
+ from torchvision import transforms
33
+ from tqdm import tqdm
34
+ from transformers import BertTokenizer
35
+
36
+
37
+ PROJECT_ROOT = Path(__file__).resolve().parents[3]
38
+ if str(PROJECT_ROOT) not in sys.path:
39
+ sys.path.insert(0, str(PROJECT_ROOT))
40
+
41
+ from siglip.model import OcularRoBERTaSigLIP, clean_state_dict
42
+
43
+
44
+ IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
45
+
46
+
47
+ def parse_args():
48
+ parser = argparse.ArgumentParser(
49
+ description=(
50
+ "Retrieve the most compatible report texts for a folder of OCT images. "
51
+ "This model ranks existing reports; it does not generate new text."
52
+ )
53
+ )
54
+ parser.add_argument("--image-dir", required=True, help="Directory containing OCT images")
55
+ parser.add_argument(
56
+ "--config",
57
+ default=str(PROJECT_ROOT / "siglip" / "train_config.yaml"),
58
+ help="Phase 2 training config",
59
+ )
60
+ parser.add_argument("--checkpoint", default=None, help="Phase 2 checkpoint")
61
+ parser.add_argument(
62
+ "--ijepa-path",
63
+ default=None,
64
+ help="Optional Phase 1 initialization; normally omit for a complete Phase 2 checkpoint",
65
+ )
66
+ parser.add_argument("--report-bank", default=None, help="XLSX/CSV containing candidate report texts")
67
+ parser.add_argument("--text-column", default=None)
68
+ parser.add_argument("--image-column", default=None)
69
+ parser.add_argument("--text-model-name", default=None)
70
+ parser.add_argument("--hf-cache-dir", default=None)
71
+ parser.add_argument("--local-files-only", action="store_true", default=None)
72
+ parser.add_argument("--allow-download", action="store_true")
73
+ parser.add_argument("--output-dir", default="phase2_retrieval_results")
74
+ parser.add_argument("--top-k", type=int, default=5)
75
+ parser.add_argument("--image-batch-size", type=int, default=64)
76
+ parser.add_argument("--text-batch-size", type=int, default=256)
77
+ parser.add_argument("--retrieval-chunk-size", type=int, default=16384)
78
+ parser.add_argument("--num-workers", type=int, default=8)
79
+ parser.add_argument("--precision", choices=["bf16", "fp16", "fp32"], default="bf16")
80
+ parser.add_argument("--device", default=None)
81
+ parser.add_argument("--num-images", type=int, default=0, help="0 uses every image")
82
+ parser.add_argument("--seed", type=int, default=42)
83
+ parser.add_argument("--non-recursive", action="store_true")
84
+ parser.add_argument("--write-text-files", action="store_true")
85
+ parser.add_argument("--rebuild-text-cache", action="store_true")
86
+ return parser.parse_args()
87
+
88
+
89
+ def load_config(path):
90
+ with open(path, "r", encoding="utf-8") as f:
91
+ return yaml.safe_load(f)
92
+
93
+
94
+ def resolve_args(args, config):
95
+ data_cfg = config.get("data", {})
96
+ model_cfg = config.get("model", {})
97
+ checkpoint_cfg = config.get("checkpoint", {})
98
+
99
+ output_root = Path(checkpoint_cfg.get("output_dir", PROJECT_ROOT / "BioCliFM"))
100
+ run_name = checkpoint_cfg.get("run_name", "phase2")
101
+ default_checkpoint = output_root / "checkpoints" / run_name / "siglip_best.pth"
102
+
103
+ args.checkpoint = args.checkpoint or str(default_checkpoint)
104
+ args.report_bank = args.report_bank or data_cfg.get("excel_path")
105
+ args.text_column = args.text_column or data_cfg.get("text_col", "Notes_clean")
106
+ args.image_column = args.image_column or data_cfg.get("image_col", "ImageName")
107
+ args.text_model_name = args.text_model_name or model_cfg.get(
108
+ "text_model_name", "hfl/chinese-roberta-wwm-ext-large"
109
+ )
110
+ args.hf_cache_dir = args.hf_cache_dir or model_cfg.get("hf_cache_dir")
111
+ if args.allow_download:
112
+ args.local_files_only = False
113
+ elif args.local_files_only is None:
114
+ args.local_files_only = model_cfg.get("local_files_only", False)
115
+ args.embed_dim = model_cfg.get("embed_dim", 512)
116
+ args.max_length = data_cfg.get("max_length", 256)
117
+ args.input_size = data_cfg.get("input_size", 224)
118
+
119
+ required_paths = {
120
+ "image directory": args.image_dir,
121
+ "Phase 2 checkpoint": args.checkpoint,
122
+ "report bank": args.report_bank,
123
+ }
124
+ for label, value in required_paths.items():
125
+ if not value or not Path(value).expanduser().exists():
126
+ raise FileNotFoundError(f"{label} does not exist: {value}")
127
+
128
+ if args.ijepa_path and not Path(args.ijepa_path).expanduser().exists():
129
+ raise FileNotFoundError(f"Phase 1 checkpoint does not exist: {args.ijepa_path}")
130
+ if args.top_k <= 0:
131
+ raise ValueError("--top-k must be greater than zero")
132
+ return args
133
+
134
+
135
+ def read_table(path, columns=None, nrows=None):
136
+ path = Path(path)
137
+ if path.suffix.lower() == ".csv":
138
+ return pd.read_csv(path, usecols=columns, nrows=nrows)
139
+ return pd.read_excel(path, usecols=columns, nrows=nrows)
140
+
141
+
142
+ def load_report_bank(path, text_column, image_column):
143
+ header = read_table(path, columns=None, nrows=0).columns
144
+ if text_column not in header:
145
+ raise KeyError(f"Text column '{text_column}' not found. Available columns: {list(header)}")
146
+
147
+ columns = [text_column]
148
+ has_image_column = image_column in header
149
+ if has_image_column:
150
+ columns.append(image_column)
151
+ df = read_table(path, columns=columns)
152
+
153
+ texts = []
154
+ text_to_index = {}
155
+ ground_truth = {}
156
+ skipped = 0
157
+
158
+ for _, row in df.iterrows():
159
+ raw_text = row.get(text_column)
160
+ if pd.isna(raw_text):
161
+ skipped += 1
162
+ continue
163
+ text = str(raw_text).strip()
164
+ if not text:
165
+ skipped += 1
166
+ continue
167
+ if text not in text_to_index:
168
+ text_to_index[text] = len(texts)
169
+ texts.append(text)
170
+
171
+ if has_image_column:
172
+ raw_image = row.get(image_column)
173
+ if not pd.isna(raw_image):
174
+ image_key = Path(str(raw_image).strip()).name
175
+ if image_key:
176
+ ground_truth.setdefault(image_key, set()).add(text)
177
+
178
+ if not texts:
179
+ raise RuntimeError(f"No valid reports found in {path}")
180
+ print(f"[Info] Report bank: rows={len(df)}, unique_reports={len(texts)}, skipped={skipped}")
181
+ if has_image_column:
182
+ print(f"[Info] Ground-truth image names available: {len(ground_truth)}")
183
+ return texts, ground_truth
184
+
185
+
186
+ def discover_images(image_dir, recursive, num_images, seed):
187
+ image_dir = Path(image_dir).expanduser().resolve()
188
+ iterator = image_dir.rglob("*") if recursive else image_dir.glob("*")
189
+ paths = sorted(path for path in iterator if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS)
190
+ if not paths:
191
+ raise RuntimeError(f"No supported images found under {image_dir}")
192
+ if num_images > 0 and len(paths) > num_images:
193
+ generator = torch.Generator().manual_seed(seed)
194
+ indices = torch.randperm(len(paths), generator=generator)[:num_images].tolist()
195
+ paths = [paths[index] for index in sorted(indices)]
196
+ print(f"[Info] OCT images selected: {len(paths)}")
197
+ return image_dir, paths
198
+
199
+
200
+ class OCTImageDataset(Dataset):
201
+ def __init__(self, image_root, image_paths, transform):
202
+ self.image_root = image_root
203
+ self.image_paths = image_paths
204
+ self.transform = transform
205
+
206
+ def __len__(self):
207
+ return len(self.image_paths)
208
+
209
+ def __getitem__(self, index):
210
+ path = self.image_paths[index]
211
+ try:
212
+ with Image.open(path) as image:
213
+ tensor = self.transform(image.convert("RGB"))
214
+ except Exception as exc:
215
+ raise RuntimeError(f"Failed to read image: {path}") from exc
216
+ return tensor, str(path.relative_to(self.image_root)), path.name
217
+
218
+
219
+ def autocast_context(device, precision):
220
+ enabled = device.type == "cuda" and precision != "fp32"
221
+ dtype = torch.bfloat16 if precision == "bf16" else torch.float16
222
+ return torch.amp.autocast(device_type=device.type, dtype=dtype, enabled=enabled)
223
+
224
+
225
+ def checkpoint_signature(path):
226
+ path = Path(path).expanduser().resolve()
227
+ stat = path.stat()
228
+ return {"path": str(path), "size": stat.st_size, "mtime_ns": stat.st_mtime_ns}
229
+
230
+
231
+ def load_phase2_model(args, device):
232
+ checkpoint = torch.load(args.checkpoint, map_location="cpu")
233
+ state_dict = clean_state_dict(checkpoint.get("model_state_dict", checkpoint))
234
+ projection_weight = state_dict.get("visual_projection.weight")
235
+ embed_dim = projection_weight.shape[0] if projection_weight is not None else args.embed_dim
236
+
237
+ model = OcularRoBERTaSigLIP(
238
+ ijepa_ckpt_path=args.ijepa_path,
239
+ ijepa_encoder_source="target",
240
+ text_model_name=args.text_model_name,
241
+ embed_dim=embed_dim,
242
+ hf_cache_dir=args.hf_cache_dir,
243
+ local_files_only=args.local_files_only,
244
+ )
245
+ incompatible = model.load_state_dict(state_dict, strict=True)
246
+ if incompatible.missing_keys or incompatible.unexpected_keys:
247
+ raise RuntimeError(
248
+ f"Checkpoint mismatch: missing={incompatible.missing_keys}, "
249
+ f"unexpected={incompatible.unexpected_keys}"
250
+ )
251
+ model.to(device).eval()
252
+ epoch = checkpoint.get("epoch", "unknown")
253
+ loss = checkpoint.get("loss", "unknown")
254
+ print(f"[Info] Loaded Phase 2 checkpoint: epoch={epoch}, loss={loss}, embed_dim={embed_dim}")
255
+ if args.ijepa_path is None:
256
+ print("[Info] Phase 1 is already incorporated in the complete Phase 2 vision tower.")
257
+ return model
258
+
259
+
260
+ def encode_text_bank(model, tokenizer, texts, args, device, output_dir):
261
+ cache_path = output_dir / "text_bank_embeddings.pt"
262
+ expected_meta = {
263
+ "checkpoint": checkpoint_signature(args.checkpoint),
264
+ "report_bank": str(Path(args.report_bank).expanduser().resolve()),
265
+ "text_column": args.text_column,
266
+ "text_model_name": args.text_model_name,
267
+ "max_length": args.max_length,
268
+ "num_texts": len(texts),
269
+ }
270
+ if cache_path.exists() and not args.rebuild_text_cache:
271
+ cache = torch.load(cache_path, map_location="cpu")
272
+ if cache.get("metadata") == expected_meta and cache.get("texts") == texts:
273
+ print(f"[Info] Reusing text embedding cache: {cache_path}")
274
+ return cache["embeddings"].float()
275
+ print("[Info] Text embedding cache is stale; rebuilding it.")
276
+
277
+ chunks = []
278
+ for start in tqdm(range(0, len(texts), args.text_batch_size), desc="Encoding report bank"):
279
+ batch_texts = texts[start:start + args.text_batch_size]
280
+ inputs = tokenizer(
281
+ batch_texts,
282
+ padding=True,
283
+ truncation=True,
284
+ max_length=args.max_length,
285
+ return_tensors="pt",
286
+ ).to(device)
287
+ with torch.inference_mode(), autocast_context(device, args.precision):
288
+ embeddings = F.normalize(
289
+ model.encode_text(inputs["input_ids"], inputs["attention_mask"]), dim=-1
290
+ )
291
+ chunks.append(embeddings.float().cpu())
292
+
293
+ embeddings = torch.cat(chunks, dim=0)
294
+ torch.save({"metadata": expected_meta, "texts": texts, "embeddings": embeddings}, cache_path)
295
+ print(f"[Info] Saved text embedding cache: {cache_path}")
296
+ return embeddings
297
+
298
+
299
+ def chunked_topk(image_embeddings, text_embeddings, top_k, chunk_size, device):
300
+ batch_size = image_embeddings.shape[0]
301
+ best_scores = torch.full((batch_size, top_k), -math.inf, device=device)
302
+ best_indices = torch.full((batch_size, top_k), -1, dtype=torch.long, device=device)
303
+
304
+ for start in range(0, text_embeddings.shape[0], chunk_size):
305
+ text_chunk = text_embeddings[start:start + chunk_size].to(device, non_blocking=True)
306
+ scores = image_embeddings @ text_chunk.t()
307
+ local_k = min(top_k, scores.shape[1])
308
+ chunk_scores, chunk_indices = scores.topk(local_k, dim=1)
309
+ chunk_indices += start
310
+
311
+ combined_scores = torch.cat([best_scores, chunk_scores], dim=1)
312
+ combined_indices = torch.cat([best_indices, chunk_indices], dim=1)
313
+ best_scores, positions = combined_scores.topk(top_k, dim=1)
314
+ best_indices = combined_indices.gather(1, positions)
315
+
316
+ return best_scores.float().cpu(), best_indices.cpu()
317
+
318
+
319
+ def retrieve_reports(model, image_loader, text_embeddings, texts, ground_truth, args, device):
320
+ results = []
321
+ scale = model.criterion.t_prime.detach().exp().clamp(max=model.criterion.max_temperature).float().cpu()
322
+ bias = model.criterion.b.detach().float().cpu()
323
+ top_k = min(args.top_k, len(texts))
324
+
325
+ for images, relative_paths, basenames in tqdm(image_loader, desc="Retrieving reports"):
326
+ images = images.to(device, non_blocking=True)
327
+ with torch.inference_mode(), autocast_context(device, args.precision):
328
+ image_embeddings = F.normalize(model.encode_image(images), dim=-1)
329
+ cosine_scores, indices = chunked_topk(
330
+ image_embeddings.float(), text_embeddings, top_k, args.retrieval_chunk_size, device
331
+ )
332
+
333
+ for row_index, (relative_path, basename) in enumerate(zip(relative_paths, basenames)):
334
+ candidates = []
335
+ for rank in range(top_k):
336
+ text_index = indices[row_index, rank].item()
337
+ cosine = cosine_scores[row_index, rank].item()
338
+ logit = cosine * scale.item() + bias.item()
339
+ candidates.append({
340
+ "rank": rank + 1,
341
+ "report": texts[text_index],
342
+ "cosine_similarity": cosine,
343
+ "siglip_logit": logit,
344
+ "sigmoid_score": torch.sigmoid(torch.tensor(logit)).item(),
345
+ })
346
+
347
+ expected = ground_truth.get(basename, set())
348
+ expected_rank = next(
349
+ (candidate["rank"] for candidate in candidates if candidate["report"] in expected),
350
+ None,
351
+ )
352
+ results.append({
353
+ "image_path": relative_path,
354
+ "image_name": basename,
355
+ "retrieved_report": candidates[0]["report"],
356
+ "top1_cosine": candidates[0]["cosine_similarity"],
357
+ "top1_siglip_logit": candidates[0]["siglip_logit"],
358
+ "top1_sigmoid_score": candidates[0]["sigmoid_score"],
359
+ "top1_top2_margin": (
360
+ candidates[0]["cosine_similarity"] - candidates[1]["cosine_similarity"]
361
+ if len(candidates) > 1 else None
362
+ ),
363
+ "ground_truth_reports": sorted(expected),
364
+ "ground_truth_rank_at_k": expected_rank,
365
+ "candidates": candidates,
366
+ })
367
+ return results
368
+
369
+
370
+ def save_results(results, output_dir, top_k, write_text_files):
371
+ jsonl_path = output_dir / "retrieval_results.jsonl"
372
+ with open(jsonl_path, "w", encoding="utf-8") as f:
373
+ for result in results:
374
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
375
+
376
+ rows = []
377
+ for result in results:
378
+ row = {
379
+ "image_path": result["image_path"],
380
+ "image_name": result["image_name"],
381
+ "retrieved_report": result["retrieved_report"],
382
+ "top1_cosine": result["top1_cosine"],
383
+ "top1_siglip_logit": result["top1_siglip_logit"],
384
+ "top1_sigmoid_score": result["top1_sigmoid_score"],
385
+ "top1_top2_margin": result["top1_top2_margin"],
386
+ "ground_truth_report": " || ".join(result["ground_truth_reports"]),
387
+ "ground_truth_rank_at_k": result["ground_truth_rank_at_k"],
388
+ }
389
+ for candidate in result["candidates"][:top_k]:
390
+ rank = candidate["rank"]
391
+ row[f"report_{rank}"] = candidate["report"]
392
+ row[f"cosine_{rank}"] = candidate["cosine_similarity"]
393
+ row[f"sigmoid_score_{rank}"] = candidate["sigmoid_score"]
394
+ rows.append(row)
395
+
396
+ csv_path = output_dir / "retrieval_results.csv"
397
+ pd.DataFrame(rows).to_csv(csv_path, index=False, encoding="utf-8-sig")
398
+
399
+ if write_text_files:
400
+ reports_dir = output_dir / "reports"
401
+ reports_dir.mkdir(parents=True, exist_ok=True)
402
+ for index, result in enumerate(results, start=1):
403
+ safe_stem = Path(result["image_name"]).stem.replace("/", "_").replace("\\", "_")
404
+ report_path = reports_dir / f"{index:04d}_{safe_stem}.txt"
405
+ report_path.write_text(result["retrieved_report"] + "\n", encoding="utf-8")
406
+
407
+ return csv_path, jsonl_path
408
+
409
+
410
+ def print_summary(results, top_k):
411
+ top1_scores = torch.tensor([item["top1_cosine"] for item in results])
412
+ margins = [item["top1_top2_margin"] for item in results if item["top1_top2_margin"] is not None]
413
+ evaluated = [item for item in results if item["ground_truth_reports"]]
414
+ report_counts = Counter(item["retrieved_report"] for item in results)
415
+ most_common_report, most_common_count = report_counts.most_common(1)[0]
416
+
417
+ print("\n=== Phase 1 + Phase 2 OCT Report Retrieval Summary ===")
418
+ print(f"Images: {len(results)}")
419
+ print(
420
+ "Top-1 cosine mean/min/max: "
421
+ f"{top1_scores.mean().item():.4f} / {top1_scores.min().item():.4f} / {top1_scores.max().item():.4f}"
422
+ )
423
+ if margins:
424
+ print(f"Top-1/Top-2 cosine margin mean: {sum(margins) / len(margins):.4f}")
425
+ print(f"Unique Top-1 reports: {len(report_counts)}/{len(results)}")
426
+ print(
427
+ "Most frequent Top-1 report share: "
428
+ f"{most_common_count}/{len(results)} ({most_common_count / len(results):.2%})"
429
+ )
430
+ print(f"Most frequent Top-1 report: {most_common_report}")
431
+ if evaluated:
432
+ recall1 = sum(item["ground_truth_rank_at_k"] == 1 for item in evaluated) / len(evaluated)
433
+ recallk = sum(item["ground_truth_rank_at_k"] is not None for item in evaluated) / len(evaluated)
434
+ reciprocal_ranks = [
435
+ 1.0 / item["ground_truth_rank_at_k"] if item["ground_truth_rank_at_k"] else 0.0
436
+ for item in evaluated
437
+ ]
438
+ print(f"Ground-truth matched images: {len(evaluated)}/{len(results)}")
439
+ print(f"Recall@1: {recall1:.4f}")
440
+ print(f"Recall@{top_k}: {recallk:.4f}")
441
+ print(f"MRR@{top_k}: {sum(reciprocal_ranks) / len(reciprocal_ranks):.4f}")
442
+ else:
443
+ print("Ground-truth metrics: unavailable (image names were not found in the report table).")
444
+
445
+
446
+ def main():
447
+ args = parse_args()
448
+ args = resolve_args(args, load_config(args.config))
449
+ device = torch.device(args.device or ("cuda:0" if torch.cuda.is_available() else "cpu"))
450
+ output_dir = Path(args.output_dir).expanduser().resolve()
451
+ output_dir.mkdir(parents=True, exist_ok=True)
452
+
453
+ print("[Info] Mode: report retrieval/ranking, not free-text generation")
454
+ print(f"[Info] Device={device}, precision={args.precision}, local_files_only={args.local_files_only}")
455
+ texts, ground_truth = load_report_bank(args.report_bank, args.text_column, args.image_column)
456
+ image_root, image_paths = discover_images(
457
+ args.image_dir, not args.non_recursive, args.num_images, args.seed
458
+ )
459
+
460
+ model = load_phase2_model(args, device)
461
+ tokenizer = BertTokenizer.from_pretrained(
462
+ args.text_model_name,
463
+ cache_dir=args.hf_cache_dir,
464
+ local_files_only=args.local_files_only,
465
+ )
466
+ text_embeddings = encode_text_bank(model, tokenizer, texts, args, device, output_dir)
467
+
468
+ transform = transforms.Compose([
469
+ transforms.Resize((args.input_size, args.input_size)),
470
+ transforms.ToTensor(),
471
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
472
+ ])
473
+ image_loader = DataLoader(
474
+ OCTImageDataset(image_root, image_paths, transform),
475
+ batch_size=args.image_batch_size,
476
+ shuffle=False,
477
+ num_workers=args.num_workers,
478
+ pin_memory=device.type == "cuda",
479
+ )
480
+ results = retrieve_reports(model, image_loader, text_embeddings, texts, ground_truth, args, device)
481
+ csv_path, jsonl_path = save_results(results, output_dir, args.top_k, args.write_text_files)
482
+ print_summary(results, min(args.top_k, len(texts)))
483
+ print(f"[Info] CSV: {csv_path}")
484
+ print(f"[Info] JSONL: {jsonl_path}")
485
+
486
+
487
+ if __name__ == "__main__":
488
+ main()
data_processing/03_report_parsing/cohorts.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): cohorts.py
4
+ 原本用途 (Original Purpose):
5
+ 多中心合作医院与数据集主注册表(Master Cohort Registry)。集中定义各合作中心代码、模态类型、设备厂商型号标准命名规范及本地路径派发规则。
6
+ 适用数据集 (Target Dataset):
7
+ 全库各中心数据集统一元数据字典。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 无(作为元数据配置文件使用)
12
+ 输出结果 (Output):
13
+ 标准化 Cohort 配置映射字典
14
+ 依赖环境 (Dependencies):
15
+ dataclasses, typing, pathlib
16
+ ================================================================================
17
+ """
18
+
19
+ """Verified cohort registry for the h100 cross-center new-data consolidation (2026-06-30).
20
+
21
+ Single source of truth, encoding the 11-agent read-only recon (see memory reference_h100_newdata).
22
+ HARD RULES baked in: originals on /nfs01 are READ-ONLY and NEVER modified/deleted. Archives
23
+ extract ONLY to EXTRACT_ROOT (work dir on /data). Already-extracted dirs are read in place.
24
+ Dedup/skip is done at MANIFEST level (drop rows), never by touching files.
25
+
26
+ Each cohort dict:
27
+ key unique cohort id (also the manifest `cohort` namespace)
28
+ modality fundus_color | octa | ffa | bscan_us | ubm | uwf
29
+ center hospital/source (for multi-center splits)
30
+ src path to the extracted dir OR the archive
31
+ comp none | zip | targz | rar5 | 7z (archive type if not extracted)
32
+ extracted True -> read `src` in place (0 disk); False -> extract to EXTRACT_ROOT/key
33
+ extract_glob optional member filter for selective extraction (e.g. images only)
34
+ exts image extensions to enumerate
35
+ label_kind folder | json | jsonl | xlsx | none
36
+ label_path label file (abs), or None (folder labels come from dir names)
37
+ pii none | low | t1 (t1 = must strip identifiers before any export; see register)
38
+ dedup_group cohorts sharing a group are cross-checked for duplicates
39
+ role train | external_test (external_test = held out, never trained)
40
+ note
41
+ """
42
+ import os
43
+
44
+ EXTRACT_ROOT = "/data/team/lisicheng/new_data_extracted" # all extraction lands here (/data, 2.9T free); /nfs01 is read-only
45
+ WORK = "/data/team/lisicheng"
46
+ NFS_BACKUP = "/nfs01/datasetsBackup"
47
+ NFS_FQ = "/nfs01/FQ_Datasets/data"
48
+ DATASETS = "/data/datasets"
49
+ UNRAR = "/data/team/lisicheng/miniconda3/envs/ocr/bin/unrar" # not on PATH; full path
50
+
51
+ IMG_EXTS = (".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp")
52
+
53
+
54
+ def read_path(c):
55
+ """Where images are actually read from."""
56
+ return c["src"] if c.get("extracted") else os.path.join(EXTRACT_ROOT, c["key"])
57
+
58
+
59
+ # ----------------------------------------------------------------------------- COHORTS
60
+ COHORTS = [
61
+ # ===================== FUNDUS (color fundus photography) =====================
62
+ dict(key="fundus90wer", modality="fundus_color", center="mixed_unlabeled",
63
+ src=f"{DATASETS}/fundus90wER", comp="none", extracted=True, exts=(".png", ".jpg"),
64
+ label_kind="none", label_path=None, pii="t1", dedup_group="fundus_pool", role="train",
65
+ note="899,266 (verified). Chinese names in filenames -> t1 (filename PII only, not in pixels). md5 in cleaning_report usable as dedup key."),
66
+ dict(key="fq_rawfundus", modality="fundus_color", center="fq_unlabeled",
67
+ src=f"{NFS_FQ}/rawFundus", comp="none", extracted=True, exts=(".png",),
68
+ label_kind="none", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
69
+ note="208,138 (verified). <id>-<n>.png. SKIP rawFundus_predicted (same imgs, quality-resorted)."),
70
+ dict(key="fq_testfundus", modality="fundus_color", center="fq_unlabeled",
71
+ src=f"{NFS_FQ}/testFundus", comp="none", extracted=True, exts=(".png",),
72
+ label_kind="none", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
73
+ note="52,034 (verified). SKIP testFundus_predicted."),
74
+ dict(key="fq_validfundus", modality="fundus_color", center="fq_unlabeled",
75
+ src=f"{NFS_FQ}/validFundus", comp="none", extracted=True, exts=(".png",),
76
+ label_kind="folder", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
77
+ note="4,000 (verified). quality=gradable (whole-dir tag)."),
78
+ dict(key="eryuan_t17_fundus", modality="fundus_color", center="eryuan",
79
+ src=f"{NFS_FQ}/eryuanFundusT17RDCls", comp="none", extracted=True, exts=(".tif",),
80
+ label_kind="folder", label_path=None, pii="low", dedup_group="eryuan_pool", role="train",
81
+ note="31,621 (verified). 17 disease classes; has train/val/test -> reserve its test split as INTERNAL test. class = immediate parent dir."),
82
+ dict(key="tongren_fundus", modality="fundus_color", center="tongren",
83
+ src=f"{WORK}/Dataser/shards_tongren", comp="none", extracted=True, exts=(".png",),
84
+ label_kind="json", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
85
+ note="~628,392 WebDataset shards (de-id product, sex/age in per-image json). USE THIS, skip 同仁/fundus.zip. WebDataset -> needs wds reader (see build_manifest stub)."),
86
+ dict(key="tongren_external_fundus", modality="fundus_color", center="tongren",
87
+ src=f"{NFS_BACKUP}/同仁/external.zip", comp="zip", extracted=False, exts=(".png",),
88
+ label_kind="none", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
89
+ note="209,091 (verified). 99.5% SAME PATIENTS as tongren_fundus but 0 same-file -> OK as extra TRAIN, NEVER as eval (leakage)."),
90
+ dict(key="tongren_95disease_fundus", modality="fundus_color", center="tongren",
91
+ src=f"{NFS_BACKUP}/tr/tr1695L2/tongren16G95DFundus", comp="none", extracted=True, exts=(".png",),
92
+ label_kind="folder", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
93
+ note="264,412 (verified). 16 groups / ~95 disease subclasses (folder). GOLDMINE for downstream. dedup vs tongren_pool by 编号. SKIP the tr .7z (extracted copy already here). class=parent, group=grandparent."),
94
+ dict(key="eryuan_fundus", modality="fundus_color", center="eryuan",
95
+ src=f"{NFS_BACKUP}/data0410/eryuan.zip", comp="zip", extracted=False, exts=(".tif", ".png"),
96
+ label_kind="folder", label_path=None, pii="low", dedup_group="eryuan_pool", role="train",
97
+ note="19,599 (verified): 4 classes AMD/DR/Normal/RVO (NOT 17 as md said). SKIP eryuan_split (subset). dedup vs data0410_master."),
98
+ dict(key="dual_comorbidity_fundus", modality="fundus_color", center="data0410",
99
+ src=f"{NFS_BACKUP}/data0410/Dual_comornidity.tar.gz", comp="targz", extracted=False, exts=(".png",),
100
+ label_kind="folder", label_path=None, pii="low", dedup_group="data0410_pool", role="train",
101
+ note="~12k unique (24,120 entries = 6-class scheme + 4-class scheme of SAME pool). Keep ONE scheme in manifest. hypertension comorbidity classes."),
102
+ dict(key="hcw_fundus", modality="fundus_color", center="hcw",
103
+ src=f"{NFS_BACKUP}/data0410/fundus_hcw.zip", comp="zip", extracted=False, exts=(".tif", ".png"),
104
+ extract_glob="fundus/fundus_img/*", label_kind="xlsx", label_path=None, pii="low",
105
+ dedup_group="data0410_pool", role="train",
106
+ note="~15,503 imgs ONLY (extract_glob excludes 150G .pth + code!). dx-pairing xlsx keyed by image_name."),
107
+ dict(key="data0410_master_fundus", modality="fundus_color", center="data0410",
108
+ src=f"{NFS_BACKUP}/data0410/data.tar.gz", comp="targz", extracted=False, exts=(".png", ".jpg"),
109
+ label_kind="xlsx", label_path=None, pii="t1", dedup_group="data0410_pool", role="train",
110
+ note="104,505 (md-UNVERIFIED). master 二院 pool. reports_2020_2025_cleaned.xlsx has 姓名/PatientID/DOB (STRIP). ⚠ xlsx->image join key UNRESOLVED (datetime filenames vs patient key) -> label as none until join confirmed. dedup vs eryuan/hcw."),
111
+ dict(key="eyfrd6_fundus", modality="fundus_color", center="eryuan",
112
+ src=f"{DATASETS}/eyFRDCls", comp="none", extracted=True, exts=(".tif",),
113
+ label_kind="folder", label_path=None, pii="low", dedup_group="fundus_pool", role="train",
114
+ note="~645. 6 classes CSC/ERM/MH/RAO/RD/VKH (has train/val/test). tiny."),
115
+ dict(key="handan_fundus", modality="fundus_color", center="handan",
116
+ src=f"{NFS_BACKUP}/ffa/handan_ffa/only_image", comp="none", extracted=True, exts=(".png",),
117
+ label_kind="json", label_path=f"{NFS_BACKUP}/ffa/handan_ffa/data.json", pii="t1",
118
+ dedup_group="handan", role="external_test",
119
+ note="6,432 fundus = filenames ending _1/_2 ONLY (must filter by suffix at enumerate). HELD OUT (邯郸 external). data.json 印象 dx; strip 姓名/年龄/检查日期/ID号."),
120
+
121
+ # ===================== OCTA =====================
122
+ dict(key="octbuckets_octa", modality="octa", center="octbuckets",
123
+ src=f"{WORK}/Dataser/shards_oct", comp="none", extracted=True, exts=(".png",),
124
+ label_kind="json", label_path=None, pii="none", dedup_group="octa", role="train",
125
+ note="~34,519 WebDataset (de-id product; eye/scan_mode/frame). USE THIS, skip octBuckets.zip (raw, has name-in-filename). Is OCTA (Angio/en-face), NOT plain OCT."),
126
+
127
+ # ===================== FFA (fluorescein angiography) -- NEW modality =====================
128
+ dict(key="handan_ffa", modality="ffa", center="handan",
129
+ src=f"{NFS_BACKUP}/ffa/handan_ffa/only_image", comp="none", extracted=True, exts=(".png",),
130
+ label_kind="json", label_path=f"{NFS_BACKUP}/ffa/handan_ffa/data.json", pii="t1",
131
+ dedup_group="handan", role="external_test",
132
+ note="23,212 FFA = filenames _3 and higher suffix (filter by suffix). HELD OUT (邯郸 external). 3,226 study impressions; strip PII."),
133
+ dict(key="chengdu_ffa", modality="ffa", center="chengdu",
134
+ src=f"{NFS_BACKUP}/ffa/chengdu_ffa/jpg", comp="none", extracted=True, exts=(".png",),
135
+ label_kind="jsonl", label_path=f"{NFS_BACKUP}/ffa/chengdu_ffa/visionoph4.jsonl", pii="low",
136
+ dedup_group="chengdu_ffa", role="external_test",
137
+ note="4,938 PNG (dir misnamed 'jpg', holds .png). HELD OUT (成都 FFA external). visionoph4.jsonl is a JSON ARRAY: scan_id/structured dx codes; normalize windows backslash paths."),
138
+ dict(key="yinhai_ffa", modality="ffa", center="yinhai",
139
+ src=f"{NFS_BACKUP}/ffa/yinhai_ffa/jpg", comp="none", extracted=True, exts=(".bmp",),
140
+ label_kind="jsonl", label_path=f"{NFS_BACKUP}/ffa/yinhai_ffa/output2.jsonl", pii="t1",
141
+ dedup_group="yinhai_ffa", role="train",
142
+ note="1,058 BMP (dir misnamed 'jpg', holds .bmp). output2.jsonl 拟诊报告; strip 姓名+P-ID+签名."),
143
+ dict(key="eryuan_ffa", modality="ffa", center="eryuan",
144
+ src=f"{NFS_BACKUP}/ffa/Final_eryuan_FFA/FFA", comp="none", extracted=True, exts=(".tif",),
145
+ label_kind="none", label_path=None, pii="low", dedup_group="eryuan_ffa", role="train",
146
+ note="18,543 tif (verified). SKIP the redundant 72.5G Final_eryuan_FFA.zip. no labels."),
147
+
148
+ # ===================== B-scan ocular ultrasound -- NEW modality =====================
149
+ dict(key="yinhai_bscan", modality="bscan_us", center="yinhai",
150
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/YinhaiBscan", comp="none", extracted=True, exts=(".png",),
151
+ label_kind="json", label_path=None, pii="low", dedup_group="yinhai_bscan", role="train",
152
+ note="71,289 (verified). images in image/ subdir. Use RAW json (超声所见 findings); cleanedv3 nulls findings. no name/dob."),
153
+ dict(key="xiangya_bscan", modality="bscan_us", center="xiangya",
154
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/XiangyaBscan", comp="none", extracted=True, exts=(".bmp",),
155
+ label_kind="json", label_path=None, pii="t1", dedup_group="xiangya_bscan", role="train",
156
+ note="33,740 (verified) bmp in image/. cleanedv3.json 4,939 records: findings + name/dob/examdate (STRIP)."),
157
+ dict(key="chengdu_bscan", modality="bscan_us", center="chengdu",
158
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/chengdu_Bscan", comp="none", extracted=True, exts=(".jpg",),
159
+ label_kind="none", label_path=None, pii="none", dedup_group="chengdu_bscan", role="train",
160
+ note="8,726 (verified) jpg flat. no labels."),
161
+
162
+ # ===================== UBM (ultrasound biomicroscopy) -- NEW modality =====================
163
+ dict(key="chengdu_shiyi_ubm", modality="ubm", center="chengdu",
164
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/ChengduShiyiUBM", comp="none", extracted=True, exts=(".png",),
165
+ label_kind="json", label_path=None, pii="low", dedup_group="chengdu_ubm", role="train",
166
+ note="236,028 (verified) png in image/. Use cleanedv3 json (clinical report; raw json has corrupted blobs/false-PII)."),
167
+ dict(key="yinhai_ubm", modality="ubm", center="yinhai",
168
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/YinhaiUBM", comp="none", extracted=True, exts=(".png",),
169
+ label_kind="json", label_path=None, pii="low", dedup_group="yinhai_ubm", role="train",
170
+ note="83,750 (verified). cleanedv3 clinical text."),
171
+ dict(key="eryuan_ubm", modality="ubm", center="eryuan",
172
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/Final_eryuan_ubm", comp="none", extracted=True, exts=(".tif",),
173
+ label_kind="none", label_path=None, pii="low", dedup_group="eryuan_ubm", role="train",
174
+ note="134,350 (verified) tif. truly no labels. SKIP the 2 redundant UBM .rar packs. ms-timestamp in filename (quasi-id)."),
175
+
176
+ # ===================== UWF (ultra-widefield) -- NEW modality, single center =====================
177
+ dict(key="yinhai_uwf", modality="uwf", center="yinhai",
178
+ src=f"{NFS_BACKUP}/pretrainNewDS/uwf/yinhai_uwf", comp="rar5", extracted=False, exts=(".jpg",),
179
+ label_kind="none", label_path=None, pii="low", dedup_group="yinhai_uwf", role="train",
180
+ note="11,113 (md-UNVERIFIED). 3 RAR5 multipart sets (Secondary_1/_2/_3). extract first volume of each set with unrar. SINGLE CENTER -> no external val possible (paper limitation)."),
181
+ ]
182
+
183
+ # Archives explicitly NOT ingested (dups / products-superseded / code). Documented for transparency; never deleted.
184
+ SKIP = {
185
+ "rawFundus_predicted": "dup of fq_rawfundus (quality-resorted)",
186
+ "testFundus_predicted": "dup of fq_testfundus",
187
+ "eryuan_split.tar.gz": "subset of eryuan_fundus",
188
+ "handan_ffa2": "strict subset of handan (0 unique files)",
189
+ "Final_eryuan_FFA.zip": "redundant archive of eryuan_ffa extracted dir",
190
+ "2-UBM-SW3200L-去噪声处理.rar / 3-UBM-SW3200L2-dataset.rar": "redundant with eryuan_ubm",
191
+ "同仁/fundus.zip": "superseded by tongren_fundus shards (de-id)",
192
+ "octBuckets.zip": "superseded by octbuckets_octa shards (de-id)",
193
+ "tr/*.7z": "extracted copy tr1695L2 already present",
194
+ "BioCliFM.tar.gz": "code, not data",
195
+ "fundus_hcw .pth/code": "150G checkpoints+code; only images extracted via extract_glob",
196
+ }
197
+
198
+ INCLUDE = COHORTS
199
+ def by_role(role): return [c for c in COHORTS if c["role"] == role]
200
+ def to_extract(): return [c for c in COHORTS if not c.get("extracted")]
201
+ def modalities(): return sorted({c["modality"] for c in COHORTS})
data_processing/03_report_parsing/materialize_newdata_prompts.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): materialize_newdata_prompts.py
4
+ 原本用途 (Original Purpose):
5
+ 41 列标准模式多中心多模态主索引清单(Master Manifest)物化生成工具。将分散在各医院子目录的图像路径、设备参数、质控标签和临床提示词汇聚为统一的 Parquet 索引。
6
+ 适用数据集 (Target Dataset):
7
+ 多中心新增入库的多模态数据集(包括 FFA, UBM, UWF, OCT 等)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 各中心独立整理的分散元数据及图像目录
12
+ 输出结果 (Output):
13
+ 全局标准化 41 列主索引表(adapter_manifest_reviewed.parquet)
14
+ 依赖环境 (Dependencies):
15
+ pyarrow, pandas, numpy, json
16
+ ================================================================================
17
+ """
18
+
19
+ """Materialize new-data prompt artifacts in the old OCTFlow caption format.
20
+
21
+ Outputs:
22
+ - adapter_manifest_v1.parquet: 41-column OCTFlow-style structured manifest.
23
+ - captions_v2.parquet: caption_id, image_id, level, prompt_text, language, generator, grounded_in.
24
+ - sidecar_v1.parquet: raw non-prompt details needed to audit how fields were derived.
25
+ - README.md: artifact and prompt design summary.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import math
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ import pandas as pd
37
+ import pyarrow as pa
38
+ import pyarrow.parquet as pq
39
+
40
+ from prompt_qc import build_prompts, clean_text, extract_finding_tags, translate_diag
41
+
42
+
43
+ DEFAULT_MANIFEST = Path(
44
+ "/data/team/lisicheng/new_data_manifest/"
45
+ "new_data_manifest_dedup_split_labeled_with_wds_deid_leftfundus.parquet"
46
+ )
47
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_v1")
48
+
49
+ V2_MODALITY_OVERRIDES = {
50
+ "data0410_master_fundus": "oct_bscan",
51
+ "octbuckets_octa": "oct_bscan",
52
+ }
53
+
54
+ V2_EXCLUDE_COHORTS = {
55
+ "fq_validfundus",
56
+ "dual_comorbidity_fundus",
57
+ }
58
+
59
+ ADAPTER_COLUMNS = [
60
+ "cohort",
61
+ "study_id",
62
+ "patient_hash",
63
+ "visit_date",
64
+ "eye",
65
+ "device_vendor",
66
+ "device_model",
67
+ "device_serial_hash",
68
+ "device_software_version",
69
+ "hospital_domain",
70
+ "ethnicity",
71
+ "image_quality_score",
72
+ "image_quality_band",
73
+ "diagnosis_group",
74
+ "lesion_tags",
75
+ "lesion_location",
76
+ "layer_involvement",
77
+ "severity",
78
+ "diagnosis_source",
79
+ "label_confidence",
80
+ "schema_version",
81
+ "image_id",
82
+ "file_path",
83
+ "file_format",
84
+ "modality",
85
+ "anatomy",
86
+ "device_technology",
87
+ "scan_protocol",
88
+ "scan_x_mm",
89
+ "bscan_index",
90
+ "image_height_px",
91
+ "image_width_px",
92
+ "axial_resolution_um",
93
+ "has_segmentation",
94
+ "n_layers_visible",
95
+ "fovea_x_norm",
96
+ "crt_um",
97
+ "choroid_thickness_um",
98
+ "oct_footprint_bbox_fundus",
99
+ "oct_footprint_bbox_slo",
100
+ "is_valid",
101
+ ]
102
+
103
+ SIDECAR_COLUMNS = [
104
+ "image_id",
105
+ "source_cohort",
106
+ "center",
107
+ "role",
108
+ "split",
109
+ "original_file_path",
110
+ "train_path",
111
+ "deid_path",
112
+ "pii_masked",
113
+ "deid_method",
114
+ "diagnosis_raw",
115
+ "group_raw",
116
+ "diagnosis_group_raw",
117
+ "caption_raw",
118
+ "ocr_age",
119
+ "ocr_sex",
120
+ "ocr_eye",
121
+ "storage",
122
+ ]
123
+
124
+ ADAPTER_SCHEMA = pa.schema(
125
+ [
126
+ ("cohort", pa.string()),
127
+ ("study_id", pa.string()),
128
+ ("patient_hash", pa.string()),
129
+ ("visit_date", pa.string()),
130
+ ("eye", pa.string()),
131
+ ("device_vendor", pa.string()),
132
+ ("device_model", pa.string()),
133
+ ("device_serial_hash", pa.string()),
134
+ ("device_software_version", pa.string()),
135
+ ("hospital_domain", pa.string()),
136
+ ("ethnicity", pa.string()),
137
+ ("image_quality_score", pa.float64()),
138
+ ("image_quality_band", pa.string()),
139
+ ("diagnosis_group", pa.list_(pa.string())),
140
+ ("lesion_tags", pa.list_(pa.string())),
141
+ ("lesion_location", pa.list_(pa.string())),
142
+ ("layer_involvement", pa.list_(pa.string())),
143
+ ("severity", pa.string()),
144
+ ("diagnosis_source", pa.string()),
145
+ ("label_confidence", pa.float64()),
146
+ ("schema_version", pa.string()),
147
+ ("image_id", pa.string()),
148
+ ("file_path", pa.string()),
149
+ ("file_format", pa.string()),
150
+ ("modality", pa.string()),
151
+ ("anatomy", pa.string()),
152
+ ("device_technology", pa.string()),
153
+ ("scan_protocol", pa.string()),
154
+ ("scan_x_mm", pa.float64()),
155
+ ("bscan_index", pa.float64()),
156
+ ("image_height_px", pa.float64()),
157
+ ("image_width_px", pa.float64()),
158
+ ("axial_resolution_um", pa.float64()),
159
+ ("has_segmentation", pa.bool_()),
160
+ ("n_layers_visible", pa.int64()),
161
+ ("fovea_x_norm", pa.float64()),
162
+ ("crt_um", pa.float64()),
163
+ ("choroid_thickness_um", pa.float64()),
164
+ ("oct_footprint_bbox_fundus", pa.list_(pa.int64())),
165
+ ("oct_footprint_bbox_slo", pa.list_(pa.int64())),
166
+ ("is_valid", pa.bool_()),
167
+ ]
168
+ )
169
+
170
+ CAPTIONS_SCHEMA = pa.schema(
171
+ [
172
+ ("caption_id", pa.string()),
173
+ ("image_id", pa.string()),
174
+ ("level", pa.string()),
175
+ ("prompt_text", pa.string()),
176
+ ("language", pa.string()),
177
+ ("generator", pa.string()),
178
+ ("grounded_in", pa.string()),
179
+ ]
180
+ )
181
+
182
+ SIDECAR_SCHEMA = pa.schema(
183
+ [
184
+ ("image_id", pa.string()),
185
+ ("source_cohort", pa.string()),
186
+ ("center", pa.string()),
187
+ ("role", pa.string()),
188
+ ("split", pa.string()),
189
+ ("original_file_path", pa.string()),
190
+ ("train_path", pa.string()),
191
+ ("deid_path", pa.string()),
192
+ ("pii_masked", pa.bool_()),
193
+ ("deid_method", pa.string()),
194
+ ("diagnosis_raw", pa.string()),
195
+ ("group_raw", pa.string()),
196
+ ("diagnosis_group_raw", pa.string()),
197
+ ("caption_raw", pa.string()),
198
+ ("ocr_age", pa.float64()),
199
+ ("ocr_sex", pa.string()),
200
+ ("ocr_eye", pa.string()),
201
+ ("storage", pa.string()),
202
+ ]
203
+ )
204
+
205
+ MODALITY_META = {
206
+ "fundus_color": ("macula", "fundus_camera", "single_shot"),
207
+ "oct_bscan": ("macula", "oct", "bscan"),
208
+ "uwf": ("wide-field", "fundus_camera", "widefield"),
209
+ "ffa": ("retina", "fluorescein_angiography", "angiography"),
210
+ "octa": ("macula", "octa", "enface"),
211
+ "bscan_us": ("globe", "ultrasound", "bscan"),
212
+ "ubm": ("anterior_segment", "ultrasound_biomicroscopy", "bscan"),
213
+ }
214
+
215
+
216
+ def main() -> None:
217
+ args = parse_args()
218
+ args.out.mkdir(parents=True, exist_ok=True)
219
+
220
+ df = pd.read_parquet(args.manifest)
221
+ if args.limit:
222
+ df = df.head(args.limit).copy()
223
+ if args.policy in {"v2", "v3"}:
224
+ df = apply_v2_policy(df)
225
+
226
+ adapter_path = args.out / f"adapter_manifest_{args.policy}.parquet"
227
+ captions_path = args.out / "captions_v2.parquet"
228
+ sidecar_path = args.out / f"sidecar_{args.policy}.parquet"
229
+
230
+ for path in [adapter_path, captions_path, sidecar_path]:
231
+ if path.exists() and not args.overwrite:
232
+ raise FileExistsError(f"{path} exists; pass --overwrite")
233
+ if path.exists():
234
+ path.unlink()
235
+
236
+ adapter_writer: pq.ParquetWriter | None = None
237
+ captions_writer: pq.ParquetWriter | None = None
238
+ sidecar_writer: pq.ParquetWriter | None = None
239
+
240
+ total_adapter = 0
241
+ total_captions = 0
242
+ for start in range(0, len(df), args.chunk_size):
243
+ chunk = df.iloc[start : start + args.chunk_size]
244
+ adapter_rows: list[dict[str, Any]] = []
245
+ caption_rows: list[dict[str, Any]] = []
246
+ sidecar_rows: list[dict[str, Any]] = []
247
+
248
+ for row in chunk.to_dict("records"):
249
+ adapter_rows.append(build_adapter_row(row))
250
+ sidecar_rows.append(build_sidecar_row(row))
251
+ prompts = build_prompts(row)
252
+ grounded = grounded_in(row)
253
+ for level in ["short", "medium", "dense"]:
254
+ caption_rows.append(
255
+ {
256
+ "caption_id": f"{row['image_id']}_{level}",
257
+ "image_id": row["image_id"],
258
+ "level": level,
259
+ "prompt_text": prompts[level],
260
+ "language": "en",
261
+ "generator": f"newdata_prompt_adapter_{args.policy}",
262
+ "grounded_in": grounded,
263
+ }
264
+ )
265
+
266
+ adapter_writer = append_parquet(
267
+ pd.DataFrame(adapter_rows, columns=ADAPTER_COLUMNS),
268
+ adapter_path,
269
+ adapter_writer,
270
+ ADAPTER_SCHEMA,
271
+ )
272
+ captions_writer = append_parquet(
273
+ pd.DataFrame(caption_rows), captions_path, captions_writer, CAPTIONS_SCHEMA
274
+ )
275
+ sidecar_writer = append_parquet(
276
+ pd.DataFrame(sidecar_rows, columns=SIDECAR_COLUMNS),
277
+ sidecar_path,
278
+ sidecar_writer,
279
+ SIDECAR_SCHEMA,
280
+ )
281
+ total_adapter += len(adapter_rows)
282
+ total_captions += len(caption_rows)
283
+ if total_adapter % args.log_every < len(adapter_rows):
284
+ print(f"rows={total_adapter} captions={total_captions}", flush=True)
285
+
286
+ for writer in [adapter_writer, captions_writer, sidecar_writer]:
287
+ if writer is not None:
288
+ writer.close()
289
+
290
+ write_readme(args.out, args.manifest, len(df), total_captions, args.policy)
291
+ write_summary(args.out, df, total_captions, args.policy)
292
+ print(json.dumps({"out": str(args.out), "rows": len(df), "captions": total_captions}, ensure_ascii=False))
293
+
294
+
295
+ def apply_v2_policy(df: pd.DataFrame) -> pd.DataFrame:
296
+ """Apply the first human-reviewed new-data policy before prompt materialization."""
297
+ out = df.copy()
298
+ if "split" not in out.columns:
299
+ raise KeyError("v2 policy requires a split column")
300
+ if "cohort" not in out.columns:
301
+ raise KeyError("v2 policy requires a cohort column")
302
+ if "modality" not in out.columns:
303
+ raise KeyError("v2 policy requires a modality column")
304
+
305
+ out = out[out["split"].eq("train")].copy()
306
+ out = out[~out["cohort"].isin(V2_EXCLUDE_COHORTS)].copy()
307
+ for cohort, modality in V2_MODALITY_OVERRIDES.items():
308
+ out.loc[out["cohort"].eq(cohort), "modality"] = modality
309
+ return out.reset_index(drop=True)
310
+
311
+
312
+ def append_parquet(
313
+ frame: pd.DataFrame, path: Path, writer: pq.ParquetWriter | None, schema: pa.Schema
314
+ ) -> pq.ParquetWriter:
315
+ table = pa.Table.from_pandas(frame, schema=schema, preserve_index=False)
316
+ if writer is None:
317
+ writer = pq.ParquetWriter(path, table.schema, compression="zstd")
318
+ writer.write_table(table)
319
+ return writer
320
+
321
+
322
+ def build_adapter_row(row: dict[str, Any]) -> dict[str, Any]:
323
+ modality = str(row.get("modality") or "unknown")
324
+ anatomy, technology, protocol = MODALITY_META.get(
325
+ modality, ("unknown", "unknown", "unknown")
326
+ )
327
+ if row.get("cohort") == "tongren_external_fundus":
328
+ anatomy = "anterior_segment"
329
+ technology = "external_photography"
330
+ protocol = "single_shot"
331
+
332
+ train_path = str(row.get("train_path") or row.get("file_path") or "")
333
+ diagnosis_group = canonical_diagnoses(row)
334
+ lesion_tags = canonical_lesions(row)
335
+ has_label = bool(diagnosis_group or lesion_tags or clean_text(row.get("caption")))
336
+
337
+ return {
338
+ "cohort": row.get("cohort"),
339
+ "study_id": row.get("image_id"),
340
+ "patient_hash": None,
341
+ "visit_date": None,
342
+ "eye": normalize_eye(row.get("ocr_eye")),
343
+ "device_vendor": "unknown",
344
+ "device_model": "unknown",
345
+ "device_serial_hash": None,
346
+ "device_software_version": None,
347
+ "hospital_domain": "new_data",
348
+ "ethnicity": "unknown",
349
+ "image_quality_score": None,
350
+ "image_quality_band": "unknown",
351
+ "diagnosis_group": diagnosis_group,
352
+ "lesion_tags": lesion_tags,
353
+ "lesion_location": [],
354
+ "layer_involvement": [],
355
+ "severity": "unknown",
356
+ "diagnosis_source": diagnosis_source(row),
357
+ "label_confidence": 1.0 if has_label else None,
358
+ "schema_version": "newdata_adapter_v1",
359
+ "image_id": row.get("image_id"),
360
+ "file_path": train_path,
361
+ "file_format": file_format(train_path),
362
+ "modality": modality,
363
+ "anatomy": anatomy,
364
+ "device_technology": technology,
365
+ "scan_protocol": protocol,
366
+ "scan_x_mm": None,
367
+ "bscan_index": None,
368
+ "image_height_px": None,
369
+ "image_width_px": None,
370
+ "axial_resolution_um": None,
371
+ "has_segmentation": False,
372
+ "n_layers_visible": 0,
373
+ "fovea_x_norm": None,
374
+ "crt_um": None,
375
+ "choroid_thickness_um": None,
376
+ "oct_footprint_bbox_fundus": None,
377
+ "oct_footprint_bbox_slo": None,
378
+ "is_valid": True,
379
+ }
380
+
381
+
382
+ def build_sidecar_row(row: dict[str, Any]) -> dict[str, Any]:
383
+ return {
384
+ "image_id": row.get("image_id"),
385
+ "source_cohort": row.get("cohort"),
386
+ "center": row.get("center"),
387
+ "role": row.get("role"),
388
+ "split": row.get("split"),
389
+ "original_file_path": row.get("file_path"),
390
+ "train_path": row.get("train_path"),
391
+ "deid_path": row.get("deid_path"),
392
+ "pii_masked": bool(row.get("pii_masked")),
393
+ "deid_method": row.get("deid_method"),
394
+ "diagnosis_raw": row.get("diagnosis_raw"),
395
+ "group_raw": row.get("group_raw"),
396
+ "diagnosis_group_raw": row.get("diagnosis_group"),
397
+ "caption_raw": row.get("caption"),
398
+ "ocr_age": clean_scalar(row.get("ocr_age")),
399
+ "ocr_sex": clean_scalar(row.get("ocr_sex")),
400
+ "ocr_eye": clean_scalar(row.get("ocr_eye")),
401
+ "storage": row.get("storage"),
402
+ }
403
+
404
+
405
+ def canonical_diagnoses(row: dict[str, Any]) -> list[str]:
406
+ out: list[str] = []
407
+ for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
408
+ text = clean_text(row.get(key))
409
+ if not text:
410
+ continue
411
+ val = translate_diag(text)
412
+ if is_canonical_label(val):
413
+ add_unique(out, val)
414
+ return out
415
+
416
+
417
+ def canonical_lesions(row: dict[str, Any]) -> list[str]:
418
+ out: list[str] = []
419
+ for key in ["caption", "diagnosis_raw", "diagnosis_group", "group_raw"]:
420
+ for tag in extract_finding_tags(clean_text(row.get(key))):
421
+ add_unique(out, tag)
422
+ return out
423
+
424
+
425
+ def is_canonical_label(text: str) -> bool:
426
+ if not text or "_" in text or len(text) > 80:
427
+ return False
428
+ return not any("\u4e00" <= ch <= "\u9fff" for ch in text)
429
+
430
+
431
+ def add_unique(out: list[str], value: str) -> None:
432
+ if value and value.lower() not in {v.lower() for v in out}:
433
+ out.append(value)
434
+
435
+
436
+ def diagnosis_source(row: dict[str, Any]) -> str:
437
+ if clean_text(row.get("caption")):
438
+ return "clinical_report"
439
+ if clean_text(row.get("diagnosis_raw")) or clean_text(row.get("diagnosis_group")):
440
+ return "file_label"
441
+ if clean_text(row.get("group_raw")):
442
+ return "folder_label"
443
+ return "none"
444
+
445
+
446
+ def grounded_in(row: dict[str, Any]) -> str:
447
+ parts = ["manifest_fields"]
448
+ if (
449
+ clean_scalar(row.get("ocr_age")) is not None
450
+ or clean_scalar(row.get("ocr_sex")) is not None
451
+ or clean_scalar(row.get("ocr_eye")) is not None
452
+ ):
453
+ parts.append("nonidentifying_demographics")
454
+ if diagnosis_source(row) != "none":
455
+ parts.append("clinical_labels")
456
+ return "+".join(parts)
457
+
458
+
459
+ def normalize_eye(value: Any) -> str:
460
+ eye = str(value or "").upper()
461
+ if eye in {"OD", "OS", "OU"}:
462
+ return eye
463
+ return "unknown"
464
+
465
+
466
+ def file_format(path: str) -> str:
467
+ suffix = path.split("::", 1)[1] if "::" in path else path
468
+ ext = Path(suffix).suffix.lower().lstrip(".")
469
+ return ext or "unknown"
470
+
471
+
472
+ def clean_scalar(value: Any) -> Any:
473
+ if value is None:
474
+ return None
475
+ if isinstance(value, float) and math.isnan(value):
476
+ return None
477
+ return value
478
+
479
+
480
+ def write_readme(out: Path, manifest: Path, rows: int, captions: int, policy: str) -> None:
481
+ policy_note = ""
482
+ if policy in {"v2", "v3"}:
483
+ policy_note = f"""
484
+ Human-reviewed {policy} data policy:
485
+
486
+ - keep only `split=train`;
487
+ - exclude cohorts: `{", ".join(sorted(V2_EXCLUDE_COHORTS))}`;
488
+ - modality overrides: `{json.dumps(V2_MODALITY_OVERRIDES, ensure_ascii=False)}`.
489
+ """
490
+
491
+ text = f"""# New Data Prompt Adapter {policy}
492
+
493
+ Source manifest:
494
+
495
+ ```text
496
+ {manifest}
497
+ ```
498
+
499
+ Artifacts:
500
+
501
+ - `adapter_manifest_{policy}.parquet`: OCTFlow-style structured manifest. It follows the old
502
+ 41-column adapter schema. `file_path` points to the actual training image path.
503
+ - `captions_v2.parquet`: SD3 text-conditioning table with columns
504
+ `caption_id,image_id,level,prompt_text,language,generator,grounded_in`.
505
+ - `sidecar_{policy}.parquet`: raw audit fields that are not copied into prompts.
506
+ - `summary.json`: counts and coverage.
507
+
508
+ Rows: {rows}
509
+ Caption rows: {captions}
510
+
511
+ {policy_note}
512
+
513
+ Prompt policy:
514
+
515
+ - `short`: modality phrase only.
516
+ - `medium`: modality phrase + reliable non-identifying demographics + up to 3 English labels.
517
+ - `dense`: modality phrase + reliable non-identifying demographics + up to 8 English labels.
518
+ - No center, hospital, cohort, dataset name, file name, ID, exact date, DOB, raw OCR text, or
519
+ raw Chinese report text is copied into `prompt_text`.
520
+ - Age enters prompts only as buckets such as `in their 60s`, never exact age.
521
+
522
+ The original de-identified image routing remains controlled by the source manifest's `train_path`.
523
+ """
524
+ (out / "README.md").write_text(text, encoding="utf-8")
525
+
526
+
527
+ def write_summary(out: Path, df: pd.DataFrame, captions: int, policy: str) -> None:
528
+ summary = {
529
+ "policy": policy,
530
+ "rows": int(len(df)),
531
+ "captions": int(captions),
532
+ "by_modality": df.groupby("modality").size().astype(int).to_dict(),
533
+ "by_cohort": df.groupby("cohort").size().astype(int).to_dict(),
534
+ "pii_masked": int(df["pii_masked"].fillna(False).sum()) if "pii_masked" in df else 0,
535
+ }
536
+ if policy in {"v2", "v3"}:
537
+ summary[f"{policy}_exclude_cohorts"] = sorted(V2_EXCLUDE_COHORTS)
538
+ summary[f"{policy}_modality_overrides"] = V2_MODALITY_OVERRIDES
539
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
540
+
541
+
542
+ def parse_args() -> argparse.Namespace:
543
+ parser = argparse.ArgumentParser()
544
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
545
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
546
+ parser.add_argument("--chunk-size", type=int, default=100_000)
547
+ parser.add_argument("--log-every", type=int, default=500_000)
548
+ parser.add_argument("--limit", type=int, default=None)
549
+ parser.add_argument("--overwrite", action="store_true")
550
+ parser.add_argument("--policy", choices=["v1", "v2", "v3"], default="v1")
551
+ return parser.parse_args()
552
+
553
+
554
+ if __name__ == "__main__":
555
+ main()
data_processing/04_modality_split/split_octbuckets_octa_review.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): split_octbuckets_octa_review.py
4
+ 原本用途 (Original Purpose):
5
+ 启发式多特征混杂 OCT 模态拆分与人工复审流水线。提取纵横比、边缘密度、层状结构评分(Layer score)与血管流信号评分(Vessel score),将打包混杂的 OCT 数据精准解耦分离为 B-scan、OCTA en-face 与 SLO 样图像。
6
+ 适用数据集 (Target Dataset):
7
+ archives/data0410/ 中的 octBuckets.zip(34,519 张多模态混合 OCT 图像)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 包含混杂扫描模式的 octBuckets 图像集
12
+ 输出结果 (Output):
13
+ 按真实模态分类的 CSV 清单(oct_bscan, octa_enface, oct_enface_or_slo_like)及单张复审 HTML
14
+ 依赖环境 (Dependencies):
15
+ numpy, pandas, pillow, tarfile
16
+ ================================================================================
17
+ """
18
+
19
+ """Split the mixed octbuckets_octa cohort into reviewable OCT subtypes.
20
+
21
+ This script is read-only with respect to source images and training manifests.
22
+ It produces:
23
+ - auto_labels.csv: one row per image with heuristic subtype and features
24
+ - review_candidates.csv: non-B-scan, uncertain, and sampled B-scan rows
25
+ - OPEN_THIS_OCTBUCKETS_OCTA_REVIEW.html: single-image manual review page
26
+ - thumbs/: local thumbnails referenced by the HTML
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import html
33
+ import io
34
+ import json
35
+ import random
36
+ import re
37
+ import tarfile
38
+ from dataclasses import asdict, dataclass
39
+ from pathlib import Path
40
+ from typing import Any
41
+
42
+ import numpy as np
43
+ import pandas as pd
44
+ from PIL import Image
45
+
46
+
47
+ DEFAULT_MANIFEST = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6/adapter_manifest_mixed_v6.parquet")
48
+ DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/octbuckets_octa_split_20260708")
49
+
50
+ LABELS = ["oct_bscan", "octa_enface", "oct_enface_or_slo_like", "unknown"]
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Classification:
55
+ label: str
56
+ confidence: float
57
+ reason: str
58
+ aspect_ratio: float
59
+ edge_density: float
60
+ horizontal_edge_ratio: float
61
+ vertical_edge_ratio: float
62
+ dark_fraction: float
63
+ bright_fraction: float
64
+ layer_score: float
65
+ vessel_score: float
66
+ enface_score: float
67
+
68
+
69
+ class ImageOpener:
70
+ def __init__(self) -> None:
71
+ self._tar_cache: dict[str, tarfile.TarFile] = {}
72
+
73
+ def close(self) -> None:
74
+ for tf in self._tar_cache.values():
75
+ tf.close()
76
+ self._tar_cache.clear()
77
+
78
+ def open(self, path: str) -> Image.Image:
79
+ if "::" not in path:
80
+ return Image.open(path).convert("RGB")
81
+ tar_path, member = path.split("::", 1)
82
+ tf = self._tar_cache.get(tar_path)
83
+ if tf is None:
84
+ tf = tarfile.open(tar_path, "r:*")
85
+ self._tar_cache[tar_path] = tf
86
+ fh = tf.extractfile(member)
87
+ if fh is None:
88
+ raise FileNotFoundError(member)
89
+ return Image.open(io.BytesIO(fh.read())).convert("RGB")
90
+
91
+
92
+ def _to_gray_resized(arr: np.ndarray, size: int = 192) -> tuple[np.ndarray, float]:
93
+ if arr.ndim == 3:
94
+ gray = np.dot(arr[..., :3], [0.299, 0.587, 0.114])
95
+ else:
96
+ gray = arr.astype(np.float32)
97
+ h, w = gray.shape[:2]
98
+ aspect = max(w / max(h, 1), h / max(w, 1))
99
+ im = Image.fromarray(np.clip(gray, 0, 255).astype(np.uint8)).resize((size, size), Image.Resampling.BILINEAR)
100
+ out = np.asarray(im, dtype=np.float32) / 255.0
101
+ p1, p99 = np.percentile(out, [1, 99])
102
+ if p99 > p1 + 0.05:
103
+ out = np.clip((out - p1) / (p99 - p1), 0, 1)
104
+ return out, float(aspect)
105
+
106
+
107
+ def classify_array(arr: np.ndarray) -> Classification:
108
+ gray, aspect = _to_gray_resized(arr)
109
+ gy, gx = np.gradient(gray)
110
+ agx = np.abs(gx)
111
+ agy = np.abs(gy)
112
+ mag = agx + agy
113
+ edge_threshold = max(float(np.quantile(mag, 0.86)), 0.035)
114
+ edges = mag > edge_threshold
115
+ edge_count = int(edges.sum())
116
+ total = int(edges.size)
117
+ edge_density = edge_count / max(total, 1)
118
+ if edge_count:
119
+ horizontal = ((agy > agx * 1.20) & edges).sum() / edge_count
120
+ vertical = ((agx > agy * 1.20) & edges).sum() / edge_count
121
+ else:
122
+ horizontal = 0.0
123
+ vertical = 0.0
124
+
125
+ dark_fraction = float((gray < 0.12).mean())
126
+ bright_fraction = float((gray > 0.78).mean())
127
+ row_profile = gray.mean(axis=1)
128
+ col_profile = gray.mean(axis=0)
129
+ row_variation = float(row_profile.std())
130
+ col_variation = float(col_profile.std())
131
+ anisotropy = abs(horizontal - vertical)
132
+
133
+ layer_score = (
134
+ 0.52 * horizontal
135
+ + 0.23 * min(row_variation / 0.18, 1.0)
136
+ + 0.15 * min(dark_fraction / 0.45, 1.0)
137
+ + 0.10 * min(aspect / 2.0, 1.0)
138
+ )
139
+ vessel_score = (
140
+ 0.42 * min(edge_density / 0.18, 1.0)
141
+ + 0.30 * min(bright_fraction / 0.14, 1.0)
142
+ + 0.18 * max(0.0, 1.0 - anisotropy / 0.55)
143
+ + 0.10 * min((row_variation + col_variation) / 0.28, 1.0)
144
+ )
145
+ enface_score = (
146
+ 0.40 * max(0.0, 1.0 - min(aspect - 1.0, 1.0))
147
+ + 0.25 * max(0.0, 1.0 - min(layer_score / 0.72, 1.0))
148
+ + 0.20 * min(edge_density / 0.12, 1.0)
149
+ + 0.15 * min(float(gray.std()) / 0.24, 1.0)
150
+ )
151
+
152
+ if layer_score >= 0.54 and horizontal >= 0.42 and (dark_fraction >= 0.18 or aspect >= 1.35):
153
+ label = "oct_bscan"
154
+ confidence = min(0.98, 0.62 + (layer_score - 0.54) * 1.25 + max(0.0, horizontal - 0.42))
155
+ reason = "layer-dominant horizontal OCT cross-section"
156
+ elif vessel_score >= 0.56 and layer_score < 0.58 and edge_density >= 0.08:
157
+ label = "octa_enface"
158
+ confidence = min(0.95, 0.55 + (vessel_score - 0.56) * 1.20 + max(0.0, edge_density - 0.08))
159
+ reason = "dense vessel-like en-face network"
160
+ elif enface_score >= 0.56 and layer_score < 0.62 and aspect <= 1.45:
161
+ label = "oct_enface_or_slo_like"
162
+ confidence = min(0.90, 0.52 + (enface_score - 0.56) * 1.10)
163
+ reason = "fundus-like gray en-face projection without dominant layers"
164
+ else:
165
+ label = "unknown"
166
+ confidence = max(0.30, min(0.58, max(layer_score, vessel_score, enface_score)))
167
+ reason = "ambiguous OCT/OCTA appearance"
168
+
169
+ return Classification(
170
+ label=label,
171
+ confidence=round(float(confidence), 4),
172
+ reason=reason,
173
+ aspect_ratio=round(float(aspect), 4),
174
+ edge_density=round(float(edge_density), 4),
175
+ horizontal_edge_ratio=round(float(horizontal), 4),
176
+ vertical_edge_ratio=round(float(vertical), 4),
177
+ dark_fraction=round(float(dark_fraction), 4),
178
+ bright_fraction=round(float(bright_fraction), 4),
179
+ layer_score=round(float(layer_score), 4),
180
+ vessel_score=round(float(vessel_score), 4),
181
+ enface_score=round(float(enface_score), 4),
182
+ )
183
+
184
+
185
+ def choose_review_rows(
186
+ rows: list[dict[str, Any]],
187
+ bscan_sample: int,
188
+ uncertain_threshold: float,
189
+ seed: int,
190
+ ) -> list[dict[str, Any]]:
191
+ selected: list[dict[str, Any]] = []
192
+ bscan_pool: list[dict[str, Any]] = []
193
+ seen: set[str] = set()
194
+ for row in rows:
195
+ label = str(row["auto_subtype"])
196
+ conf = float(row["confidence"])
197
+ image_id = str(row["image_id"])
198
+ needs_review = label != "oct_bscan" or conf < uncertain_threshold
199
+ if needs_review:
200
+ selected.append(row)
201
+ seen.add(image_id)
202
+ elif bscan_sample > 0:
203
+ bscan_pool.append(row)
204
+ rng = random.Random(seed)
205
+ rng.shuffle(bscan_pool)
206
+ for row in bscan_pool[:bscan_sample]:
207
+ image_id = str(row["image_id"])
208
+ if image_id not in seen:
209
+ selected.append(row)
210
+ seen.add(image_id)
211
+ return selected
212
+
213
+
214
+ def save_thumb(im: Image.Image, out: Path, size: int) -> None:
215
+ thumb = im.copy()
216
+ thumb.thumbnail((size, size), Image.Resampling.LANCZOS)
217
+ canvas = Image.new("RGB", (size, size), (245, 245, 245))
218
+ canvas.paste(thumb, ((size - thumb.width) // 2, (size - thumb.height) // 2))
219
+ canvas.save(out, quality=90)
220
+
221
+
222
+ def safe_name(value: str) -> str:
223
+ return re.sub(r"[^A-Za-z0-9_.-]+", "_", value)[:160]
224
+
225
+
226
+ def build_html(records: list[dict[str, Any]], out: Path, title: str) -> None:
227
+ rows_json = json.dumps(records, ensure_ascii=False).replace("</", "<\\/")
228
+ labels_json = json.dumps(LABELS, ensure_ascii=False)
229
+ css = """:root{--bg:#f4f6f8;--panel:#fff;--line:#d8dee8;--text:#1f2937;--muted:#64748b;--blue:#0f62fe;--green:#177245;--red:#b42318;--amber:#9a5b00}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:Arial,"Noto Sans CJK SC","Microsoft YaHei",sans-serif}header{position:sticky;top:0;z-index:10;background:var(--panel);border-bottom:1px solid var(--line);padding:12px 16px;box-shadow:0 1px 8px rgba(15,23,42,.07)}h1{font-size:18px;margin:0 0 8px}.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.muted{color:var(--muted);font-size:13px}.progress{font-size:13px;min-width:260px}.viewer{display:grid;grid-template-columns:minmax(420px,52vw) 1fr;gap:14px;padding:14px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:12px}.imgbox{height:min(70vh,720px);min-height:420px;background:#080808;display:flex;align-items:center;justify-content:center;overflow:hidden;border:1px solid #111}.imgbox img{max-width:100%;max-height:100%;object-fit:contain}.badge{display:inline-block;border-radius:999px;padding:3px 8px;margin:0 5px 6px 0;font-size:12px;background:#edf2ff;color:#173b8f}.ok{background:#e8f5e9;color:#1b5e20}.warn{background:#fff7e6;color:#8a4b00}.bad{background:#ffecec;color:#9b1c1c}.meta{font-size:13px;line-height:1.5;word-break:break-word}.features{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 12px;margin-top:8px;font-size:12px;color:#334155}.review{border-top:1px solid var(--line);margin-top:10px;padding-top:10px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0}button,select,input,textarea{font-size:13px;border:1px solid #b8c0cc;border-radius:4px;background:#fff;padding:7px 9px}button{cursor:pointer}button.primary{background:var(--blue);border-color:var(--blue);color:#fff}button.good{background:#e9f7ef;color:var(--green);border-color:#a8ddb9}button.drop{background:#fff1f0;color:var(--red);border-color:#ffccc7}textarea{width:100%;height:78px;resize:vertical}.path{font-family:monospace;font-size:12px;color:#334155}.hint{margin-top:6px;font-size:12px;color:var(--muted)}@media(max-width:1000px){.viewer{grid-template-columns:1fr}.imgbox{height:520px}}"""
230
+ js = f"""
231
+ const rows = JSON.parse(document.getElementById('rows-data').textContent);
232
+ const labels = {labels_json};
233
+ const storageKey = 'octbuckets_octa_split_review_20260708';
234
+ let idx = Number(localStorage.getItem(storageKey + ':idx') || 0);
235
+ let edits = JSON.parse(localStorage.getItem(storageKey) || '{{}}');
236
+ function esc(v) {{ return String(v ?? '').replace(/[&<>"']/g, c => ({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[c])); }}
237
+ function edit(id) {{ return edits[id] || {{status:'unreviewed', final_subtype:'', note:''}}; }}
238
+ function save() {{ localStorage.setItem(storageKey, JSON.stringify(edits)); localStorage.setItem(storageKey + ':idx', String(idx)); }}
239
+ function counts() {{ const c={{unreviewed:0,reviewed:0,drop:0}}; rows.forEach(r=>{{ const s=edit(r.image_id).status || 'unreviewed'; c[s]=(c[s]||0)+1; }}); return c; }}
240
+ function go(delta) {{ idx=Math.max(0, Math.min(rows.length-1, idx+delta)); save(); render(); }}
241
+ function gotoIndex(v) {{ const n=Number(v); if (!Number.isNaN(n)) {{ idx=Math.max(0,Math.min(rows.length-1,n-1)); save(); render(); }} }}
242
+ function setLabel(label, advance=true) {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,status:'reviewed',final_subtype:label}}; save(); if (advance) go(1); else render(); }}
243
+ function dropRow() {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,status:'drop',final_subtype:'exclude'}}; save(); go(1); }}
244
+ function updateNote(v) {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,note:v}}; save(); }}
245
+ function mergedRows() {{ return rows.map(r=>{{ const e=edit(r.image_id); return {{...r,status:e.status||'unreviewed',final_subtype:e.final_subtype||r.auto_subtype,note:e.note||''}}; }}); }}
246
+ function download(name, text, type) {{ const blob=new Blob([text],{{type}}); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download=name; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }}
247
+ function exportCSV() {{ const out=mergedRows(); const cols=['image_id','cohort','current_subtype','auto_subtype','confidence','status','final_subtype','note','reason','file_path']; const csv=[cols.join(',')].concat(out.map(o=>cols.map(c=>'"'+String(o[c]??'').replaceAll('"','""')+'"').join(','))).join('\\n'); download('octbuckets_octa_split_review_edits.csv', csv, 'text/csv'); }}
248
+ function exportJSON() {{ download('octbuckets_octa_split_review_edits.json', JSON.stringify(mergedRows(), null, 2), 'application/json'); }}
249
+ function labelSelect(current) {{ return '<select onchange="setLabel(this.value,false)">' + labels.concat(['exclude']).map(x=>`<option value="${{esc(x)}}" ${{x===current?'selected':''}}>${{esc(x)}}</option>`).join('') + '</select>'; }}
250
+ function badgeClass(r) {{ if (r.auto_subtype === 'oct_bscan' && Number(r.confidence) >= 0.65) return 'ok'; if (r.auto_subtype === 'unknown' || Number(r.confidence) < 0.60) return 'warn'; return 'bad'; }}
251
+ function render() {{
252
+ if (!rows.length) {{ document.getElementById('root').innerHTML='<div class=viewer><div class=panel>没有审核样本。</div></div>'; return; }}
253
+ const r=rows[idx]; const e=edit(r.image_id); const final=e.final_subtype || r.auto_subtype; const c=counts();
254
+ document.getElementById('progress').textContent=`第 ${{idx+1}} / ${{rows.length}} 张;已看 ${{c.reviewed||0}},排除 ${{c.drop||0}},未看 ${{c.unreviewed||0}}`;
255
+ document.getElementById('jump').value=idx+1;
256
+ document.getElementById('root').innerHTML=`<section class="viewer"><div class="panel"><div class="imgbox"><img src="${{esc(r.thumb_rel)}}" loading="eager"></div></div><div class="panel"><div><span class="badge ${{badgeClass(r)}}">自动:${{esc(r.auto_subtype)}} (${{Number(r.confidence).toFixed(2)}})</span><span class="badge">当前:${{esc(r.current_subtype)}}</span><span class="badge">最终:${{esc(final)}}</span></div><div class="meta"><b>图像 ID</b>:${{esc(r.image_id)}}<br><b>cohort</b>:${{esc(r.cohort)}}<br><b>理由</b>:${{esc(r.reason)}}<br><b>路径</b>:<span class="path">${{esc(r.file_path)}}</span></div><div class="features"><div>aspect: ${{esc(r.aspect_ratio)}}</div><div>edge_density: ${{esc(r.edge_density)}}</div><div>horizontal: ${{esc(r.horizontal_edge_ratio)}}</div><div>vertical: ${{esc(r.vertical_edge_ratio)}}</div><div>dark: ${{esc(r.dark_fraction)}}</div><div>bright: ${{esc(r.bright_fraction)}}</div><div>layer_score: ${{esc(r.layer_score)}}</div><div>vessel_score: ${{esc(r.vessel_score)}}</div><div>enface_score: ${{esc(r.enface_score)}}</div></div><div class="review"><div class="row"><button class="good" onclick="setLabel('oct_bscan')">1 B-scan</button><button class="good" onclick="setLabel('octa_enface')">2 OCTA en face</button><button class="good" onclick="setLabel('oct_enface_or_slo_like')">3 en face/SLO-like</button><button class="drop" onclick="dropRow()">4 unknown/exclude</button><button onclick="setLabel('${{esc(final)}}', false)">只保存</button></div><div class="row"><label>最终标签:${{labelSelect(final)}}</label></div><textarea placeholder="备注" oninput="updateNote(this.value)">${{esc(e.note || '')}}</textarea></div><div class="hint">快捷键:1/2/3/4 标注并下一张,←/→ 上一张/下一张,C 导出 CSV,J 导出 JSON。备注框内不会触发快捷键。</div></div></section>`;
257
+ }}
258
+ document.addEventListener('keydown', ev => {{
259
+ const tag=(ev.target && ev.target.tagName || '').toLowerCase();
260
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
261
+ if (ev.key === 'ArrowRight') go(1);
262
+ else if (ev.key === 'ArrowLeft') go(-1);
263
+ else if (ev.key === '1') setLabel('oct_bscan');
264
+ else if (ev.key === '2') setLabel('octa_enface');
265
+ else if (ev.key === '3') setLabel('oct_enface_or_slo_like');
266
+ else if (ev.key === '4') dropRow();
267
+ else if (ev.key.toLowerCase() === 'c') exportCSV();
268
+ else if (ev.key.toLowerCase() === 'j') exportJSON();
269
+ }});
270
+ render();
271
+ """
272
+ doc = f"""<!doctype html>
273
+ <html><head><meta charset="utf-8"><title>{html.escape(title)}</title><style>{css}</style></head>
274
+ <body><header><h1>{html.escape(title)}</h1><div class="bar"><span id="progress" class="progress"></span><button onclick="go(-1)">上一张</button><button class="primary" onclick="go(1)">下一张</button><label>跳转 <input id="jump" type="number" min="1" max="{len(records)}" onchange="gotoIndex(this.value)" style="width:80px"></label><button onclick="exportCSV()">导出 CSV</button><button onclick="exportJSON()">导出 JSON</button></div><div class="hint">只审核自动非 B-scan、低置信度样本,以及抽样 B-scan。源图和 manifest 不会被修改。</div></header><main id="root"></main><script type="application/json" id="rows-data">{rows_json}</script><script>{js}</script></body></html>"""
275
+ out.write_text(doc, encoding="utf-8")
276
+
277
+
278
+ def parse_args() -> argparse.Namespace:
279
+ p = argparse.ArgumentParser(description=__doc__)
280
+ p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
281
+ p.add_argument("--out", type=Path, default=DEFAULT_OUT)
282
+ p.add_argument("--cohort", default="octbuckets_octa")
283
+ p.add_argument("--limit", type=int, default=0, help="Debug limit; 0 means all rows.")
284
+ p.add_argument("--seed", type=int, default=20260708)
285
+ p.add_argument("--thumb-size", type=int, default=512)
286
+ p.add_argument("--review-bscan-sample", type=int, default=300)
287
+ p.add_argument("--uncertain-threshold", type=float, default=0.65)
288
+ return p.parse_args()
289
+
290
+
291
+ def main() -> None:
292
+ args = parse_args()
293
+ args.out.mkdir(parents=True, exist_ok=True)
294
+ thumb_dir = args.out / "thumbs"
295
+ thumb_dir.mkdir(parents=True, exist_ok=True)
296
+
297
+ cols = ["image_id", "cohort", "modality", "modality_subtype", "file_path"]
298
+ rows = pd.read_parquet(args.manifest, columns=cols)
299
+ rows = rows[rows["cohort"].astype(str).eq(args.cohort)].copy()
300
+ rows = rows.sort_values(["file_path", "image_id"]).reset_index(drop=True)
301
+ if args.limit:
302
+ rows = rows.head(args.limit).copy()
303
+ print(f"[load] {len(rows)} rows from {args.manifest} cohort={args.cohort}", flush=True)
304
+
305
+ opener = ImageOpener()
306
+ records: list[dict[str, Any]] = []
307
+ try:
308
+ for i, row in enumerate(rows.itertuples(index=False), start=1):
309
+ try:
310
+ im = opener.open(str(row.file_path))
311
+ arr = np.asarray(im)
312
+ result = classify_array(arr)
313
+ rec = {
314
+ "image_id": str(row.image_id),
315
+ "cohort": str(row.cohort),
316
+ "modality": str(row.modality),
317
+ "current_subtype": str(row.modality_subtype),
318
+ "file_path": str(row.file_path),
319
+ "auto_subtype": result.label,
320
+ **asdict(result),
321
+ "open_error": "",
322
+ }
323
+ except Exception as exc:
324
+ rec = {
325
+ "image_id": str(row.image_id),
326
+ "cohort": str(row.cohort),
327
+ "modality": str(row.modality),
328
+ "current_subtype": str(row.modality_subtype),
329
+ "file_path": str(row.file_path),
330
+ "auto_subtype": "unknown",
331
+ "label": "unknown",
332
+ "confidence": 0.0,
333
+ "reason": "open/classify error",
334
+ "open_error": repr(exc),
335
+ }
336
+ records.append(rec)
337
+ if i % 1000 == 0 or i == len(rows):
338
+ print(f"[classify] {i}/{len(rows)}", flush=True)
339
+ finally:
340
+ opener.close()
341
+
342
+ auto = pd.DataFrame(records)
343
+ auto_path = args.out / "auto_labels.csv"
344
+ auto.to_csv(auto_path, index=False)
345
+ summary = {
346
+ "rows": len(auto),
347
+ "auto_subtype_counts": auto["auto_subtype"].value_counts(dropna=False).to_dict(),
348
+ "open_errors": int((auto.get("open_error", "") != "").sum()) if "open_error" in auto else 0,
349
+ "uncertain_threshold": args.uncertain_threshold,
350
+ "review_bscan_sample": args.review_bscan_sample,
351
+ }
352
+ (args.out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
353
+ print("[summary]", json.dumps(summary, ensure_ascii=False), flush=True)
354
+
355
+ review = choose_review_rows(records, args.review_bscan_sample, args.uncertain_threshold, args.seed)
356
+ opener = ImageOpener()
357
+ try:
358
+ for i, rec in enumerate(review, start=1):
359
+ thumb_name = f"{i:05d}_{safe_name(rec['image_id'])}.jpg"
360
+ thumb_path = thumb_dir / thumb_name
361
+ rec["thumb_rel"] = f"thumbs/{thumb_name}"
362
+ if not thumb_path.exists():
363
+ try:
364
+ save_thumb(opener.open(str(rec["file_path"])), thumb_path, args.thumb_size)
365
+ except Exception as exc:
366
+ rec["thumb_rel"] = ""
367
+ rec["open_error"] = repr(exc)
368
+ if i % 500 == 0 or i == len(review):
369
+ print(f"[thumbs] {i}/{len(review)}", flush=True)
370
+ finally:
371
+ opener.close()
372
+
373
+ review_path = args.out / "review_candidates.csv"
374
+ pd.DataFrame(review).to_csv(review_path, index=False)
375
+ html_path = args.out / "OPEN_THIS_OCTBUCKETS_OCTA_REVIEW.html"
376
+ build_html(review, html_path, "octbuckets_octa 自动拆分人工审核")
377
+ print(json.dumps({"out": str(args.out), "auto_labels": str(auto_path), "review_rows": len(review), "html": str(html_path)}, ensure_ascii=False), flush=True)
378
+
379
+
380
+ if __name__ == "__main__":
381
+ main()
data_processing/05_taxonomy_and_prompts/build_clean_captions.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): build_clean_captions.py
4
+ 原本用途 (Original Purpose):
5
+ 预训练文本提示词偏置剔除与净态 Prompt 生成工具。就地正则扫描全量预训练图文对,彻底剥离含有 "from the EyePACS dataset"、"Messidor dataset" 等 51.9% 的数据集专有名称,保留设备型号、眼别、质控与解剖病灶特征,避免模型学习到数据集先验偏置。
6
+ 适用数据集 (Target Dataset):
7
+ 全库 1.2M 跨模态预训练图文对(OCT 840k + 眼底 250k + SLO 120k)。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 / 团队, 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 原始含有数据源名称偏置的预训练 Prompts Parquet 表
12
+ 输出结果 (Output):
13
+ 400 万条零丢失、100% 净态的无偏预训练文本表(pretrain_captions_clean.parquet)
14
+ 依赖环境 (Dependencies):
15
+ pyarrow, pandas, re
16
+ ================================================================================
17
+ """
18
+
19
+ """Strip dataset-name phrases from the pretrain captions -> clean-prompt caption file.
20
+
21
+ Goal (user, 2026-06-05): continue-train the base on CLEAN prompts (no dataset provenance) for
22
+ OCT + fundus + SLO. The user's HF caption update is NOT synced to h800; but the existing
23
+ pretrain_captions.parquet already encodes the clinical info — it just also names the source
24
+ dataset ~54% of the time. Rather than drop those (would lose 30% of images that have NO clean
25
+ level), we REMOVE the dataset-name clauses in place, keeping device / eye / quality / disease.
26
+ Device vendors (Topcon/Heidelberg/Zeiss/Optovue/Bioptigen/BMizar) are KEPT — only dataset names go.
27
+ """
28
+ from __future__ import annotations
29
+ import re
30
+ import pandas as pd
31
+
32
+ IN = "pilot/path1/data_pretrain_full/pretrain_captions.parquet"
33
+ OUT = "pilot/path1/data_pretrain_full/pretrain_captions_clean.parquet"
34
+
35
+ # dataset proper nouns to strip (NOT device vendors)
36
+ DATASETS = (r"EyePACS|OCTA-?500|Kermany( 2018)?|UESTC|Messidor-?2?|IDRiD|REFUGE-?2?|GAMMA|OLIVES|"
37
+ r"RETOUCH|AREDS2?|OCTDL|OCTID|OIMHS|NEH-?UT-?2021|NYU POAG|AROI|Srinivasan( 2014)?|"
38
+ r"Chiu( DME)?( 2015)?|Stratus TD|THOCT-?1800|Sparsity SDOCT( 2012)?|DRIVE|combo_dr_aug")
39
+ DETECT = (r"dataset|EyePACS|OCTA-?500|Kermany|UESTC|Messidor|IDRiD|REFUGE|GAMMA|OLIVES|RETOUCH|"
40
+ r"AREDS|combo_dr|despeckling|classification dataset|screening dataset")
41
+
42
+
43
+ def clean(t):
44
+ t = str(t)
45
+ # ", ... from the <...> dataset (...)" clause
46
+ t = re.sub(r",?\s*(captured|acquired)?\s*from the [^.]*?dataset(\s*\([^)]*\))?", "", t, flags=re.I)
47
+ # leading "<...> dataset (...), "
48
+ t = re.sub(r"^[^,.]*?dataset(\s*\([^)]*\))?\s*,?\s*", "", t, flags=re.I)
49
+ # generic filler "public dataset style"
50
+ t = re.sub(r",?\s*public dataset style", "", t, flags=re.I)
51
+ # any remaining "<...> dataset (...)" fragment
52
+ t = re.sub(r"[^,.]*?dataset(\s*\([^)]*\))?\s*,?", "", t, flags=re.I)
53
+ # parenthetical dataset notes
54
+ t = re.sub(r"\([^)]*(despeckling|UCSD|NEI|Croatia|Indian|Iranian)[^)]*\)", "", t, flags=re.I)
55
+ # leftover standalone dataset proper nouns (device vendors preserved)
56
+ t = re.sub(rf"\b({DATASETS})\b\s*,?\s*", "", t, flags=re.I)
57
+ # cleanup
58
+ t = re.sub(r"\s+", " ", t)
59
+ t = re.sub(r"\s*,\s*,", ",", t)
60
+ t = re.sub(r"\s*,\s*\.", ".", t)
61
+ t = re.sub(r"^[\s,]+", "", t)
62
+ t = re.sub(r"\s*,\s*$", ".", t).strip()
63
+ if t and t[0].islower():
64
+ t = t[0].upper() + t[1:]
65
+ if t and not t.endswith("."):
66
+ t += "."
67
+ return t
68
+
69
+
70
+ def main():
71
+ d = pd.read_parquet(IN)
72
+ before = d.prompt_text.astype(str).str.contains(DETECT, case=False, regex=True).mean()
73
+ d["prompt_text"] = d.prompt_text.map(clean)
74
+ after = d.prompt_text.astype(str).str.contains(DETECT, case=False, regex=True).mean()
75
+ # drop empties / too-short (fallback to a generic modality caption would need modality; just guard)
76
+ d = d[d.prompt_text.str.len() >= 6].reset_index(drop=True)
77
+ d.to_parquet(OUT)
78
+ print(f"rows {len(d)} | dataset-name ratio before {before:.3f} -> after {after:.3f}")
79
+ print("clean samples:")
80
+ for s in d.prompt_text.drop_duplicates().head(12):
81
+ print(" ", s[:95])
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
data_processing/05_taxonomy_and_prompts/build_mixed_v5_taxonomy.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): build_mixed_v5_taxonomy.py
4
+ 原本用途 (Original Purpose):
5
+ 跨中心临床诊断多表交叉映射字典(Crosswalk)生成脚本(v5 阶段版本)。汇总各合作医院的不同表述并归一化。
6
+ 适用数据集 (Target Dataset):
7
+ 同仁、浙二、邯郸等不同医院原始病历中的异构眼病诊断词条。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 多中心原始诊断列表
12
+ 输出结果 (Output):
13
+ 同义词归一化映射对照表
14
+ 依赖环境 (Dependencies):
15
+ pandas, json
16
+ ================================================================================
17
+ """
18
+
19
+ """Build the mixed v5 prompt/taxonomy artifact from the mixed v4 artifact.
20
+
21
+ v5 keeps the v4 image routing unchanged, but separates raw modality labels from
22
+ paper-facing modality taxonomy. It also rewrites prompt prefixes so UWF, OCT
23
+ views, and SLO variants are described as family/subtype/view/protocol rather
24
+ than as unrelated independent modalities.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import math
32
+ import re
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+
37
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v4")
38
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v5")
39
+
40
+ NEW_COLUMNS = [
41
+ "taxonomy_version",
42
+ "modality_family",
43
+ "modality_subtype",
44
+ "view_or_projection",
45
+ "field_of_view",
46
+ "device_or_acquisition_protocol",
47
+ "prompt_modality_phrase",
48
+ ]
49
+
50
+ OLD_PROMPT_PREFIXES = [
51
+ "optical coherence tomography angiography en face image",
52
+ "fundus fluorescein angiography image",
53
+ "fluorescein fundus angiography image",
54
+ "retinal fluorescein angiography image",
55
+ "ultra-widefield retinal fundus photograph",
56
+ "ultra-widefield color fundus photograph",
57
+ "ultra-widefield fundus photograph",
58
+ "ultra-widefield fundus image",
59
+ "ultra-widefield fundus",
60
+ "ultrasound biomicroscopy image of the anterior segment",
61
+ "ultrasound biomicroscopy image",
62
+ "B-scan ultrasonography image",
63
+ "ocular B-scan ultrasound image",
64
+ "structural OCT en face projection",
65
+ "structural OCT B-scan",
66
+ "OCTA en face image",
67
+ "OCT B-scan",
68
+ "color fundus photograph",
69
+ "color fundus",
70
+ "anterior segment photograph",
71
+ "slit-lamp anterior segment photograph",
72
+ "infrared SLO",
73
+ "IR-SLO",
74
+ "SLO",
75
+ ]
76
+
77
+
78
+ def derive_taxonomy(row: dict[str, Any]) -> dict[str, str]:
79
+ modality = _clean(row.get("modality")).lower()
80
+ anatomy = _clean(row.get("anatomy")).lower()
81
+ technology = _clean(row.get("device_technology")).lower()
82
+ protocol = _clean(row.get("scan_protocol")).lower()
83
+
84
+ if modality == "fundus_color" and (
85
+ anatomy == "anterior_segment" or technology == "external_photography"
86
+ ):
87
+ return _tax(
88
+ "anterior_segment_photography",
89
+ "external_anterior_segment_photo",
90
+ "single_shot",
91
+ "anterior_segment",
92
+ technology,
93
+ protocol,
94
+ )
95
+ if modality == "fundus_color":
96
+ return _tax(
97
+ "color_fundus_photography",
98
+ "standard_color_fundus",
99
+ "single_shot",
100
+ _posterior_fov(anatomy, "standard"),
101
+ technology,
102
+ protocol,
103
+ )
104
+ if modality == "uwf":
105
+ return _tax(
106
+ "color_fundus_photography",
107
+ "uwf_color_fundus",
108
+ "single_shot",
109
+ "ultra_widefield",
110
+ technology or "fundus_camera",
111
+ protocol or "widefield",
112
+ )
113
+ if modality == "ffa":
114
+ return _tax(
115
+ "fluorescein_angiography",
116
+ "fundus_fluorescein_angiography",
117
+ "angiography",
118
+ _posterior_fov(anatomy, "standard"),
119
+ technology or "fluorescein_angiography",
120
+ protocol or "angiography",
121
+ )
122
+ if modality == "oct_bscan":
123
+ return _tax(
124
+ "structural_oct",
125
+ "oct_bscan",
126
+ "bscan",
127
+ _posterior_fov(anatomy, "macula"),
128
+ technology or "oct",
129
+ protocol or "bscan",
130
+ )
131
+ if modality == "oct_enface":
132
+ return _tax(
133
+ "structural_oct",
134
+ "oct_enface",
135
+ "en_face_projection",
136
+ _posterior_fov(anatomy, "macula"),
137
+ technology or "oct",
138
+ protocol or "en_face_projection",
139
+ )
140
+ if modality == "octa_enface" or modality == "octa":
141
+ return _tax(
142
+ "oct_angiography",
143
+ "octa_enface",
144
+ "en_face_projection",
145
+ _posterior_fov(anatomy, "macula"),
146
+ technology or "octa",
147
+ protocol or "en_face_projection",
148
+ )
149
+ if modality == "ir_slo":
150
+ return _tax(
151
+ "scanning_laser_ophthalmoscopy",
152
+ "infrared_slo",
153
+ "en_face_reflectance",
154
+ _posterior_fov(anatomy, "macula"),
155
+ technology or "slo",
156
+ protocol or "single_shot",
157
+ )
158
+ if modality == "slo_gray":
159
+ return _tax(
160
+ "scanning_laser_ophthalmoscopy",
161
+ "reflectance_slo_gray",
162
+ "en_face_reflectance",
163
+ _posterior_fov(anatomy, "macula"),
164
+ technology or "slo",
165
+ protocol or "single_shot",
166
+ )
167
+ if modality == "bscan_us":
168
+ return _tax(
169
+ "ocular_ultrasound",
170
+ "ocular_bscan_ultrasound",
171
+ "bscan",
172
+ "globe",
173
+ technology or "ultrasound",
174
+ protocol or "bscan",
175
+ )
176
+ if modality == "ubm":
177
+ return _tax(
178
+ "ultrasound_biomicroscopy",
179
+ "ubm_anterior_segment",
180
+ "bscan",
181
+ "anterior_segment",
182
+ technology or "ultrasound_biomicroscopy",
183
+ protocol or "bscan",
184
+ )
185
+ if modality == "slit_lamp":
186
+ return _tax(
187
+ "anterior_segment_photography",
188
+ "slit_lamp_anterior_segment",
189
+ "single_shot",
190
+ "anterior_segment",
191
+ technology or "slit_lamp",
192
+ protocol or "single_shot",
193
+ )
194
+ return _tax("unknown", modality or "unknown", protocol or "unknown", anatomy or "unknown", technology, protocol)
195
+
196
+
197
+ def base_phrase(row: dict[str, Any], taxonomy: dict[str, str] | None = None) -> str:
198
+ taxonomy = taxonomy or derive_taxonomy(row)
199
+ subtype = taxonomy["modality_subtype"]
200
+ if subtype == "external_anterior_segment_photo":
201
+ return "anterior segment photograph"
202
+ if subtype == "standard_color_fundus":
203
+ return "color fundus photograph"
204
+ if subtype == "uwf_color_fundus":
205
+ return "ultra-widefield color fundus photograph"
206
+ if subtype == "fundus_fluorescein_angiography":
207
+ return "fundus fluorescein angiography image"
208
+ if subtype == "oct_bscan":
209
+ return "structural OCT B-scan"
210
+ if subtype == "oct_enface":
211
+ return "structural OCT en face projection"
212
+ if subtype == "octa_enface":
213
+ return "OCT angiography en face image"
214
+ if subtype == "infrared_slo":
215
+ return "infrared scanning laser ophthalmoscopy image"
216
+ if subtype == "reflectance_slo_gray":
217
+ return "scanning laser ophthalmoscopy reflectance image"
218
+ if subtype == "ocular_bscan_ultrasound":
219
+ return "ocular B-scan ultrasound image"
220
+ if subtype == "ubm_anterior_segment":
221
+ return "ultrasound biomicroscopy image"
222
+ if subtype == "slit_lamp_anterior_segment":
223
+ return "slit-lamp anterior segment photograph"
224
+ return f"{_clean(row.get('modality')).replace('_', ' ')} ophthalmic image".strip()
225
+
226
+
227
+ def rewrite_prompt(old_prompt: Any, level: str, phrase: str) -> str:
228
+ phrase = _squash(phrase)
229
+ if level == "short":
230
+ return phrase
231
+ descriptor = strip_old_prefix(old_prompt)
232
+ if not descriptor:
233
+ return phrase
234
+ if descriptor.lower() == phrase.lower():
235
+ return phrase
236
+ if descriptor.lower().startswith(phrase.lower() + ","):
237
+ return _squash(descriptor)
238
+ return _squash(f"{phrase}, {descriptor}")
239
+
240
+
241
+ def strip_old_prefix(text: Any) -> str:
242
+ text = _squash(_clean(text))
243
+ if not text:
244
+ return ""
245
+ for prefix in OLD_PROMPT_PREFIXES:
246
+ match = re.match(rf"^{re.escape(prefix)}(?:\s*[,,]\s*|\s*$)", text, flags=re.I)
247
+ if match:
248
+ return _squash(text[match.end() :])
249
+ return text
250
+
251
+
252
+ def add_taxonomy_columns(frame):
253
+ import pandas as pd
254
+
255
+ out = frame.copy()
256
+ for col in NEW_COLUMNS:
257
+ if col in out.columns:
258
+ out = out.drop(columns=[col])
259
+
260
+ out["taxonomy_version"] = "mixed_v5_taxonomy_20260706"
261
+ out["modality_family"] = "unknown"
262
+ out["modality_subtype"] = out["modality"].fillna("unknown").astype(str)
263
+ out["view_or_projection"] = "unknown"
264
+ out["field_of_view"] = out.get("anatomy", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
265
+ dev = out.get("device_technology", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
266
+ proto = out.get("scan_protocol", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
267
+ out["device_or_acquisition_protocol"] = dev + "/" + proto
268
+ out["prompt_modality_phrase"] = "ophthalmic image"
269
+
270
+ def set_mask(mask, family, subtype, view, fov, phrase):
271
+ out.loc[mask, "modality_family"] = family
272
+ out.loc[mask, "modality_subtype"] = subtype
273
+ out.loc[mask, "view_or_projection"] = view
274
+ out.loc[mask, "field_of_view"] = fov
275
+ out.loc[mask, "prompt_modality_phrase"] = phrase
276
+
277
+ mod = out["modality"].fillna("").astype(str)
278
+ anatomy = out.get("anatomy", pd.Series("", index=out.index)).fillna("").astype(str)
279
+ technology = out.get("device_technology", pd.Series("", index=out.index)).fillna("").astype(str)
280
+ protocol = out.get("scan_protocol", pd.Series("", index=out.index)).fillna("").astype(str)
281
+
282
+ anterior_fundus = mod.eq("fundus_color") & (
283
+ anatomy.eq("anterior_segment") | technology.eq("external_photography")
284
+ )
285
+ set_mask(anterior_fundus, "anterior_segment_photography", "external_anterior_segment_photo", "single_shot", "anterior_segment", "anterior segment photograph")
286
+ set_mask(mod.eq("fundus_color") & ~anterior_fundus, "color_fundus_photography", "standard_color_fundus", "single_shot", "standard", "color fundus photograph")
287
+ set_mask(mod.eq("uwf"), "color_fundus_photography", "uwf_color_fundus", "single_shot", "ultra_widefield", "ultra-widefield color fundus photograph")
288
+ set_mask(mod.eq("ffa"), "fluorescein_angiography", "fundus_fluorescein_angiography", "angiography", "standard", "fundus fluorescein angiography image")
289
+ set_mask(mod.eq("oct_bscan"), "structural_oct", "oct_bscan", "bscan", "macula", "structural OCT B-scan")
290
+ set_mask(mod.eq("oct_enface"), "structural_oct", "oct_enface", "en_face_projection", "macula", "structural OCT en face projection")
291
+ set_mask(mod.isin(["octa", "octa_enface"]), "oct_angiography", "octa_enface", "en_face_projection", "macula", "OCT angiography en face image")
292
+ set_mask(mod.eq("slo_gray"), "scanning_laser_ophthalmoscopy", "reflectance_slo_gray", "en_face_reflectance", "macula", "scanning laser ophthalmoscopy reflectance image")
293
+ set_mask(mod.eq("ir_slo"), "scanning_laser_ophthalmoscopy", "infrared_slo", "en_face_reflectance", "macula", "infrared scanning laser ophthalmoscopy image")
294
+ set_mask(mod.eq("bscan_us"), "ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe", "ocular B-scan ultrasound image")
295
+ set_mask(mod.eq("ubm"), "ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment", "ultrasound biomicroscopy image")
296
+ set_mask(mod.eq("slit_lamp"), "anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment", "slit-lamp anterior segment photograph")
297
+
298
+ optic = anatomy.eq("optic_disc")
299
+ out.loc[optic & mod.eq("oct_bscan"), "field_of_view"] = "optic_disc"
300
+ out.loc[optic & mod.eq("slo_gray"), "field_of_view"] = "optic_disc"
301
+ wide = anatomy.eq("wide-field") | protocol.str.contains("wide", case=False, na=False) | mod.eq("uwf")
302
+ out.loc[wide, "field_of_view"] = "ultra_widefield"
303
+ return out
304
+
305
+
306
+ def build_captions(manifest, old_captions, out_path: Path, chunk_size: int) -> int:
307
+ import pandas as pd
308
+ import pyarrow as pa
309
+ import pyarrow.parquet as pq
310
+
311
+ caps = old_captions[["image_id", "level", "prompt_text"]].copy()
312
+ caps["image_id"] = caps["image_id"].astype(str)
313
+ caps = caps.drop_duplicates(["image_id", "level"], keep="first")
314
+ wide = caps.pivot(index="image_id", columns="level", values="prompt_text")
315
+
316
+ ids = manifest["image_id"].astype(str).reset_index(drop=True)
317
+ phrases = manifest["prompt_modality_phrase"].astype(str).reset_index(drop=True)
318
+ old_short = wide["short"].reindex(ids).reset_index(drop=True) if "short" in wide else pd.Series([None] * len(ids))
319
+ old_medium = wide["medium"].reindex(ids).reset_index(drop=True) if "medium" in wide else pd.Series([None] * len(ids))
320
+ old_dense = wide["dense"].reindex(ids).reset_index(drop=True) if "dense" in wide else pd.Series([None] * len(ids))
321
+ source_by_level = {
322
+ "short": old_short,
323
+ "medium": old_medium.combine_first(old_dense).combine_first(old_short),
324
+ "dense": old_dense.combine_first(old_medium).combine_first(old_short),
325
+ }
326
+
327
+ schema = pa.schema(
328
+ [
329
+ ("caption_id", pa.string()),
330
+ ("image_id", pa.string()),
331
+ ("level", pa.string()),
332
+ ("prompt_text", pa.string()),
333
+ ("language", pa.string()),
334
+ ("generator", pa.string()),
335
+ ("grounded_in", pa.string()),
336
+ ]
337
+ )
338
+ if out_path.exists():
339
+ out_path.unlink()
340
+ writer = pq.ParquetWriter(out_path, schema, compression="zstd")
341
+ total = 0
342
+ try:
343
+ for start in range(0, len(ids), chunk_size):
344
+ end = min(start + chunk_size, len(ids))
345
+ frames = []
346
+ phrase_chunk = phrases.iloc[start:end].tolist()
347
+ id_chunk = ids.iloc[start:end].tolist()
348
+ for level in ["short", "medium", "dense"]:
349
+ old_chunk = source_by_level[level].iloc[start:end].tolist()
350
+ prompt_text = [
351
+ rewrite_prompt(old, level, phrase)
352
+ for old, phrase in zip(old_chunk, phrase_chunk, strict=True)
353
+ ]
354
+ frames.append(
355
+ pd.DataFrame(
356
+ {
357
+ "caption_id": [f"{image_id}_{level}" for image_id in id_chunk],
358
+ "image_id": id_chunk,
359
+ "level": level,
360
+ "prompt_text": prompt_text,
361
+ "language": "en",
362
+ "generator": "mixed_prompt_adapter_v5_taxonomy",
363
+ "grounded_in": "v5_taxonomy+v4_clean_prompt_descriptors",
364
+ }
365
+ )
366
+ )
367
+ table = pa.Table.from_pandas(pd.concat(frames, ignore_index=True), schema=schema, preserve_index=False)
368
+ writer.write_table(table)
369
+ total += table.num_rows
370
+ print(f"captions={total}", flush=True)
371
+ finally:
372
+ writer.close()
373
+ return total
374
+
375
+
376
+ def write_readme(out: Path, manifest_rows: int, caption_rows: int) -> None:
377
+ text = f"""# Mixed Prompt Adapter v5
378
+
379
+ Rows: {manifest_rows}
380
+ Caption rows: {caption_rows}
381
+
382
+ v5 keeps image paths and raw `modality` labels from v4, then adds:
383
+
384
+ - `modality_family`
385
+ - `modality_subtype`
386
+ - `view_or_projection`
387
+ - `field_of_view`
388
+ - `device_or_acquisition_protocol`
389
+ - `prompt_modality_phrase`
390
+
391
+ Design:
392
+
393
+ - UWF is represented as a color fundus photography variant with
394
+ `field_of_view=ultra_widefield`, not as an unrelated independent modality.
395
+ - OCT B-scan and OCT en-face are structural OCT views/projections.
396
+ - OCTA en-face is an OCT angiography en-face image.
397
+ - SLO gray and IR-SLO are scanning-laser-ophthalmoscopy reflectance variants.
398
+ - Ocular B-scan ultrasound and UBM remain separate ultrasound-family subtypes
399
+ because they image different anatomical regions at different frequencies.
400
+ - Anterior-segment external photographs previously carried under
401
+ `fundus_color/anterior_segment` are prompted as anterior segment photographs.
402
+
403
+ Prompt policy:
404
+
405
+ - `short`: v5 modality phrase only.
406
+ - `medium` and `dense`: v5 modality phrase plus the already-cleaned v4 prompt
407
+ descriptors, with only the modality prefix rewritten.
408
+ - No raw Chinese report text or new image-derived labels are introduced here.
409
+ """
410
+ (out / "README.md").write_text(text, encoding="utf-8")
411
+
412
+
413
+ def write_summary(out: Path, manifest, caption_rows: int) -> None:
414
+ summary = {
415
+ "rows": int(len(manifest)),
416
+ "captions": int(caption_rows),
417
+ "by_modality": manifest.groupby("modality").size().astype(int).to_dict(),
418
+ "by_modality_family": manifest.groupby("modality_family").size().astype(int).to_dict(),
419
+ "by_modality_subtype": manifest.groupby("modality_subtype").size().astype(int).to_dict(),
420
+ "by_family_subtype": {
421
+ f"{family}/{subtype}": int(n)
422
+ for (family, subtype), n in manifest.groupby(["modality_family", "modality_subtype"]).size().items()
423
+ },
424
+ }
425
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
426
+
427
+
428
+ def main() -> None:
429
+ import pandas as pd
430
+
431
+ args = parse_args()
432
+ args.out.mkdir(parents=True, exist_ok=True)
433
+ manifest_in = args.input / "adapter_manifest_mixed_v4.parquet"
434
+ captions_in = args.input / "captions_v2.parquet"
435
+ manifest_out = args.out / "adapter_manifest_mixed_v5.parquet"
436
+ captions_out = args.out / "captions_v2.parquet"
437
+
438
+ if not args.overwrite:
439
+ for path in [manifest_out, captions_out]:
440
+ if path.exists():
441
+ raise FileExistsError(f"{path} exists; pass --overwrite")
442
+
443
+ manifest = pd.read_parquet(manifest_in)
444
+ if args.limit:
445
+ manifest = manifest.head(args.limit).copy()
446
+ manifest = add_taxonomy_columns(manifest)
447
+ manifest.to_parquet(manifest_out, index=False, compression="zstd")
448
+
449
+ captions = pd.read_parquet(captions_in, columns=["image_id", "level", "prompt_text"])
450
+ caption_rows = build_captions(manifest, captions, captions_out, args.chunk_size)
451
+ write_summary(args.out, manifest, caption_rows)
452
+ write_readme(args.out, len(manifest), caption_rows)
453
+ print(json.dumps({"out": str(args.out), "rows": len(manifest), "captions": caption_rows}, ensure_ascii=False))
454
+
455
+
456
+ def parse_args() -> argparse.Namespace:
457
+ parser = argparse.ArgumentParser()
458
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
459
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
460
+ parser.add_argument("--chunk-size", type=int, default=250_000)
461
+ parser.add_argument("--limit", type=int, default=None)
462
+ parser.add_argument("--overwrite", action="store_true")
463
+ return parser.parse_args()
464
+
465
+
466
+ def _tax(family: str, subtype: str, view: str, fov: str, technology: str, protocol: str) -> dict[str, str]:
467
+ return {
468
+ "taxonomy_version": "mixed_v5_taxonomy_20260706",
469
+ "modality_family": family,
470
+ "modality_subtype": subtype,
471
+ "view_or_projection": view,
472
+ "field_of_view": fov,
473
+ "device_or_acquisition_protocol": f"{technology or 'unknown'}/{protocol or 'unknown'}",
474
+ }
475
+
476
+
477
+ def _posterior_fov(anatomy: str, default: str) -> str:
478
+ if anatomy == "optic_disc":
479
+ return "optic_disc"
480
+ if anatomy in {"wide-field", "widefield"}:
481
+ return "ultra_widefield"
482
+ if anatomy in {"macula", "retina"}:
483
+ return "macula" if anatomy == "macula" else default
484
+ return default
485
+
486
+
487
+ def _clean(value: Any) -> str:
488
+ if value is None:
489
+ return ""
490
+ if isinstance(value, float) and math.isnan(value):
491
+ return ""
492
+ return str(value).strip()
493
+
494
+
495
+ def _squash(text: str) -> str:
496
+ text = re.sub(r"\s+", " ", text)
497
+ text = re.sub(r"\s*[,,]\s*", ", ", text)
498
+ return text.strip(" ,,")
499
+
500
+
501
+ if __name__ == "__main__":
502
+ main()
data_processing/05_taxonomy_and_prompts/build_mixed_v6_taxonomy.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): build_mixed_v6_taxonomy.py
4
+ 原本用途 (Original Purpose):
5
+ 对齐国际 ICD-10 与 SNOMED 编码标准的 95 种眼病分级多中心分类学(Taxonomy)构建器,生成 tongren95_taxonomy.csv 标准词典,实现非标准中文病名到规范英文概念与病种家族的自动映射。
6
+ 适用数据集 (Target Dataset):
7
+ 全库 95 类眼科疾病标准化临床分类。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 各中心历史病历诊断频数表与眼科学专业诊断术语表
12
+ 输出结果 (Output):
13
+ tongren95_taxonomy.csv(包含 raw_zh, canonical_en, family_en, icd_code 等)
14
+ 依赖环境 (Dependencies):
15
+ pandas, pyarrow, csv
16
+ ================================================================================
17
+ """
18
+
19
+ """Build mixed v6 prompt/taxonomy artifacts from the mixed v5 artifacts.
20
+
21
+ v6 keeps image routing unchanged, but makes prompt conditioning hierarchical:
22
+ modality family + view/projection + field of view/anatomy. It also folds the
23
+ tiny IR-SLO split into the reflectance SLO subtype and removes dataset split
24
+ tokens from diagnosis descriptors before they can enter prompts.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import json
31
+ import math
32
+ import re
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ from build_mixed_v5_taxonomy import OLD_PROMPT_PREFIXES, strip_old_prefix
37
+
38
+
39
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v5")
40
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6")
41
+ VERSION = "mixed_v6_hierarchical_taxonomy_20260707"
42
+ SPLIT_TOKENS = {"train", "test", "val", "valid", "validation", "eryuan"}
43
+ V6_EXTRA_OLD_PROMPT_PREFIXES = [
44
+ "infrared scanning laser ophthalmoscopy image",
45
+ "scanning laser ophthalmoscopy reflectance image",
46
+ ]
47
+
48
+
49
+ def derive_taxonomy(row: dict[str, Any]) -> dict[str, str]:
50
+ modality = _clean(row.get("modality")).lower()
51
+ anatomy = _clean(row.get("anatomy")).lower()
52
+ technology = _clean(row.get("device_technology")).lower()
53
+ protocol = _clean(row.get("scan_protocol")).lower()
54
+
55
+ if modality == "fundus_color" and (
56
+ anatomy == "anterior_segment" or technology == "external_photography"
57
+ ):
58
+ return _tax(
59
+ "anterior_segment_photography",
60
+ "external_anterior_segment_photo",
61
+ "single_shot",
62
+ "anterior_segment",
63
+ technology,
64
+ protocol,
65
+ )
66
+ if modality == "fundus_color":
67
+ return _tax(
68
+ "color_fundus_photography",
69
+ "standard_color_fundus",
70
+ "single_shot",
71
+ _posterior_fov(anatomy, "standard"),
72
+ technology,
73
+ protocol,
74
+ )
75
+ if modality == "uwf":
76
+ return _tax(
77
+ "color_fundus_photography",
78
+ "uwf_color_fundus",
79
+ "single_shot",
80
+ "ultra_widefield",
81
+ technology or "fundus_camera",
82
+ protocol or "widefield",
83
+ )
84
+ if modality == "ffa":
85
+ return _tax(
86
+ "fluorescein_angiography",
87
+ "fundus_fluorescein_angiography",
88
+ "angiography",
89
+ _posterior_fov(anatomy, "standard"),
90
+ technology or "fluorescein_angiography",
91
+ protocol or "angiography",
92
+ )
93
+ if modality == "oct_bscan":
94
+ return _tax("structural_oct", "oct_bscan", "bscan", _posterior_fov(anatomy, "macula"), technology or "oct", protocol or "bscan")
95
+ if modality == "oct_enface":
96
+ return _tax("structural_oct", "oct_enface", "en_face_projection", _posterior_fov(anatomy, "macula"), technology or "oct", protocol or "en_face_projection")
97
+ if modality in {"octa", "octa_enface"}:
98
+ return _tax("oct_angiography", "octa_enface", "en_face_projection", _posterior_fov(anatomy, "macula"), technology or "octa", protocol or "en_face_projection")
99
+ if modality in {"slo_gray", "ir_slo"}:
100
+ return _tax(
101
+ "scanning_laser_ophthalmoscopy",
102
+ "reflectance_slo_gray",
103
+ "en_face_reflectance",
104
+ _posterior_fov(anatomy, "macula"),
105
+ technology or "slo",
106
+ protocol or ("infrared" if modality == "ir_slo" else "single_shot"),
107
+ )
108
+ if modality == "bscan_us":
109
+ return _tax("ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe", technology or "ultrasound", protocol or "bscan")
110
+ if modality == "ubm":
111
+ return _tax("ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment", technology or "ultrasound_biomicroscopy", protocol or "bscan")
112
+ if modality == "slit_lamp":
113
+ return _tax("anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment", technology or "slit_lamp", protocol or "single_shot")
114
+ return _tax("unknown", modality or "unknown", protocol or "unknown", anatomy or "unknown", technology, protocol)
115
+
116
+
117
+ def hierarchical_phrase(taxonomy: dict[str, str]) -> str:
118
+ subtype = taxonomy["modality_subtype"]
119
+ fov = taxonomy.get("field_of_view", "unknown")
120
+ if subtype == "standard_color_fundus":
121
+ return _join_prompt_parts("ophthalmic image", "color fundus photography", f"{_fov_text(fov)} field of view", "retina")
122
+ if subtype == "uwf_color_fundus":
123
+ return _join_prompt_parts("ophthalmic image", "color fundus photography", "ultra-widefield view", "retina")
124
+ if subtype == "fundus_fluorescein_angiography":
125
+ return _join_prompt_parts("ophthalmic image", "fundus fluorescein angiography", _fov_text(fov), "retina")
126
+ if subtype == "oct_bscan":
127
+ return _join_prompt_parts("ophthalmic image", "structural OCT", "B-scan view", _fov_text(fov))
128
+ if subtype == "oct_enface":
129
+ return _join_prompt_parts("ophthalmic image", "structural OCT", "en face projection", _fov_text(fov))
130
+ if subtype == "octa_enface":
131
+ return _join_prompt_parts("ophthalmic image", "OCT angiography", "en face projection", _fov_text(fov))
132
+ if subtype == "reflectance_slo_gray":
133
+ return _join_prompt_parts("ophthalmic image", "scanning laser ophthalmoscopy", "reflectance en face view", _fov_text(fov))
134
+ if subtype == "ocular_bscan_ultrasound":
135
+ return _join_prompt_parts("ophthalmic image", "ocular ultrasound", "B-scan view", "globe")
136
+ if subtype == "ubm_anterior_segment":
137
+ return _join_prompt_parts("ophthalmic image", "ultrasound biomicroscopy", "anterior segment", "B-scan view")
138
+ if subtype == "external_anterior_segment_photo":
139
+ return _join_prompt_parts("ophthalmic image", "anterior segment photography", "external photograph")
140
+ if subtype == "slit_lamp_anterior_segment":
141
+ return _join_prompt_parts("ophthalmic image", "slit-lamp anterior segment photography")
142
+ return _join_prompt_parts("ophthalmic image", taxonomy.get("modality_family", "unknown"))
143
+
144
+
145
+ def clean_diagnosis_group(value: Any) -> list[str]:
146
+ if value is None:
147
+ return []
148
+ if isinstance(value, float) and math.isnan(value):
149
+ return []
150
+ if isinstance(value, (list, tuple)):
151
+ tokens = [str(v) for v in value]
152
+ else:
153
+ text = _clean(value)
154
+ if not text or text in {"[]", "None", "nan", "<NA>"}:
155
+ return []
156
+ tokens = re.findall(r"'([^']+)'", text)
157
+ if not tokens:
158
+ tokens = re.split(r"[;,|]", text.strip("[]"))
159
+ cleaned: list[str] = []
160
+ seen: set[str] = set()
161
+ for token in tokens:
162
+ label = _squash(str(token).strip(" \"'[]"))
163
+ if not label:
164
+ continue
165
+ if label.lower() in SPLIT_TOKENS:
166
+ continue
167
+ if label.lower() in seen:
168
+ continue
169
+ seen.add(label.lower())
170
+ cleaned.append(label)
171
+ return cleaned
172
+
173
+
174
+ def rewrite_prompt(old_prompt: Any, level: str, taxonomy: dict[str, str], diagnosis: Any = None) -> str:
175
+ phrase = hierarchical_phrase(taxonomy)
176
+ if level == "short":
177
+ return phrase
178
+ descriptor = clean_prompt_descriptor(strip_old_prefix(old_prompt))
179
+ diagnosis_text = diagnosis_phrase(diagnosis)
180
+ extras = []
181
+ if diagnosis_text and diagnosis_text.lower() not in descriptor.lower():
182
+ extras.append(diagnosis_text)
183
+ if descriptor:
184
+ extras.append(descriptor)
185
+ return _squash(", ".join([phrase, *extras]))
186
+
187
+
188
+ def diagnosis_phrase(value: Any) -> str:
189
+ labels = clean_diagnosis_group(value)
190
+ if not labels:
191
+ return ""
192
+ return "diagnosis: " + "; ".join(labels)
193
+
194
+
195
+ def clean_prompt_descriptor(text: Any) -> str:
196
+ text = _squash(_clean(text))
197
+ if not text:
198
+ return ""
199
+ for prefix in [*V6_EXTRA_OLD_PROMPT_PREFIXES, *OLD_PROMPT_PREFIXES]:
200
+ text = re.sub(rf"^{re.escape(prefix)}(?:\s*[,,]\s*|\s*$)", "", text, flags=re.I)
201
+ parts = []
202
+ for part in re.split(r"[,,;|]+", text):
203
+ part = _squash(part)
204
+ if not part:
205
+ continue
206
+ if part.lower() in SPLIT_TOKENS:
207
+ continue
208
+ part = re.sub(r"\b(?:train|test|val|valid|validation|eryuan)\b", "", part, flags=re.I)
209
+ part = _squash(part.strip(" ,;"))
210
+ if part:
211
+ parts.append(part)
212
+ return _squash(", ".join(dict.fromkeys(parts)))
213
+
214
+
215
+ def add_v6_columns(frame):
216
+ import pandas as pd
217
+
218
+ out = frame.copy()
219
+ for col in [
220
+ "taxonomy_version",
221
+ "modality_family",
222
+ "modality_subtype",
223
+ "view_or_projection",
224
+ "field_of_view",
225
+ "device_or_acquisition_protocol",
226
+ "prompt_modality_phrase",
227
+ "diagnosis_group_clean",
228
+ "subtype_sample_status",
229
+ ]:
230
+ if col in out.columns:
231
+ out = out.drop(columns=[col])
232
+
233
+ out["taxonomy_version"] = VERSION
234
+ out["modality_family"] = "unknown"
235
+ out["modality_subtype"] = out["modality"].fillna("unknown").astype(str)
236
+ out["view_or_projection"] = "unknown"
237
+ out["field_of_view"] = out.get("anatomy", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
238
+ dev = out.get("device_technology", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
239
+ proto = out.get("scan_protocol", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
240
+ out["device_or_acquisition_protocol"] = dev + "/" + proto
241
+
242
+ def set_mask(mask, family, subtype, view, fov):
243
+ out.loc[mask, "modality_family"] = family
244
+ out.loc[mask, "modality_subtype"] = subtype
245
+ out.loc[mask, "view_or_projection"] = view
246
+ out.loc[mask, "field_of_view"] = fov
247
+
248
+ mod = out["modality"].fillna("").astype(str)
249
+ anatomy = out.get("anatomy", pd.Series("", index=out.index)).fillna("").astype(str)
250
+ technology = out.get("device_technology", pd.Series("", index=out.index)).fillna("").astype(str)
251
+ protocol = out.get("scan_protocol", pd.Series("", index=out.index)).fillna("").astype(str)
252
+
253
+ anterior_fundus = mod.eq("fundus_color") & (
254
+ anatomy.eq("anterior_segment") | technology.eq("external_photography")
255
+ )
256
+ set_mask(anterior_fundus, "anterior_segment_photography", "external_anterior_segment_photo", "single_shot", "anterior_segment")
257
+ set_mask(mod.eq("fundus_color") & ~anterior_fundus, "color_fundus_photography", "standard_color_fundus", "single_shot", "standard")
258
+ set_mask(mod.eq("uwf"), "color_fundus_photography", "uwf_color_fundus", "single_shot", "ultra_widefield")
259
+ set_mask(mod.eq("ffa"), "fluorescein_angiography", "fundus_fluorescein_angiography", "angiography", "standard")
260
+ set_mask(mod.eq("oct_bscan"), "structural_oct", "oct_bscan", "bscan", "macula")
261
+ set_mask(mod.eq("oct_enface"), "structural_oct", "oct_enface", "en_face_projection", "macula")
262
+ set_mask(mod.isin(["octa", "octa_enface"]), "oct_angiography", "octa_enface", "en_face_projection", "macula")
263
+ set_mask(mod.isin(["slo_gray", "ir_slo"]), "scanning_laser_ophthalmoscopy", "reflectance_slo_gray", "en_face_reflectance", "macula")
264
+ set_mask(mod.eq("bscan_us"), "ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe")
265
+ set_mask(mod.eq("ubm"), "ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment")
266
+ set_mask(mod.eq("slit_lamp"), "anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment")
267
+
268
+ optic = anatomy.eq("optic_disc")
269
+ out.loc[optic & mod.eq("oct_bscan"), "field_of_view"] = "optic_disc"
270
+ out.loc[optic & mod.isin(["slo_gray", "ir_slo"]), "field_of_view"] = "optic_disc"
271
+ wide = anatomy.eq("wide-field") | protocol.str.contains("wide", case=False, na=False) | mod.eq("uwf")
272
+ out.loc[wide, "field_of_view"] = "ultra_widefield"
273
+
274
+ tax_cols = out[["modality_family", "modality_subtype", "view_or_projection", "field_of_view"]]
275
+ out["prompt_modality_phrase"] = [
276
+ hierarchical_phrase(row)
277
+ for row in tax_cols.to_dict("records")
278
+ ]
279
+ diag = out.get("diagnosis_group", pd.Series([None] * len(out), index=out.index))
280
+ out["diagnosis_group_clean"] = ["; ".join(clean_diagnosis_group(v)) for v in diag]
281
+ counts = out["modality_subtype"].value_counts()
282
+ out["subtype_sample_status"] = out["modality_subtype"].map(
283
+ lambda s: "formal" if counts.get(s, 0) >= 2000 else ("supplemental" if counts.get(s, 0) >= 500 else "tiny")
284
+ )
285
+ return out
286
+
287
+
288
+ def build_captions(manifest, old_captions, out_path: Path, chunk_size: int) -> int:
289
+ import pandas as pd
290
+ import pyarrow as pa
291
+ import pyarrow.parquet as pq
292
+
293
+ caps = old_captions[["image_id", "level", "prompt_text"]].copy()
294
+ caps["image_id"] = caps["image_id"].astype(str)
295
+ caps = caps.drop_duplicates(["image_id", "level"], keep="first")
296
+ wide = caps.pivot(index="image_id", columns="level", values="prompt_text")
297
+
298
+ ids = manifest["image_id"].astype(str).reset_index(drop=True)
299
+ tax_records = manifest[
300
+ ["modality_family", "modality_subtype", "view_or_projection", "field_of_view"]
301
+ ].to_dict("records")
302
+ diagnoses = manifest["diagnosis_group_clean"].astype(str).replace("nan", "").reset_index(drop=True)
303
+ old_short = wide["short"].reindex(ids).reset_index(drop=True) if "short" in wide else pd.Series([None] * len(ids))
304
+ old_medium = wide["medium"].reindex(ids).reset_index(drop=True) if "medium" in wide else pd.Series([None] * len(ids))
305
+ old_dense = wide["dense"].reindex(ids).reset_index(drop=True) if "dense" in wide else pd.Series([None] * len(ids))
306
+ source_by_level = {
307
+ "short": old_short,
308
+ "medium": old_medium.combine_first(old_dense).combine_first(old_short),
309
+ "dense": old_dense.combine_first(old_medium).combine_first(old_short),
310
+ }
311
+
312
+ schema = pa.schema(
313
+ [
314
+ ("caption_id", pa.string()),
315
+ ("image_id", pa.string()),
316
+ ("level", pa.string()),
317
+ ("prompt_text", pa.string()),
318
+ ("language", pa.string()),
319
+ ("generator", pa.string()),
320
+ ("grounded_in", pa.string()),
321
+ ]
322
+ )
323
+ if out_path.exists():
324
+ out_path.unlink()
325
+ writer = pq.ParquetWriter(out_path, schema, compression="zstd")
326
+ total = 0
327
+ try:
328
+ for start in range(0, len(ids), chunk_size):
329
+ end = min(start + chunk_size, len(ids))
330
+ frames = []
331
+ id_chunk = ids.iloc[start:end].tolist()
332
+ tax_chunk = tax_records[start:end]
333
+ diag_chunk = diagnoses.iloc[start:end].tolist()
334
+ for level in ["short", "medium", "dense"]:
335
+ old_chunk = source_by_level[level].iloc[start:end].tolist()
336
+ prompt_text = [
337
+ rewrite_prompt(old, level, tax, diag)
338
+ for old, tax, diag in zip(old_chunk, tax_chunk, diag_chunk, strict=True)
339
+ ]
340
+ frames.append(
341
+ pd.DataFrame(
342
+ {
343
+ "caption_id": [f"{image_id}_{level}" for image_id in id_chunk],
344
+ "image_id": id_chunk,
345
+ "level": level,
346
+ "prompt_text": prompt_text,
347
+ "language": "en",
348
+ "generator": "mixed_prompt_adapter_v6_hierarchical_taxonomy",
349
+ "grounded_in": "v6_taxonomy+clean_diagnosis+v5_descriptors",
350
+ }
351
+ )
352
+ )
353
+ table = pa.Table.from_pandas(pd.concat(frames, ignore_index=True), schema=schema, preserve_index=False)
354
+ writer.write_table(table)
355
+ total += table.num_rows
356
+ print(f"captions={total}", flush=True)
357
+ finally:
358
+ writer.close()
359
+ return total
360
+
361
+
362
+ def write_summary(out: Path, manifest, caption_rows: int) -> None:
363
+ summary = {
364
+ "rows": int(len(manifest)),
365
+ "captions": int(caption_rows),
366
+ "taxonomy_version": VERSION,
367
+ "by_modality": manifest.groupby("modality").size().astype(int).to_dict(),
368
+ "by_modality_family": manifest.groupby("modality_family").size().astype(int).to_dict(),
369
+ "by_modality_subtype": manifest.groupby("modality_subtype").size().astype(int).to_dict(),
370
+ "by_subtype_sample_status": manifest.groupby("subtype_sample_status").size().astype(int).to_dict(),
371
+ }
372
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
373
+
374
+
375
+ def write_readme(out: Path, manifest_rows: int, caption_rows: int) -> None:
376
+ text = f"""# Mixed Prompt Adapter v6
377
+
378
+ Rows: {manifest_rows}
379
+ Caption rows: {caption_rows}
380
+
381
+ Changes from v5:
382
+
383
+ - Prompt prefixes are hierarchical: modality family + view/projection +
384
+ field-of-view/anatomy.
385
+ - `ir_slo` rows are folded into `reflectance_slo_gray`; 42 images are too few
386
+ for an independent subtype.
387
+ - `diagnosis_group_clean` removes dataset split/source tokens such as
388
+ `train`, `test`, `val`, and `eryuan`.
389
+ - `subtype_sample_status` marks formal/supplemental/tiny groups for reporting.
390
+
391
+ Prompt policy:
392
+
393
+ - `short`: imaging condition only.
394
+ - `medium` and `dense`: imaging condition plus cleaned diagnosis and existing
395
+ cleaned descriptors.
396
+ """
397
+ (out / "README.md").write_text(text, encoding="utf-8")
398
+
399
+
400
+ def main() -> None:
401
+ import pandas as pd
402
+
403
+ args = parse_args()
404
+ args.out.mkdir(parents=True, exist_ok=True)
405
+ manifest_in = args.input / "adapter_manifest_mixed_v5.parquet"
406
+ captions_in = args.input / "captions_v2.parquet"
407
+ manifest_out = args.out / "adapter_manifest_mixed_v6.parquet"
408
+ captions_out = args.out / "captions_v2.parquet"
409
+
410
+ if not args.overwrite:
411
+ for path in [manifest_out, captions_out]:
412
+ if path.exists():
413
+ raise FileExistsError(f"{path} exists; pass --overwrite")
414
+
415
+ manifest = pd.read_parquet(manifest_in)
416
+ if args.limit:
417
+ manifest = manifest.head(args.limit).copy()
418
+ manifest = add_v6_columns(manifest)
419
+ manifest.to_parquet(manifest_out, index=False, compression="zstd")
420
+
421
+ captions = pd.read_parquet(captions_in, columns=["image_id", "level", "prompt_text"])
422
+ caption_rows = build_captions(manifest, captions, captions_out, args.chunk_size)
423
+ write_summary(args.out, manifest, caption_rows)
424
+ write_readme(args.out, len(manifest), caption_rows)
425
+ print(json.dumps({"out": str(args.out), "rows": len(manifest), "captions": caption_rows}, ensure_ascii=False))
426
+
427
+
428
+ def parse_args() -> argparse.Namespace:
429
+ parser = argparse.ArgumentParser()
430
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
431
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
432
+ parser.add_argument("--chunk-size", type=int, default=250_000)
433
+ parser.add_argument("--limit", type=int, default=None)
434
+ parser.add_argument("--overwrite", action="store_true")
435
+ return parser.parse_args()
436
+
437
+
438
+ def _tax(family: str, subtype: str, view: str, fov: str, technology: str, protocol: str) -> dict[str, str]:
439
+ return {
440
+ "taxonomy_version": VERSION,
441
+ "modality_family": family,
442
+ "modality_subtype": subtype,
443
+ "view_or_projection": view,
444
+ "field_of_view": fov,
445
+ "device_or_acquisition_protocol": f"{technology or 'unknown'}/{protocol or 'unknown'}",
446
+ "prompt_modality_phrase": "",
447
+ }
448
+
449
+
450
+ def _posterior_fov(anatomy: str, default: str) -> str:
451
+ if anatomy == "optic_disc":
452
+ return "optic_disc"
453
+ if anatomy in {"wide-field", "widefield", "ultra_widefield"}:
454
+ return "ultra_widefield"
455
+ if anatomy == "macula":
456
+ return "macula"
457
+ return default
458
+
459
+
460
+ def _fov_text(value: str) -> str:
461
+ return {
462
+ "standard": "standard",
463
+ "macula": "macula",
464
+ "optic_disc": "optic disc",
465
+ "ultra_widefield": "ultra-widefield",
466
+ "anterior_segment": "anterior segment",
467
+ "globe": "globe",
468
+ }.get(str(value), str(value).replace("_", " "))
469
+
470
+
471
+ def _join_prompt_parts(*parts: str) -> str:
472
+ return _squash(", ".join(part for part in parts if part and part != "unknown"))
473
+
474
+
475
+ def _clean(value: Any) -> str:
476
+ if value is None:
477
+ return ""
478
+ if isinstance(value, float) and math.isnan(value):
479
+ return ""
480
+ return str(value).strip()
481
+
482
+
483
+ def _squash(text: str) -> str:
484
+ return re.sub(r"\s+", " ", str(text).strip())
485
+
486
+
487
+ if __name__ == "__main__":
488
+ main()
data_processing/05_taxonomy_and_prompts/test_build_mixed_v6_taxonomy.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): test_build_mixed_v6_taxonomy.py
4
+ 原本用途 (Original Purpose):
5
+ 分类学层次结构完整性与 ICD 映射无死角测试。确保 95 种眼病每一类别均有且仅有一个主分类归属。
6
+ 适用数据集 (Target Dataset):
7
+ tongren95_taxonomy.csv 标准分类字典。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 构建完成的分类学 CSV 表格
12
+ 输出结果 (Output):
13
+ 单元测试断言通过性报告
14
+ 依赖环境 (Dependencies):
15
+ pytest, pandas
16
+ ================================================================================
17
+ """
18
+
19
+ import sys
20
+ import unittest
21
+ from pathlib import Path
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+
25
+ from build_mixed_v6_taxonomy import (
26
+ clean_diagnosis_group,
27
+ derive_taxonomy,
28
+ rewrite_prompt,
29
+ )
30
+
31
+
32
+ class BuildMixedV6TaxonomyTest(unittest.TestCase):
33
+ def test_ir_slo_is_folded_into_reflectance_slo_not_own_subtype(self):
34
+ tax = derive_taxonomy(
35
+ {
36
+ "modality": "ir_slo",
37
+ "anatomy": "macula",
38
+ "device_technology": "slo",
39
+ "scan_protocol": "infrared",
40
+ }
41
+ )
42
+
43
+ self.assertEqual(tax["modality_family"], "scanning_laser_ophthalmoscopy")
44
+ self.assertEqual(tax["modality_subtype"], "reflectance_slo_gray")
45
+ self.assertEqual(tax["view_or_projection"], "en_face_reflectance")
46
+
47
+ def test_hierarchical_prompt_names_family_view_and_anatomy(self):
48
+ tax = derive_taxonomy(
49
+ {
50
+ "modality": "oct_bscan",
51
+ "anatomy": "macula",
52
+ "device_technology": "sd_oct",
53
+ "scan_protocol": "volume_3d_macula",
54
+ }
55
+ )
56
+
57
+ prompt = rewrite_prompt("OCT B-scan, normal", "short", tax)
58
+
59
+ self.assertIn("ophthalmic image", prompt)
60
+ self.assertIn("structural OCT", prompt)
61
+ self.assertIn("B-scan view", prompt)
62
+ self.assertIn("macula", prompt)
63
+
64
+ def test_split_tokens_are_removed_from_clean_diagnosis_group(self):
65
+ self.assertEqual(
66
+ clean_diagnosis_group("['diabetic retinopathy' 'train']"),
67
+ ["diabetic retinopathy"],
68
+ )
69
+ self.assertEqual(clean_diagnosis_group("['normal' 'eryuan']"), ["normal"])
70
+ self.assertEqual(clean_diagnosis_group("[]"), [])
71
+
72
+ def test_rewrite_prompt_removes_split_tokens_from_descriptor(self):
73
+ tax = derive_taxonomy({"modality": "fundus_color", "anatomy": "retina"})
74
+
75
+ prompt = rewrite_prompt(
76
+ "color fundus photograph, diabetic retinopathy, train",
77
+ "medium",
78
+ tax,
79
+ )
80
+
81
+ self.assertIn("diabetic retinopathy", prompt)
82
+ self.assertNotIn("train", prompt.lower())
83
+
84
+ def test_rewrite_prompt_removes_folded_ir_slo_legacy_prefix(self):
85
+ tax = derive_taxonomy({"modality": "ir_slo", "anatomy": "macula"})
86
+
87
+ prompt = rewrite_prompt(
88
+ "infrared scanning laser ophthalmoscopy image",
89
+ "medium",
90
+ tax,
91
+ )
92
+
93
+ self.assertEqual(
94
+ prompt,
95
+ "ophthalmic image, scanning laser ophthalmoscopy, reflectance en face view, macula",
96
+ )
97
+
98
+
99
+ if __name__ == "__main__":
100
+ unittest.main()
data_processing/05_taxonomy_and_prompts/test_taxonomy_sampling.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================================================================
3
+ 脚本名称 (Script Name): test_taxonomy_sampling.py
4
+ 原本用途 (Original Purpose):
5
+ 疾病类别平衡与分层抽样算法测试套件。验证针对罕见病与常见病的加权采样机制。
6
+ 适用数据集 (Target Dataset):
7
+ 全库长尾分布的多病种诊断数据集。
8
+ 作者与归属 (Author/Provenance):
9
+ 李思成 (Lisicheng), 浙江大学多模态眼科团队
10
+ 输入要求 (Input):
11
+ 样本分布频数表
12
+ 输出结果 (Output):
13
+ 分层抽样平衡度评估指标
14
+ 依赖环境 (Dependencies):
15
+ numpy, pandas
16
+ ================================================================================
17
+ """
18
+
19
+ import sys
20
+ import types
21
+ import unittest
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
27
+
28
+ omegaconf_stub = types.ModuleType("omegaconf")
29
+ omegaconf_stub.OmegaConf = object
30
+ omegaconf_stub.DictConfig = object
31
+ sys.modules.setdefault("omegaconf", omegaconf_stub)
32
+
33
+ data_stub = types.ModuleType("data")
34
+ octflow_stub = types.ModuleType("data.octflow_dataset")
35
+ octflow_stub.OCTFlowDataset = object
36
+ sys.modules.setdefault("data", data_stub)
37
+ sys.modules.setdefault("data.octflow_dataset", octflow_stub)
38
+
39
+ from train_sd3_t2i import build_balanced_sampling_weights
40
+
41
+
42
+ class TaxonomySamplingTest(unittest.TestCase):
43
+ def test_temperature_sampling_gives_each_group_equal_total_weight_at_zero_temperature(self):
44
+ labels = np.array(["fundus"] * 8 + ["ubm"] * 2)
45
+
46
+ weights, counts, targets = build_balanced_sampling_weights(
47
+ labels,
48
+ temperature=0.0,
49
+ min_count=1,
50
+ )
51
+
52
+ self.assertEqual(counts, {"fundus": 8, "ubm": 2})
53
+ self.assertAlmostEqual(weights[:8].sum(), weights[8:].sum(), places=8)
54
+ self.assertEqual(set(targets), {"fundus", "ubm"})
55
+
56
+ def test_min_count_excludes_tiny_groups(self):
57
+ labels = np.array(["fundus"] * 8 + ["ir_slo"] * 2)
58
+
59
+ weights, counts, targets = build_balanced_sampling_weights(
60
+ labels,
61
+ temperature=0.5,
62
+ min_count=3,
63
+ )
64
+
65
+ self.assertEqual(counts, {"fundus": 8, "ir_slo": 2})
66
+ self.assertGreater(weights[:8].sum(), 0.0)
67
+ self.assertEqual(weights[8:].sum(), 0.0)
68
+ self.assertEqual(targets, {"fundus": 1.0})
69
+
70
+
71
+ if __name__ == "__main__":
72
+ unittest.main()
data_processing/README.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ophthalmic Multimodal Data Processing & Curation Toolkit
2
+
3
+ <div align="center">
4
+
5
+ **Official Data Curation, De-identification, Quality Control & Taxonomy Standardization Pipeline for MM-OphBench**
6
+
7
+ [![Hugging Face Dataset](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Dataset-blue)](https://huggingface.co/datasets/Kaphathy/Dataset)
8
+ [![Toolkit Directory](https://img.shields.io/badge/Directory-data__processing-brightgreen)]()
9
+ [![Contributors](https://img.shields.io/badge/Contributors-Lisicheng%20|%20Zhanghuan%20|%20Huchengwei%20|%20Team-orange)]()
10
+
11
+ </div>
12
+
13
+ ---
14
+
15
+ ## 1. 概述 (Executive Summary)
16
+
17
+ 本目录为 **MM-OphBench** 大规模多中心多模态眼科基准数据集(4,307,415 张图像、7 大临床影像模态)的**官方数据预处理、脱敏、质控与标准化代码库**。
18
+
19
+ 为保证科研复现性与数据工程透明度,本目录将所有曾经用于清洗原始医院数据、公开集裁剪、伪影过滤、Excel 跨表校对、病灶匹配以及疾病分类学构建的生产级代码集中归档。**每一个脚本的文件头均附有详细的中英文注释,严格标明其原本用途、所适用的具体数据集、作者及输入输出规范。**
20
+
21
+ ---
22
+
23
+ ## 2. 目录架构 (Directory Structure)
24
+
25
+ ```text
26
+ data_processing/
27
+ ├── README.md # 本说明指南与全量速查矩阵表
28
+ ├── 01_deidentification/ # 隐私脱敏、视网膜圆剪裁与黑框消除
29
+ │ ├── deidentify_batch.py # [通用眼底大集] 批量多进程几何圆掩模与 OCR 正则脱敏 (李思成)
30
+ │ ├── audit_fundus_corner_pii.py # [全库眼底图] OCR 与角部像素密度 PII 自动化复审 (李思成)
31
+ │ ├── crop_fundus_images.py # [CSDI/公开眼底集] 自动轮廓提取与多余黑边裁剪 (张焕)
32
+ │ ├── deidentify_trial.py # [眼底算法库] Otsu 圆掩模与局部遮盖核心算法 (李思成)
33
+ │ ├── fundus_pii_trial.py # [眼底相片] 烧录文字交互式可视化核验工具 (李思成)
34
+ │ └── test_deidentify_trial.py # [测试套件] 几何掩模提取单元回归测试 (李思成)
35
+ │
36
+ ├── 02_quality_control/ # 图像质量评估、伪影检测与表格清洗
37
+ │ ├── asrm_preprocess.py # [全库眼底图] 基于 ASRMNet 的清晰度与可诊断性质控 (张焕)
38
+ │ ├── clean_excel.py # [data0410/fundus_hcw] 原始诊断 Excel 表格清洗对齐 (胡成伟)
39
+ │ ├── build_hcw_semantic_patch.py # [data0410/fundus_hcw] 隐私安全诊断侧卡 Parquet 生成 (李思成)
40
+ │ ├── scan_eyepacs_edge_artifact.py # [EyePACS] 历史底片冷冻灰阶边缘伪影扫描 (李思成/团队)
41
+ │ ├── build_quality_risk_review.py # [全库 7 模态] 破损文件头、极端长宽比与曝光异常排查 (李思成)
42
+ │ ├── filter_prompt_artifacts.py # [多模态 Prompt] 提示词格式去噪与非法符号过滤 (李思成)
43
+ │ ├── prompt_qc.py # [多模态 Prompt] 临床提示词解剖层级语法校验 (李思成)
44
+ │ └── resize_mode_qc.py # [多分辨率图] 下采样缩放失真监控与模式验证 (李思成)
45
+ │
46
+ ├── 03_report_parsing/ # 临床报告解析、跨模态检索与主清单物化
47
+ │ ├── materialize_newdata_prompts.py # [多中心新增集] 41 列标准模式多模态主清单生成 (李思成)
48
+ │ ├── attach_labels.py # [同仁/浙二等] 自由文本临床病历报告与图像记录合并 (李思成)
49
+ │ ├── batch_retrieve_reports.py # [OCT_LES_CW_V1] RoBERTa-SigLIP 零样本图文病灶匹配 (张焕)
50
+ │ └── cohorts.py # [全局字典] 多中心合作医院与模态配置主注册表 (李思成)
51
+ │
52
+ ├── 04_modality_split/ # 混杂模态自动化解耦拆分
53
+ │ └── split_octbuckets_octa_review.py# [data0410/octBuckets] 启发式多特征拆分 B-scan/OCTA/SLO (李思成)
54
+ │
55
+ └── 05_taxonomy_and_prompts/ # 疾病分类标准化与 Prompt 净化
56
+ ├── build_mixed_v5_taxonomy.py # [跨院病历] 临床诊断多表交叉映射字典 (Crosswalk) (李思成)
57
+ ├── build_mixed_v6_taxonomy.py # [全库 95 类] 对齐 ICD/SNOMED 的 95 种眼病分类构建器 (李思成)
58
+ ├── test_build_mixed_v6_taxonomy.py# [测试套件] 95 类分类学完整性单元测试 (李思成)
59
+ ├── test_taxonomy_sampling.py # [测试套件] 类别平衡与分层抽样算法测试 (李思成)
60
+ └── build_clean_captions.py # [全库 1.2M 图文] 提示词数据集专有名词去偏工具 (李思成/团队)
61
+ ```
62
+
63
+ ---
64
+
65
+ ## 3. 核心速查表:脚本与针对数据集映射矩阵 (Master Mapping Matrix)
66
+
67
+ | 脚本文件名 | 适用/针对的数据集 (Target Dataset) | 原本用来做什么 (Original Purpose & Function) | 编写/贡献者 |
68
+ | :--- | :--- | :--- | :--- |
69
+ | `crop_fundus_images.py` | `CSDI` / `zhanghuan_selected_public` (公开眼底集) | 基于图像边缘梯度与轮廓拟合,自动切除四周不对称大黑边 | 张焕 (Zhanghuan) |
70
+ | `clean_excel.py` | `archives/data0410/` (`fundus_hcw.zip` 诊断表) | 清洗多源混乱 Excel,核验图片 ID,消除合并单元格与非法字符 | 胡成伟 (Huchengwei) |
71
+ | `asrm_preprocess.py` | 全库彩色眼底相片 (CFP) | 基于 ASRMNet 深度网络评估图像清晰度与临床可诊断性 | 张焕 (Zhanghuan) |
72
+ | `batch_retrieve_reports.py` | `archives/OCT_LES_CW_V1` (OCT 病灶图文对) | 基于 RoBERTa-SigLIP 模型进行零样本跨模态图文对齐与检索 | 张焕 (Zhanghuan) |
73
+ | `scan_eyepacs_edge_artifact.py` | `archives/EyePACS` (糖尿病视网膜筛查集) | 扫描并过滤历史底片中的冷冻灰阶伪影与非纯黑边框 | 李思成 / 团队 |
74
+ | `split_octbuckets_octa_review.py` | `archives/data0410/octBuckets.zip` (混合 OCT) | 提取纵横比、边缘密度、层状评分,拆分 B-scan / OCTA / SLO | 李思成 (Lisicheng) |
75
+ | `build_hcw_semantic_patch.py` | `archives/data0410/fundus_hcw` (眼底大集) | 剥离患者隐私列,生成纯净标准化诊断 Parquet 侧卡 | 李思成 (Lisicheng) |
76
+ | `deidentify_batch.py` | 多中心大规模原始眼底相片(同仁、浙二等数百万张) | 批量多进程圆形视网膜视野掩模覆盖与 OCR 正则敏感字符抹黑 | 李思成 (Lisicheng) |
77
+ | `audit_fundus_corner_pii.py` | 脱敏后的各中心眼底图库 (CFP / UWF) | 自动化扫描图像四角文字残留,进行合规性审计 | 李思成 (Lisicheng) |
78
+ | `deidentify_trial.py` | 通用眼底脱敏算法试算与调试 | Otsu 阈值视网膜轮廓提取与局部高斯/黑框脱敏核心算法库 | 李思成 (Lisicheng) |
79
+ | `build_clean_captions.py` | 全库 1.2M 跨模态预训练图文对 | 正则剔除提示词中 51.9% 泄露的数据集名,保留设备与病征 | 李思成 / 团队 |
80
+ | `build_mixed_v6_taxonomy.py` | 全库 95 类眼科疾病标注体系 | 对齐 ICD-10 与 SNOMED,生成 `tongren95_taxonomy.csv` 标准词典 | 李思成 (Lisicheng) |
81
+ | `materialize_newdata_prompts.py` | 多中心多模态新增图像与报告 | 将分散元数据聚合成 41 列标准模式的主清单 (Manifest) | 李思成 (Lisicheng) |
82
+ | `attach_labels.py` | 北京同仁、浙二等带临床报告队列 | 将非结构化自由病历文本与图像索引进行准确关联 | 李思成 (Lisicheng) |
83
+ | `build_quality_risk_review.py` | 全库 430 万+ 图文资产 (7 大模态) | 扫描图像文件头损坏、极端纵横比与曝光异常样本 | 李思成 (Lisicheng) |
84
+ | `filter_prompt_artifacts.py` | 多模态微调与生成提示词 Prompts | 清除自由文本病历转 Prompts 中的格式噪点与重复标签 | 李思成 (Lisicheng) |
85
+ | `prompt_qc.py` | 全库多模态提示词体系 | 校验提示词“检查类型-解剖部位-眼别-病征”层级语法 | 李思成 (Lisicheng) |
86
+ | `resize_mode_qc.py` | 全库跨硬件厂商的多分辨率图像 | 监控不同设备图像在下采样时的失真情况并建议缩放模式 | 李思成 (Lisicheng) |
87
+ | `cohorts.py` | 全库各中心数据集统一元数据字典 | 集中定义合作医院代码、模态类型与路径分发规则 | 李思成 (Lisicheng) |
88
+ | `build_mixed_v5_taxonomy.py` | 同仁、浙二、邯郸等原始病历诊断 | 多中心病历诊断词条多表交叉映射字典 (Crosswalk) | 李思成 (Lisicheng) |
89
+ | `fundus_pii_trial.py` | 带有设备硬烧录文字的水印眼底图 | 交互式与样本可视化抽检工具,叠加脱敏框与 OCR 框 | 李思成 (Lisicheng) |
90
+ | `test_deidentify_trial.py` | 几何掩模单元回归测试 | 保证复杂长宽比、偏心眼底图在脱敏时不误切视网膜 | 李思成 (Lisicheng) |
91
+ | `test_build_mixed_v6_taxonomy.py` | `tongren95_taxonomy.csv` 标准词典 | 验证 95 种眼病分类层级完整性与 ICD 映射无死角 | 李思成 (Lisicheng) |
92
+ | `test_taxonomy_sampling.py` | 全库长尾分布的多病种诊断数据集 | 验证针对罕见病与常见病的类别平衡抽样算法 | 李思成 (Lisicheng) |
93
+
94
+ ---
95
+
96
+ ## 4. 快速运行与依赖说明 (Quick Start)
97
+
98
+ 所有脚本均在 Python 3.10–3.12 环境下通过验证。推荐安装如下核心科学计算与医学图像依赖:
99
+
100
+ ```bash
101
+ pip install numpy pillow opencv-python pandas pyarrow openpyxl torch torchvision transformers easyocr tqdm
102
+ ```
103
+
104
+ ### 示例 1:对公共眼底集执行多余黑边自动裁切 (张焕)
105
+ ```bash
106
+ python data_processing/01_deidentification/crop_fundus_images.py \
107
+ --input_dir /path/to/raw_csdi_images \
108
+ --output_dir /path/to/cropped_clean_images
109
+ ```
110
+
111
+ ### 示例 2:清洗多中心诊断 Excel 表格 (胡成伟)
112
+ ```bash
113
+ python data_processing/02_quality_control/clean_excel.py \
114
+ --excel_path /path/to/raw_diagnosis.xlsx \
115
+ --output_csv /path/to/clean_diagnosis.csv
116
+ ```
117
+
118
+ ### 示例 3:拆分混杂模态 OCT 数据集 (李思成)
119
+ ```bash
120
+ python data_processing/04_modality_split/split_octbuckets_octa_review.py \
121
+ --manifest /path/to/adapter_manifest.parquet \
122
+ --out_dir /path/to/octbuckets_split_output
123
+ ```