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

Add data processing, de-identification & quality control toolkit

Browse files
tools/data_processing/README.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ophthalmic Data Processing, De-identification & Quality Control Toolkit
2
+
3
+ This toolkit gathers validated, production-tested scripts written by team members for preprocessing, de-identifying, quality filtering, and structuring raw multi-center ophthalmic datasets.
4
+
5
+ ## 1. Directory Layout & Key Modules
6
+
7
+ - deidentification/: Privacy redaction & image sanitization
8
+ - audit_fundus_corner_pii.py: Optical OCR & pixel-density corner PII audit
9
+ - deidentify_trial.py: Core algorithms (fundus circular mask, frame blackout, OCR regex)
10
+ - deidentify_batch.py: High-throughput batch de-identification pipeline
11
+ - fundus_pii_trial.py: Visual inspection harness for burned-in text
12
+ - test_deidentify_trial.py: Automated regression tests for geometric masking
13
+ - crop_fundus_images.py: Automatic contour extraction & fundus border cropping
14
+
15
+ - quality_control/: Multi-stage image & metadata QA
16
+ - build_quality_risk_review.py: Audits aspect ratios, corrupted headers, and outlier samples
17
+ - filter_prompt_artifacts.py: Sanitizes prompt formatting noise and deduplicates tags
18
+ - prompt_qc.py: Validates clinical prompt consistency and anatomical hierarchies
19
+ - resize_mode_qc.py: Aspect ratio and resolution distribution verification
20
+ - asrm_preprocess.py: ASRMNet-based fundus quality evaluation preprocessor
21
+ - clean_excel.py: Cross-references image files against diagnosis tables
22
+
23
+ - report_parsing/: Clinical report extraction & multimodal matching
24
+ - materialize_newdata_prompts.py: Generates unified 41-column structured manifests
25
+ - attach_labels.py: Merges free-text clinical reports with image records
26
+ - batch_retrieve_reports.py: RoBERTa-SigLIP zero-shot image-to-report cross-modal retrieval
27
+ - cohorts.py: Master registry of all multi-center hospital datasets
28
+
29
+ - taxonomy/: Clinical taxonomy & bilingual standardizations
30
+ - build_mixed_v5_taxonomy.py: Disease category crosswalk mapping
31
+ - build_mixed_v6_taxonomy.py: 95-disease hierarchical taxonomy builder (ICD/SNOMED aligned)
32
+ - test_build_mixed_v6_taxonomy.py: Taxonomy integrity tests
33
+ - test_taxonomy_sampling.py: Category-balanced sampling evaluation
34
+
35
+ ## 2. Provenance & Attribution
36
+ Developed by ZJU & Multimodal Ophthalmology Lab contributors (Lisicheng, Zhanghuan, Huchengwei, Lizekun).
tools/data_processing/deidentification/audit_fundus_corner_pii.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit fundus-like cohorts for residual top-left burned-in PII.
2
+
3
+ This script samples images from a prompt-adapter manifest, computes a fast
4
+ top-left white-text proxy, optionally runs OCR on top candidates, and writes a
5
+ review HTML. It never modifies source images and never stores raw OCR text.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import base64
12
+ import io
13
+ import json
14
+ import math
15
+ import tarfile
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import cv2
20
+ import numpy as np
21
+ import pandas as pd
22
+ from PIL import Image
23
+
24
+
25
+ DEFAULT_MANIFEST = Path(
26
+ "/data/team/lisicheng/new_data_manifest/"
27
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/adapter_manifest_mixed_v6.parquet"
28
+ )
29
+ DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/fundus_corner_pii_audit_20260709")
30
+ DEFAULT_COHORTS = [
31
+ "tongren_fundus",
32
+ "tongren_95disease_fundus",
33
+ "fundus90wer",
34
+ "fq_rawfundus",
35
+ "fq_testfundus",
36
+ "tongren_external_fundus",
37
+ "eryuan_t17_fundus",
38
+ "hcw_fundus",
39
+ "eyfrd6_fundus",
40
+ ]
41
+
42
+
43
+ class ImageOpener:
44
+ def __init__(self) -> None:
45
+ self._tar_cache: dict[str, tarfile.TarFile] = {}
46
+
47
+ def close(self) -> None:
48
+ for tf in self._tar_cache.values():
49
+ tf.close()
50
+ self._tar_cache.clear()
51
+
52
+ def open(self, path: str) -> Image.Image:
53
+ if "::" not in path:
54
+ return Image.open(path).convert("RGB")
55
+ tar_path, member = path.split("::", 1)
56
+ tf = self._tar_cache.get(tar_path)
57
+ if tf is None:
58
+ tf = tarfile.open(tar_path, "r:*")
59
+ self._tar_cache[tar_path] = tf
60
+ fh = tf.extractfile(member)
61
+ if fh is None:
62
+ raise FileNotFoundError(member)
63
+ return Image.open(io.BytesIO(fh.read())).convert("RGB")
64
+
65
+
66
+ def top_left_text_proxy(im: Image.Image, top_ratio: float, left_ratio: float) -> dict[str, float]:
67
+ arr = np.asarray(im.convert("RGB"), dtype=np.float32)
68
+ h, w = arr.shape[:2]
69
+ crop = arr[: max(1, int(h * top_ratio)), : max(1, int(w * left_ratio))]
70
+ gray = crop.mean(axis=2)
71
+ white = (crop[..., 0] > 180) & (crop[..., 1] > 180) & (crop[..., 2] > 180)
72
+ dx = np.abs(np.diff(gray, axis=1))
73
+ dy = np.abs(np.diff(gray, axis=0)) if gray.shape[0] > 1 else np.zeros_like(dx)
74
+ edge_density = float(((dx > 18).mean() + (dy > 18).mean()) / 2.0)
75
+ white_fraction = float(white.mean())
76
+ return {
77
+ "corner_white_fraction": round(white_fraction, 6),
78
+ "corner_edge_density": round(edge_density, 6),
79
+ "corner_gray_std": round(float(gray.std()), 4),
80
+ "corner_text_score": round(float(white_fraction * 100.0 + edge_density * 10.0), 6),
81
+ }
82
+
83
+
84
+ def likely_text(stats: dict[str, float]) -> bool:
85
+ return (
86
+ stats["corner_white_fraction"] >= 0.01
87
+ and stats["corner_edge_density"] >= 0.006
88
+ and stats["corner_gray_std"] >= 15.0
89
+ )
90
+
91
+
92
+ def load_ocr_reader(enable: bool) -> object | None:
93
+ if not enable:
94
+ return None
95
+ import easyocr
96
+
97
+ return easyocr.Reader(["ch_sim", "en"], gpu=True)
98
+
99
+
100
+ def run_ocr(reader: object | None, im: Image.Image, top_ratio: float, left_ratio: float) -> dict[str, Any]:
101
+ if reader is None:
102
+ return {
103
+ "ocr_checked": False,
104
+ "ocr_box_count": 0,
105
+ "ocr_has_age": False,
106
+ "ocr_has_sex": False,
107
+ "ocr_has_chinese": False,
108
+ "ocr_has_any_text": False,
109
+ }
110
+ arr = np.asarray(im.convert("RGB"))
111
+ h, w = arr.shape[:2]
112
+ crop = arr[: max(1, int(h * top_ratio)), : max(1, int(w * left_ratio))]
113
+ results = reader.readtext(crop, detail=1)
114
+ detected_text = " ".join(str(item[1]) for item in results if len(item) >= 2)
115
+ return {
116
+ "ocr_checked": True,
117
+ "ocr_box_count": int(len(results)),
118
+ "ocr_has_age": bool(("岁" in detected_text) or any(str(i) in detected_text for i in range(1, 100))),
119
+ "ocr_has_sex": bool(("男" in detected_text) or ("女" in detected_text)),
120
+ "ocr_has_chinese": bool(any("\u4e00" <= ch <= "\u9fff" for ch in detected_text)),
121
+ "ocr_has_any_text": bool(detected_text.strip()),
122
+ }
123
+
124
+
125
+ def thumb_data(im: Image.Image, size: int) -> str:
126
+ thumb = im.copy()
127
+ thumb.thumbnail((size, size), Image.Resampling.LANCZOS)
128
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
129
+ canvas.paste(thumb, ((size - thumb.width) // 2, (size - thumb.height) // 2))
130
+ buf = io.BytesIO()
131
+ canvas.save(buf, format="JPEG", quality=86)
132
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
133
+
134
+
135
+ def json_safe(value: Any) -> Any:
136
+ if isinstance(value, dict):
137
+ return {str(k): json_safe(v) for k, v in value.items()}
138
+ if isinstance(value, list | tuple):
139
+ return [json_safe(v) for v in value]
140
+ if isinstance(value, np.integer):
141
+ return int(value)
142
+ if isinstance(value, np.floating):
143
+ value = float(value)
144
+ if isinstance(value, float):
145
+ return value if math.isfinite(value) else None
146
+ try:
147
+ if pd.isna(value):
148
+ return None
149
+ except (TypeError, ValueError):
150
+ pass
151
+ return value
152
+
153
+
154
+ def audit(args: argparse.Namespace) -> tuple[list[dict[str, Any]], dict[str, Any]]:
155
+ df = pd.read_parquet(
156
+ args.manifest,
157
+ columns=["image_id", "cohort", "modality", "modality_subtype", "file_path"],
158
+ )
159
+ df = df[df["cohort"].astype(str).isin(args.cohorts)].copy()
160
+ sampled = []
161
+ for cohort, group in df.groupby("cohort", sort=True):
162
+ sampled.append(group.sample(n=min(args.per_cohort, len(group)), random_state=args.seed))
163
+ sample = pd.concat(sampled, ignore_index=True) if sampled else df.head(0)
164
+
165
+ opener = ImageOpener()
166
+ rows: list[dict[str, Any]] = []
167
+ try:
168
+ for i, row in enumerate(sample.to_dict("records"), start=1):
169
+ rec = {k: row.get(k) for k in row}
170
+ rec["decode_error"] = ""
171
+ try:
172
+ im = opener.open(str(row["file_path"]))
173
+ rec.update(top_left_text_proxy(im, args.top_ratio, args.left_ratio))
174
+ rec["likely_corner_text"] = likely_text(rec)
175
+ rec["_image"] = im
176
+ except Exception as exc:
177
+ rec["decode_error"] = repr(exc)
178
+ rec["likely_corner_text"] = False
179
+ rec["corner_white_fraction"] = None
180
+ rec["corner_edge_density"] = None
181
+ rec["corner_gray_std"] = None
182
+ rec["corner_text_score"] = None
183
+ rec["_image"] = None
184
+ rows.append(rec)
185
+ if i % 200 == 0:
186
+ print(f"[scan] {i}/{len(sample)}", flush=True)
187
+ finally:
188
+ opener.close()
189
+
190
+ rows.sort(key=lambda r: (str(r.get("cohort")), -(r.get("corner_text_score") or 0.0)))
191
+ ocr_targets: list[dict[str, Any]] = []
192
+ for _, group in pd.DataFrame([{k: v for k, v in r.items() if k != "_image"} for r in rows]).groupby("cohort", sort=True):
193
+ ids = set(group.sort_values("corner_text_score", ascending=False).head(args.ocr_top_per_cohort)["image_id"].astype(str))
194
+ ocr_targets.extend([r for r in rows if str(r["image_id"]) in ids])
195
+
196
+ reader = load_ocr_reader(args.ocr)
197
+ target_ids = {str(r["image_id"]) for r in ocr_targets}
198
+ for rec in rows:
199
+ if str(rec["image_id"]) in target_ids and rec.get("_image") is not None:
200
+ rec.update(run_ocr(reader, rec["_image"], args.top_ratio, args.left_ratio))
201
+ else:
202
+ rec.update(run_ocr(None, None, args.top_ratio, args.left_ratio))
203
+
204
+ html_records = []
205
+ for _, group in pd.DataFrame([{k: v for k, v in r.items() if k != "_image"} for r in rows]).groupby("cohort", sort=True):
206
+ ids = set(group.sort_values("corner_text_score", ascending=False).head(args.html_top_per_cohort)["image_id"].astype(str))
207
+ html_records.extend([r for r in rows if str(r["image_id"]) in ids])
208
+ for rec in html_records:
209
+ im = rec.get("_image")
210
+ rec["thumb_data"] = thumb_data(im, args.thumb_size) if im is not None else ""
211
+
212
+ clean_rows = [{k: v for k, v in r.items() if k != "_image"} for r in rows]
213
+ clean_html = [{k: v for k, v in r.items() if k != "_image"} for r in html_records]
214
+ data = pd.DataFrame(clean_rows)
215
+ summary = {
216
+ "manifest": str(args.manifest),
217
+ "rows_sampled": int(len(clean_rows)),
218
+ "per_cohort": int(args.per_cohort),
219
+ "likely_corner_text_total": int(data["likely_corner_text"].sum()) if len(data) else 0,
220
+ "decode_errors": int(data["decode_error"].fillna("").astype(str).ne("").sum()) if len(data) else 0,
221
+ "by_cohort": data.groupby("cohort").agg(
222
+ sampled=("image_id", "count"),
223
+ likely_corner_text=("likely_corner_text", "sum"),
224
+ mean_corner_text_score=("corner_text_score", "mean"),
225
+ max_corner_text_score=("corner_text_score", "max"),
226
+ ocr_checked=("ocr_checked", "sum"),
227
+ ocr_has_any_text=("ocr_has_any_text", "sum"),
228
+ ocr_has_chinese=("ocr_has_chinese", "sum"),
229
+ ocr_has_age=("ocr_has_age", "sum"),
230
+ ocr_has_sex=("ocr_has_sex", "sum"),
231
+ ).reset_index().to_dict("records")
232
+ if len(data)
233
+ else [],
234
+ }
235
+ return clean_rows, {"summary": summary, "html_records": clean_html}
236
+
237
+
238
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
239
+ rows_json = json.dumps(json_safe(records), ensure_ascii=False, allow_nan=False).replace("</", "<\\/")
240
+ 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}"""
241
+ js = """
242
+ const rows = JSON.parse(document.getElementById('rows-data').textContent);
243
+ let idx = 0;
244
+ function esc(v) { return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
245
+ function go(delta) { idx=Math.max(0, Math.min(rows.length-1, idx+delta)); render(); }
246
+ function gotoIndex(v) { const n=Number(v); if (Number.isFinite(n)) { idx=Math.max(0, Math.min(rows.length-1, n-1)); render(); } }
247
+ function render() {
248
+ if (!rows.length) { document.getElementById('root').innerHTML='<div class=viewer><div class=panel>没有样本。</div></div>'; return; }
249
+ const r=rows[idx];
250
+ document.getElementById('progress').textContent=`第 ${idx+1} / ${rows.length} 张`;
251
+ document.getElementById('jump').value=idx+1;
252
+ 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>`;
253
+ }
254
+ document.addEventListener('keydown', ev => { if (ev.key === 'ArrowRight') go(1); else if (ev.key === 'ArrowLeft') go(-1); });
255
+ render();
256
+ """
257
+ 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>"""
258
+ out.write_text(doc, encoding="utf-8")
259
+
260
+
261
+ def parse_args() -> argparse.Namespace:
262
+ parser = argparse.ArgumentParser(description=__doc__)
263
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
264
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
265
+ parser.add_argument("--cohorts", nargs="+", default=DEFAULT_COHORTS)
266
+ parser.add_argument("--per-cohort", type=int, default=400)
267
+ parser.add_argument("--ocr-top-per-cohort", type=int, default=20)
268
+ parser.add_argument("--html-top-per-cohort", type=int, default=30)
269
+ parser.add_argument("--top-ratio", type=float, default=0.18)
270
+ parser.add_argument("--left-ratio", type=float, default=0.20)
271
+ parser.add_argument("--thumb-size", type=int, default=512)
272
+ parser.add_argument("--seed", type=int, default=20260709)
273
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
274
+ return parser.parse_args()
275
+
276
+
277
+ def main() -> None:
278
+ args = parse_args()
279
+ args.out.mkdir(parents=True, exist_ok=True)
280
+ rows, payload = audit(args)
281
+ pd.DataFrame(rows).to_csv(args.out / "corner_pii_sample_stats.csv", index=False)
282
+ (args.out / "summary.json").write_text(
283
+ json.dumps(json_safe(payload["summary"]), ensure_ascii=False, indent=2, allow_nan=False),
284
+ encoding="utf-8",
285
+ )
286
+ write_html(payload["html_records"], args.out / "OPEN_THIS_FUNDUS_CORNER_PII_AUDIT.html")
287
+ print(json.dumps(json_safe(payload["summary"]), ensure_ascii=False), flush=True)
288
+
289
+
290
+ if __name__ == "__main__":
291
+ main()
tools/data_processing/deidentification/crop_fundus_images.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+ import argparse
5
+ from tqdm import tqdm
6
+ import csv
7
+
8
+ def crop_and_save_image(input_path, output_path, padding=10):
9
+ """
10
+ Crop a single fundus image to remove black background and save to the specified path.
11
+
12
+ Returns:
13
+ dict: A dictionary containing cropping information, used for writing to CSV.
14
+ """
15
+ try:
16
+ image = cv2.imread(input_path)
17
+ if image is None:
18
+ print(f"Warning: Unable to read image {input_path}, skipped.")
19
+ return None
20
+
21
+ original_h, original_w = image.shape[:2]
22
+
23
+ # Convert to grayscale for thresholding
24
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
25
+ _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
26
+
27
+ # Find contours
28
+ contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
29
+ if not contours:
30
+ print(f"Warning: No contours found in image {input_path}, skipped.")
31
+ return None
32
+
33
+ # Find the largest contour (main fundus region)
34
+ main_contour = max(contours, key=cv2.contourArea)
35
+ x, y, w, h = cv2.boundingRect(main_contour)
36
+
37
+ img_h, img_w = original_h, original_w
38
+ x1 = max(0, x - padding)
39
+ y1 = max(0, y - padding)
40
+ x2 = min(img_w, x + w + padding)
41
+ y2 = min(img_h, y + h + padding)
42
+
43
+ cropped_image = image[y1:y2, x1:x2]
44
+
45
+ # Replace white spots in black background with black
46
+ white_mask = np.all(cropped_image == [255, 255, 255], axis=-1)
47
+ cropped_image[white_mask] = [0, 0, 0]
48
+
49
+ cv2.imwrite(output_path, cropped_image)
50
+
51
+ # Calculate cropped pixels (left, top, right, bottom)
52
+ left_crop = x1
53
+ top_crop = y1
54
+ right_crop = img_w - x2
55
+ bottom_crop = img_h - y2
56
+
57
+ return {
58
+ "filename": os.path.basename(input_path),
59
+ "original_width": original_w,
60
+ "original_height": original_h,
61
+ "left_crop": left_crop,
62
+ "top_crop": top_crop,
63
+ "right_crop": right_crop,
64
+ "bottom_crop": bottom_crop
65
+ }
66
+
67
+ except Exception as e:
68
+ print(f"Error processing file {input_path}: {e}")
69
+ return None
70
+
71
+ def main():
72
+ parser = argparse.ArgumentParser(description="Automatically crop fundus images to remove black background.")
73
+ parser.add_argument('-i', '--input_dir', help="Input directory containing original images.", default="csdi_datasets/original_images")
74
+ parser.add_argument('-o', '--output_dir', help="Output directory for saving cropped images.", default="csdi_datasets/croped_images")
75
+ parser.add_argument('-p', '--padding', type=int, default=0, help="Extra pixel padding around the crop boundary, default 0.")
76
+ parser.add_argument('-c', '--csv_path', type=str, default="crop_info.csv", help="CSV file path to save cropping information, default 'crop_info.csv'.")
77
+
78
+ args = parser.parse_args()
79
+ input_dir = args.input_dir
80
+ output_dir = args.output_dir
81
+ padding = args.padding
82
+ csv_path = args.csv_path
83
+
84
+ if not os.path.isdir(input_dir):
85
+ print(f"Error: Input directory '{input_dir}' does not exist.")
86
+ return
87
+
88
+ os.makedirs(output_dir, exist_ok=True)
89
+ print(f"Cropped images will be saved to: '{output_dir}'")
90
+
91
+ supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff')
92
+ image_files = [f for f in os.listdir(input_dir) if f.lower().endswith(supported_formats)]
93
+
94
+ if not image_files:
95
+ print(f"No supported image files found in directory '{input_dir}'.")
96
+ return
97
+
98
+ crop_records = []
99
+
100
+ print(f"Found {len(image_files)} images, starting processing...")
101
+ for filename in tqdm(image_files, desc="Processing progress"):
102
+ input_image_path = os.path.join(input_dir, filename)
103
+ output_image_path = os.path.join(output_dir, filename)
104
+
105
+ record = crop_and_save_image(input_image_path, output_image_path, padding)
106
+ if record:
107
+ crop_records.append(record)
108
+
109
+ # Write CSV file
110
+ with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
111
+ fieldnames = ["filename", "original_width", "original_height", "left_crop", "top_crop", "right_crop", "bottom_crop"]
112
+ writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
113
+ writer.writeheader()
114
+ for rec in crop_records:
115
+ writer.writerow(rec)
116
+
117
+ print(f"All images processed! Cropping information saved to '{csv_path}'.")
118
+
119
+ if __name__ == '__main__':
120
+ main()
tools/data_processing/deidentification/deidentify_batch.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch de-identification for cohorts with confirmed pixel-level PII.
2
+
3
+ Original images are read-only. Processed images are written as opaque-ID JPEGs
4
+ under /data/team/lisicheng/new_data_deid and the manifest is updated to use
5
+ train_path for the affected cohorts.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import math
13
+ import os
14
+ import tarfile
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import cv2
19
+ import numpy as np
20
+
21
+ from deidentify_trial import (
22
+ blackout_frame,
23
+ deidentify_fundus_circle,
24
+ deidentify_fundus_left_outside_circle,
25
+ load_easyocr_reader,
26
+ maybe_ocr_metadata,
27
+ make_sheet,
28
+ read_image,
29
+ write_image,
30
+ )
31
+
32
+
33
+ DEFAULT_MANIFEST = Path(
34
+ "/data/team/lisicheng/new_data_manifest/"
35
+ "new_data_manifest_dedup_split_labeled_with_wds.parquet"
36
+ )
37
+ DEFAULT_OUT_ROOT = Path("/data/team/lisicheng/new_data_deid")
38
+ DEFAULT_TONGREN_METADATA = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv")
39
+ DEID_COHORTS = (
40
+ "tongren_95disease_fundus",
41
+ "fundus90wer",
42
+ "eryuan_fundus",
43
+ "xiangya_bscan",
44
+ "tongren_fundus",
45
+ "tongren_external_fundus",
46
+ "fq_testfundus",
47
+ "fq_rawfundus",
48
+ "fq_validfundus",
49
+ )
50
+ LEFT_ONLY_FUNDUS_COHORTS = {
51
+ "tongren_fundus",
52
+ "tongren_external_fundus",
53
+ "fq_testfundus",
54
+ "fq_rawfundus",
55
+ "fq_validfundus",
56
+ }
57
+ FULL_CIRCLE_FUNDUS_COHORTS = {
58
+ "tongren_95disease_fundus",
59
+ "fundus90wer",
60
+ "eryuan_fundus",
61
+ }
62
+
63
+
64
+ def main() -> None:
65
+ args = parse_args()
66
+ if args.command == "prepare":
67
+ prepare_inputs(args)
68
+ elif args.command == "process":
69
+ process_inputs(args)
70
+ elif args.command == "finalize":
71
+ finalize_manifest(args)
72
+ elif args.command == "qc":
73
+ build_qc(args)
74
+ else:
75
+ raise ValueError(f"unknown command: {args.command}")
76
+
77
+
78
+ def prepare_inputs(args: argparse.Namespace) -> None:
79
+ import pandas as pd
80
+
81
+ args.out_root.mkdir(parents=True, exist_ok=True)
82
+ meta_dir = args.out_root / "metadata"
83
+ meta_dir.mkdir(parents=True, exist_ok=True)
84
+ out_jsonl = args.input_jsonl or meta_dir / "deid_inputs.jsonl"
85
+
86
+ df = pd.read_parquet(args.manifest)
87
+ cohorts = tuple(args.cohorts or DEID_COHORTS)
88
+ subset = df[df["cohort"].isin(cohorts)].copy()
89
+ if args.limit:
90
+ subset = subset.groupby("cohort", group_keys=False).head(args.limit)
91
+
92
+ fields = ["image_id", "cohort", "file_path", "train_path", "rel_path", "modality"]
93
+ missing = [field for field in fields if field not in subset.columns]
94
+ if missing:
95
+ raise KeyError(f"manifest missing columns: {missing}")
96
+
97
+ tongren_meta = load_tongren_metadata(args.tongren_metadata)
98
+ with out_jsonl.open("w", encoding="utf-8") as f:
99
+ for row in subset[fields].to_dict("records"):
100
+ meta = metadata_for_row(row, tongren_meta)
101
+ row.update({f"ocr_{key}": value for key, value in meta.items()})
102
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
103
+
104
+ counts = subset.groupby("cohort").size().to_dict()
105
+ print(json.dumps({"input_jsonl": str(out_jsonl), "counts": counts}, ensure_ascii=False))
106
+
107
+
108
+ def process_inputs(args: argparse.Namespace) -> None:
109
+ meta_dir = args.out_root / "metadata"
110
+ meta_dir.mkdir(parents=True, exist_ok=True)
111
+ shard_name = f"{args.run_name}_shard{args.shard_index:03d}-of-{args.num_shards:03d}.jsonl"
112
+ metadata_path = args.metadata_jsonl or meta_dir / shard_name
113
+ if metadata_path.exists() and not args.overwrite_metadata:
114
+ raise FileExistsError(f"metadata exists; use --overwrite-metadata: {metadata_path}")
115
+
116
+ done_ids = load_done_ids(args.skip_done_metadata_dir, args.skip_done_metadata_glob)
117
+ if done_ids:
118
+ print(f"[resume] loaded {len(done_ids)} completed image_ids")
119
+
120
+ reader = load_easyocr_reader(args.ocr)
121
+ n_seen = 0
122
+ n_skip = 0
123
+ n_done = 0
124
+ n_error = 0
125
+ with args.input_jsonl.open("r", encoding="utf-8") as src, metadata_path.open(
126
+ "w", encoding="utf-8"
127
+ ) as meta_out:
128
+ for idx, line in enumerate(src):
129
+ if idx % args.num_shards != args.shard_index:
130
+ continue
131
+ if args.limit and n_seen >= args.limit:
132
+ break
133
+ n_seen += 1
134
+ row = json.loads(line)
135
+ if row.get("image_id") in done_ids:
136
+ n_skip += 1
137
+ continue
138
+ try:
139
+ result = process_one(row, args, reader)
140
+ n_done += 1
141
+ except Exception as exc:
142
+ n_error += 1
143
+ result = {
144
+ "image_id": row.get("image_id"),
145
+ "cohort": row.get("cohort"),
146
+ "ok": False,
147
+ "error": repr(exc),
148
+ }
149
+ meta_out.write(json.dumps(result, ensure_ascii=False) + "\n")
150
+ if n_seen % args.log_every == 0:
151
+ print(
152
+ f"[{args.shard_index}/{args.num_shards}] "
153
+ f"seen={n_seen} skip={n_skip} done={n_done} err={n_error}"
154
+ )
155
+ print(
156
+ json.dumps(
157
+ {
158
+ "metadata_jsonl": str(metadata_path),
159
+ "seen": n_seen,
160
+ "skip": n_skip,
161
+ "done": n_done,
162
+ "error": n_error,
163
+ },
164
+ ensure_ascii=False,
165
+ )
166
+ )
167
+
168
+
169
+ def process_one(row: dict[str, Any], args: argparse.Namespace, reader: object | None) -> dict[str, Any]:
170
+ cohort = row["cohort"]
171
+ src_path = str(row.get("train_path") or row["file_path"])
172
+ image_id = row["image_id"]
173
+ out_path = args.out_root / "images" / cohort / f"{image_id}.jpg"
174
+ out_path.parent.mkdir(parents=True, exist_ok=True)
175
+
176
+ img = read_image_any(src_path)
177
+ ocr_meta: dict[str, int | str] = existing_ocr_meta(row)
178
+ circle_ok: bool | None = None
179
+ circle_info: dict[str, Any] | None = None
180
+
181
+ if cohort in FULL_CIRCLE_FUNDUS_COHORTS:
182
+ if reader is not None and not ocr_meta:
183
+ ocr_meta = maybe_ocr_metadata(img, reader)
184
+ out_img, circle_ok, circle_info = deidentify_fundus_circle(
185
+ img,
186
+ radius_ratio=args.fundus_radius_ratio,
187
+ threshold=args.fundus_threshold,
188
+ open_kernel=args.fundus_open_kernel,
189
+ )
190
+ method = "fundus_circle_mask"
191
+ elif cohort in LEFT_ONLY_FUNDUS_COHORTS:
192
+ if reader is not None and not ocr_meta:
193
+ ocr_meta = maybe_ocr_metadata(img, reader)
194
+ out_img, circle_ok, circle_info = deidentify_fundus_left_outside_circle(
195
+ img,
196
+ radius_ratio=args.left_fundus_radius_ratio,
197
+ left_ratio=args.left_fundus_ratio,
198
+ threshold=args.fundus_threshold,
199
+ open_kernel=args.fundus_open_kernel,
200
+ )
201
+ method = "fundus_left_outside_circle_mask_r0985_l055"
202
+ elif cohort == "xiangya_bscan":
203
+ out_img = blackout_frame(
204
+ img,
205
+ top=args.bscan_top,
206
+ bottom=args.bscan_bottom,
207
+ right=args.bscan_right,
208
+ )
209
+ method = "bscan_blackout_top10_bottom5_right2"
210
+ else:
211
+ raise ValueError(f"unsupported cohort: {cohort}")
212
+
213
+ if not out_path.exists() or args.overwrite_images:
214
+ write_image(out_path, out_img, quality=args.jpeg_quality)
215
+
216
+ return {
217
+ "image_id": image_id,
218
+ "cohort": cohort,
219
+ "ok": True,
220
+ "source_path": src_path,
221
+ "deid_path": str(out_path),
222
+ "deid_method": method,
223
+ "pii_masked": True,
224
+ "ocr_age": ocr_meta.get("age"),
225
+ "ocr_sex": ocr_meta.get("sex"),
226
+ "ocr_eye": ocr_meta.get("eye"),
227
+ "circle_ok": circle_ok,
228
+ "circle_info": circle_info,
229
+ }
230
+
231
+
232
+ def finalize_manifest(args: argparse.Namespace) -> None:
233
+ import pandas as pd
234
+
235
+ meta_files = sorted(args.metadata_dir.glob(args.metadata_glob))
236
+ if not meta_files:
237
+ raise FileNotFoundError(f"no metadata files match {args.metadata_dir}/{args.metadata_glob}")
238
+
239
+ rows: list[dict[str, Any]] = []
240
+ failed_rows: list[dict[str, Any]] = []
241
+ for path in meta_files:
242
+ with path.open("r", encoding="utf-8") as f:
243
+ for line in f:
244
+ try:
245
+ row = json.loads(line)
246
+ except json.JSONDecodeError:
247
+ continue
248
+ if row.get("ok"):
249
+ rows.append(row)
250
+ elif row.get("image_id"):
251
+ failed_rows.append(row)
252
+ meta = pd.DataFrame(rows)
253
+ if meta.empty:
254
+ raise ValueError("no successful deid metadata rows found")
255
+ meta = meta.drop_duplicates("image_id", keep="last")
256
+
257
+ df = pd.read_parquet(args.manifest)
258
+ df = df.copy()
259
+ if "train_path" not in df.columns:
260
+ df["train_path"] = df["file_path"]
261
+ else:
262
+ df["train_path"] = df["train_path"].where(df["train_path"].notna(), df["file_path"])
263
+ for col, default in [
264
+ ("deid_path", None),
265
+ ("pii_masked", False),
266
+ ("deid_method", None),
267
+ ("ocr_age", None),
268
+ ("ocr_sex", None),
269
+ ("ocr_eye", None),
270
+ ]:
271
+ if col not in df.columns:
272
+ df[col] = default
273
+
274
+ cols = ["image_id", "deid_path", "deid_method", "ocr_age", "ocr_sex", "ocr_eye"]
275
+ merged = df.merge(meta[cols], on="image_id", how="left", suffixes=("", "_new"))
276
+ has_deid = merged["deid_path_new"].notna()
277
+ nullable_cols = [
278
+ "deid_path",
279
+ "deid_path_new",
280
+ "deid_method",
281
+ "deid_method_new",
282
+ "ocr_age",
283
+ "ocr_age_new",
284
+ "ocr_sex",
285
+ "ocr_sex_new",
286
+ "ocr_eye",
287
+ "ocr_eye_new",
288
+ ]
289
+ for col in nullable_cols:
290
+ if col in merged.columns:
291
+ merged[col] = merged[col].astype("object")
292
+ merged.loc[has_deid, "train_path"] = merged.loc[has_deid, "deid_path_new"]
293
+ merged.loc[has_deid, "deid_path"] = merged.loc[has_deid, "deid_path_new"]
294
+ merged.loc[has_deid, "pii_masked"] = True
295
+ for col in ["deid_method", "ocr_age", "ocr_sex", "ocr_eye"]:
296
+ merged.loc[has_deid, col] = merged.loc[has_deid, f"{col}_new"]
297
+ merged = merged.drop(columns=[f"{col}_new" for col in cols if col != "image_id"])
298
+
299
+ required_cohorts = tuple(args.cohorts or DEID_COHORTS)
300
+ missing_deid = merged["cohort"].isin(required_cohorts) & ~merged["pii_masked"]
301
+ dropped_missing_deid = int(missing_deid.sum())
302
+ if dropped_missing_deid:
303
+ missing_path = args.out_manifest.with_suffix(".missing_deid.jsonl")
304
+ missing_records = merged.loc[
305
+ missing_deid, ["image_id", "cohort", "file_path", "rel_path"]
306
+ ].to_dict("records")
307
+ failure_by_id = {row.get("image_id"): row for row in failed_rows}
308
+ with missing_path.open("w", encoding="utf-8") as f:
309
+ for row in missing_records:
310
+ failure = failure_by_id.get(row["image_id"])
311
+ if failure:
312
+ row["error"] = failure.get("error")
313
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
314
+ if args.drop_missing_deid:
315
+ merged = merged.loc[~missing_deid].copy()
316
+
317
+ args.out_manifest.parent.mkdir(parents=True, exist_ok=True)
318
+ merged.to_parquet(args.out_manifest, index=False)
319
+ print(
320
+ json.dumps(
321
+ {
322
+ "out_manifest": str(args.out_manifest),
323
+ "rows": int(len(merged)),
324
+ "pii_masked": int(merged["pii_masked"].sum()),
325
+ "by_cohort": merged[merged["pii_masked"]].groupby("cohort").size().to_dict(),
326
+ "dropped_missing_deid": dropped_missing_deid if args.drop_missing_deid else 0,
327
+ },
328
+ ensure_ascii=False,
329
+ )
330
+ )
331
+
332
+
333
+ def build_qc(args: argparse.Namespace) -> None:
334
+ rows = []
335
+ with args.metadata_jsonl.open("r", encoding="utf-8") as f:
336
+ for line in f:
337
+ row = json.loads(line)
338
+ if args.cohort and row.get("cohort") != args.cohort:
339
+ continue
340
+ if row.get("ok"):
341
+ rows.append(row)
342
+ rows = rows[: args.n]
343
+ groups = []
344
+ for row in rows:
345
+ src = read_image_any(str(row["source_path"]))
346
+ deid = read_image(Path(row["deid_path"]))
347
+ groups.append([src, deid])
348
+ make_sheet(groups, ["source", "deid"], args.out, cell=args.cell)
349
+ print(f"DONE -> {args.out}")
350
+
351
+
352
+ def parse_args() -> argparse.Namespace:
353
+ parser = argparse.ArgumentParser()
354
+ sub = parser.add_subparsers(dest="command", required=True)
355
+
356
+ p = sub.add_parser("prepare")
357
+ p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
358
+ p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT)
359
+ p.add_argument("--input-jsonl", type=Path, default=None)
360
+ p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS))
361
+ p.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_METADATA)
362
+ p.add_argument("--limit", type=int, default=None)
363
+
364
+ p = sub.add_parser("process")
365
+ p.add_argument("--input-jsonl", type=Path, required=True)
366
+ p.add_argument("--out-root", type=Path, default=DEFAULT_OUT_ROOT)
367
+ p.add_argument("--run-name", default="deid")
368
+ p.add_argument("--metadata-jsonl", type=Path, default=None)
369
+ p.add_argument("--overwrite-metadata", action="store_true")
370
+ p.add_argument("--overwrite-images", action="store_true")
371
+ p.add_argument("--skip-done-metadata-dir", type=Path, default=None)
372
+ p.add_argument("--skip-done-metadata-glob", default="*.jsonl")
373
+ p.add_argument("--num-shards", type=int, default=1)
374
+ p.add_argument("--shard-index", type=int, default=0)
375
+ p.add_argument("--limit", type=int, default=None)
376
+ p.add_argument("--log-every", type=int, default=1000)
377
+ p.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
378
+ p.add_argument("--jpeg-quality", type=int, default=95)
379
+ p.add_argument("--fundus-radius-ratio", type=float, default=0.97)
380
+ p.add_argument("--left-fundus-radius-ratio", type=float, default=0.985)
381
+ p.add_argument("--left-fundus-ratio", type=float, default=0.55)
382
+ p.add_argument("--fundus-threshold", type=int, default=25)
383
+ p.add_argument("--fundus-open-kernel", type=int, default=25)
384
+ p.add_argument("--bscan-top", type=float, default=0.10)
385
+ p.add_argument("--bscan-bottom", type=float, default=0.05)
386
+ p.add_argument("--bscan-right", type=float, default=0.02)
387
+
388
+ p = sub.add_parser("finalize")
389
+ p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
390
+ p.add_argument("--metadata-dir", type=Path, default=DEFAULT_OUT_ROOT / "metadata")
391
+ p.add_argument("--metadata-glob", default="deid_shard*.jsonl")
392
+ p.add_argument("--cohorts", nargs="+", default=list(DEID_COHORTS))
393
+ p.add_argument("--drop-missing-deid", action=argparse.BooleanOptionalAction, default=True)
394
+ p.add_argument(
395
+ "--out-manifest",
396
+ type=Path,
397
+ default=DEFAULT_MANIFEST.with_name(
398
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
399
+ ),
400
+ )
401
+
402
+ p = sub.add_parser("qc")
403
+ p.add_argument("--metadata-jsonl", type=Path, required=True)
404
+ p.add_argument("--out", type=Path, required=True)
405
+ p.add_argument("--cohort", default=None)
406
+ p.add_argument("--n", type=int, default=24)
407
+ p.add_argument("--cell", type=int, default=256)
408
+
409
+ return parser.parse_args()
410
+
411
+
412
+ def load_done_ids(metadata_dir: Path | None, metadata_glob: str) -> set[str]:
413
+ if metadata_dir is None:
414
+ return set()
415
+ done: set[str] = set()
416
+ for path in sorted(metadata_dir.glob(metadata_glob)):
417
+ with path.open("r", encoding="utf-8") as f:
418
+ for line in f:
419
+ try:
420
+ row = json.loads(line)
421
+ except json.JSONDecodeError:
422
+ continue
423
+ if row.get("ok") and row.get("image_id"):
424
+ done.add(row["image_id"])
425
+ return done
426
+
427
+
428
+ def read_image_any(path: str) -> Any:
429
+ if "::" not in path:
430
+ return read_image(Path(path))
431
+
432
+ tar_path, member_name = path.split("::", 1)
433
+ with tarfile.open(tar_path, "r:*") as tf:
434
+ member = tf.getmember(member_name)
435
+ fp = tf.extractfile(member)
436
+ if fp is None:
437
+ raise FileNotFoundError(path)
438
+ data = fp.read()
439
+ arr = np.frombuffer(data, dtype=np.uint8)
440
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
441
+ if img is None:
442
+ raise ValueError(f"failed to decode image: {path}")
443
+ return img
444
+
445
+
446
+ def load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]:
447
+ if not path.exists():
448
+ return {}
449
+ import pandas as pd
450
+
451
+ meta = pd.read_csv(path)
452
+ out: dict[str, dict[str, Any]] = {}
453
+ for row in meta.itertuples(index=False):
454
+ filename = str(row.filename)
455
+ sex = {"男": "M", "女": "F"}.get(str(row.sex), None)
456
+ age = None if pd.isna(row.age) else int(row.age)
457
+ eye = eye_from_seq(row.eye_seq)
458
+ out[filename] = {k: v for k, v in {"age": age, "sex": sex, "eye": eye}.items() if v is not None}
459
+ return out
460
+
461
+
462
+ def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]:
463
+ if row.get("cohort") != "tongren_fundus":
464
+ return {}
465
+ name = str(row.get("rel_path") or "")
466
+ if not name:
467
+ path = str(row.get("train_path") or row.get("file_path") or "")
468
+ name = path.split("::", 1)[1] if "::" in path else Path(path).name
469
+ return tongren_meta.get(name, {})
470
+
471
+
472
+ def eye_from_seq(value: Any) -> str | None:
473
+ if value is None or (isinstance(value, float) and math.isnan(value)):
474
+ return None
475
+ text = str(int(value)) if isinstance(value, float) else str(value)
476
+ if text == "1":
477
+ return "OD"
478
+ if text == "2":
479
+ return "OS"
480
+ return None
481
+
482
+
483
+ def existing_ocr_meta(row: dict[str, Any]) -> dict[str, int | str]:
484
+ meta: dict[str, int | str] = {}
485
+ for src_key, dst_key in [("ocr_age", "age"), ("ocr_sex", "sex"), ("ocr_eye", "eye")]:
486
+ value = row.get(src_key)
487
+ if value is None:
488
+ continue
489
+ if isinstance(value, float) and math.isnan(value):
490
+ continue
491
+ if value == "":
492
+ continue
493
+ if dst_key == "age":
494
+ value = int(value)
495
+ meta[dst_key] = value
496
+ return meta
497
+
498
+
499
+ if __name__ == "__main__":
500
+ os.environ.setdefault("PYTHONIOENCODING", "utf-8")
501
+ main()
tools/data_processing/deidentification/deidentify_trial.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small visual trial for burned-in PII handling.
2
+
3
+ This script is intentionally sample-only. It never edits source images and never
4
+ saves raw OCR text. It writes comparison sheets so the cohort-level policy can be
5
+ chosen by eye before a full preprocessing run.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import random
13
+ import re
14
+ from pathlib import Path
15
+ import cv2
16
+ import numpy as np
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ import cohorts as C
20
+
21
+
22
+ IMG_EXTS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp"}
23
+
24
+
25
+ def parse_ocr_metadata(text: str) -> dict[str, int | str]:
26
+ """Keep only non-identifier fields from OCR text."""
27
+ meta: dict[str, int | str] = {}
28
+
29
+ age_match = re.search(r"(?<!\d)(\d{1,3})\s*岁", text)
30
+ if age_match:
31
+ age = int(age_match.group(1))
32
+ if 0 <= age <= 120:
33
+ meta["age"] = age
34
+
35
+ if "男" in text:
36
+ meta["sex"] = "M"
37
+ elif "女" in text:
38
+ meta["sex"] = "F"
39
+
40
+ eye_match = re.search(r"\b(O[DSU])\b", text.upper())
41
+ if eye_match:
42
+ meta["eye"] = eye_match.group(1)
43
+
44
+ return meta
45
+
46
+
47
+ def blackout_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
48
+ """Mask the top horizontal metadata bar while preserving image size."""
49
+ out = img.copy()
50
+ rows = _rows_from_ratio(img, ratio)
51
+ out[:rows, :] = 0
52
+ return out
53
+
54
+
55
+ def crop_top_bar(img: np.ndarray, ratio: float) -> np.ndarray:
56
+ """Remove the top horizontal metadata bar."""
57
+ rows = _rows_from_ratio(img, ratio)
58
+ return img[rows:, :].copy()
59
+
60
+
61
+ def blackout_frame(img: np.ndarray, *, top: float, bottom: float, right: float) -> np.ndarray:
62
+ """Mask fixed device UI bands while preserving the scan geometry."""
63
+ out = img.copy()
64
+ top_rows = _rows_from_ratio(img, top) if top > 0 else 0
65
+ bottom_rows = _rows_from_ratio(img, bottom) if bottom > 0 else 0
66
+ right_cols = _cols_from_ratio(img, right) if right > 0 else 0
67
+ if top_rows:
68
+ out[:top_rows, :] = 0
69
+ if bottom_rows:
70
+ out[-bottom_rows:, :] = 0
71
+ if right_cols:
72
+ out[:, -right_cols:] = 0
73
+ return out
74
+
75
+
76
+ def deidentify_fundus_circle(
77
+ img: np.ndarray,
78
+ *,
79
+ radius_ratio: float = 0.97,
80
+ threshold: int = 25,
81
+ open_kernel: int = 25,
82
+ fallback_top_ratio: float = 0.25,
83
+ ) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
84
+ """Keep the detected retinal circle and black out everything outside it."""
85
+ circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
86
+ if circle_info is None:
87
+ return _fundus_fallback(img, fallback_top_ratio, "no_component")
88
+ cx, cy, radius, area = circle_info
89
+ h, w = img.shape[:2]
90
+ if area < int(h * w * 0.08):
91
+ return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
92
+ radius = float(radius) * radius_ratio
93
+ if radius < min(h, w) * 0.20:
94
+ return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
95
+
96
+ circle = np.zeros((h, w), dtype=np.uint8)
97
+ cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
98
+ out = np.zeros_like(img)
99
+ out[circle > 0] = img[circle > 0]
100
+ return out, True, {"cx": int(cx), "cy": int(cy), "radius": int(radius), "area": area}
101
+
102
+
103
+ def deidentify_fundus_left_outside_circle(
104
+ img: np.ndarray,
105
+ *,
106
+ radius_ratio: float = 0.985,
107
+ left_ratio: float = 0.55,
108
+ threshold: int = 25,
109
+ open_kernel: int = 25,
110
+ fallback_top_ratio: float = 0.25,
111
+ ) -> tuple[np.ndarray, bool, dict[str, float | int | str]]:
112
+ """Black out only left-side pixels outside the detected fundus field of view."""
113
+ circle_info = _detect_fundus_circle(img, threshold=threshold, open_kernel=open_kernel)
114
+ if circle_info is None:
115
+ return _fundus_fallback(img, fallback_top_ratio, "no_component")
116
+
117
+ cx, cy, radius, area = circle_info
118
+ h, w = img.shape[:2]
119
+ if area < int(h * w * 0.08):
120
+ return _fundus_fallback(img, fallback_top_ratio, "component_too_small")
121
+
122
+ radius = float(radius) * radius_ratio
123
+ if radius < min(h, w) * 0.20:
124
+ return _fundus_fallback(img, fallback_top_ratio, "radius_too_small")
125
+
126
+ circle = np.zeros((h, w), dtype=np.uint8)
127
+ cv2.circle(circle, (int(cx), int(cy)), int(radius), 255, -1)
128
+ left_limit = max(int(cx), int(round(w * left_ratio)))
129
+ left_limit = min(w, max(1, left_limit))
130
+ left_mask = np.zeros((h, w), dtype=bool)
131
+ left_mask[:, :left_limit] = True
132
+
133
+ out = img.copy()
134
+ out[(circle == 0) & left_mask] = 0
135
+ return out, True, {
136
+ "cx": int(cx),
137
+ "cy": int(cy),
138
+ "radius": int(radius),
139
+ "area": area,
140
+ "left_limit": int(left_limit),
141
+ }
142
+
143
+
144
+ def read_image(path: Path) -> np.ndarray:
145
+ data = np.fromfile(str(path), dtype=np.uint8)
146
+ img = cv2.imdecode(data, cv2.IMREAD_COLOR)
147
+ if img is None:
148
+ raise ValueError(f"failed to decode image: {path}")
149
+ return img
150
+
151
+
152
+ def write_image(path: Path, img: np.ndarray, quality: int = 92) -> None:
153
+ path.parent.mkdir(parents=True, exist_ok=True)
154
+ ext = path.suffix.lower()
155
+ params = []
156
+ if ext in {".jpg", ".jpeg"}:
157
+ params = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
158
+ ok, data = cv2.imencode(ext, img, params)
159
+ if not ok:
160
+ raise ValueError(f"failed to encode image: {path}")
161
+ data.tofile(str(path))
162
+
163
+
164
+ def sample_paths(cohort_key: str, n: int, seed: int, scan_limit: int | None) -> list[Path]:
165
+ cohort = _cohort(cohort_key)
166
+ root = Path(C.read_path(cohort))
167
+ exts = set(cohort.get("exts") or IMG_EXTS)
168
+ files: list[Path] = []
169
+ for path in root.rglob("*"):
170
+ if path.is_file() and path.suffix.lower() in exts:
171
+ files.append(path)
172
+ if scan_limit and len(files) >= scan_limit:
173
+ break
174
+ if not files:
175
+ raise FileNotFoundError(f"no images found for {cohort_key} under {root}")
176
+ rng = random.Random(seed)
177
+ return rng.sample(files, min(n, len(files)))
178
+
179
+
180
+ def maybe_ocr_metadata(img: np.ndarray, reader: object | None) -> dict[str, int | str]:
181
+ if reader is None:
182
+ return {}
183
+ h = img.shape[0]
184
+ crop = img[: int(h * 0.55), :]
185
+ rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
186
+ results = reader.readtext(rgb, detail=0)
187
+ return parse_ocr_metadata(" ".join(str(item) for item in results))
188
+
189
+
190
+ def load_easyocr_reader(enable: bool) -> object | None:
191
+ if not enable:
192
+ return None
193
+ try:
194
+ import easyocr
195
+ except Exception as exc: # pragma: no cover - depends on h100 environment
196
+ print(f"[warn] easyocr unavailable; OCR metadata disabled: {exc}")
197
+ return None
198
+ try:
199
+ return easyocr.Reader(["ch_sim", "en"], gpu=True)
200
+ except Exception as exc: # pragma: no cover - depends on h100 environment
201
+ print(f"[warn] easyocr reader failed; OCR metadata disabled: {exc}")
202
+ return None
203
+
204
+
205
+ def make_sheet(
206
+ groups: list[list[np.ndarray]],
207
+ labels: list[str],
208
+ out_path: Path,
209
+ *,
210
+ cell: int = 256,
211
+ header: int = 24,
212
+ ) -> None:
213
+ rows = len(groups)
214
+ cols = len(labels)
215
+ sheet = Image.new("RGB", (cols * cell, rows * (cell + header)), (18, 18, 18))
216
+ draw = ImageDraw.Draw(sheet)
217
+ font = ImageFont.load_default()
218
+ for row, imgs in enumerate(groups):
219
+ for col, label in enumerate(labels):
220
+ x = col * cell
221
+ y = row * (cell + header)
222
+ draw.text((x + 5, y + 5), label, fill=(230, 230, 230), font=font)
223
+ thumb = _thumb_bgr(imgs[col], cell)
224
+ sheet.paste(thumb, (x, y + header))
225
+ out_path.parent.mkdir(parents=True, exist_ok=True)
226
+ sheet.save(out_path, quality=92)
227
+
228
+
229
+ def run_fundus_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
230
+ reader = load_easyocr_reader(args.ocr)
231
+ paths = sample_paths(args.fundus_cohort, args.n, args.seed, args.scan_limit)
232
+ groups: list[list[np.ndarray]] = []
233
+ for i, path in enumerate(paths):
234
+ img = read_image(path)
235
+ meta = maybe_ocr_metadata(img, reader)
236
+ masked, ok, info = deidentify_fundus_circle(
237
+ img,
238
+ radius_ratio=args.fundus_radius_ratio,
239
+ threshold=args.fundus_threshold,
240
+ open_kernel=args.fundus_open_kernel,
241
+ )
242
+ groups.append([img, masked])
243
+ write_image(args.out / "fundus" / f"sample_{i:03d}_masked.jpg", masked)
244
+ metadata_rows.append(
245
+ {
246
+ "sample_idx": i,
247
+ "cohort": args.fundus_cohort,
248
+ "kind": "fundus",
249
+ "method": "circle_mask",
250
+ "circle_ok": ok,
251
+ "circle_info": info,
252
+ "ocr_meta": meta,
253
+ }
254
+ )
255
+ make_sheet(groups, ["original", "circle_mask"], args.out / "fundus_compare.jpg")
256
+
257
+
258
+ def run_bscan_trial(args: argparse.Namespace, metadata_rows: list[dict[str, object]]) -> None:
259
+ paths = sample_paths(args.bscan_cohort, args.n, args.seed + 1, args.scan_limit)
260
+ ratios = [float(part) for part in args.bscan_ratios.split(",") if part.strip()]
261
+ frame_specs = _parse_frame_specs(args.bscan_frame_specs)
262
+
263
+ blackout_groups: list[list[np.ndarray]] = []
264
+ crop_groups: list[list[np.ndarray]] = []
265
+ frame_groups: list[list[np.ndarray]] = []
266
+ blackout_labels = ["original"] + [f"black_{int(r * 100)}pct" for r in ratios]
267
+ crop_labels = ["original"] + [f"crop_{int(r * 100)}pct" for r in ratios]
268
+ frame_labels = ["original"] + [
269
+ f"top{int(top * 100)}_bot{int(bottom * 100)}_right{int(right * 100)}"
270
+ for top, bottom, right in frame_specs
271
+ ]
272
+
273
+ for i, path in enumerate(paths):
274
+ img = read_image(path)
275
+ blackout_imgs = [img] + [blackout_top_bar(img, r) for r in ratios]
276
+ crop_imgs = [img] + [crop_top_bar(img, r) for r in ratios]
277
+ frame_imgs = [img] + [
278
+ blackout_frame(img, top=top, bottom=bottom, right=right)
279
+ for top, bottom, right in frame_specs
280
+ ]
281
+ blackout_groups.append(blackout_imgs)
282
+ crop_groups.append(crop_imgs)
283
+ frame_groups.append(frame_imgs)
284
+ for label, out_img in zip(blackout_labels[1:], blackout_imgs[1:], strict=True):
285
+ write_image(args.out / "bscan_blackout" / f"sample_{i:03d}_{label}.jpg", out_img)
286
+ for label, out_img in zip(crop_labels[1:], crop_imgs[1:], strict=True):
287
+ write_image(args.out / "bscan_crop" / f"sample_{i:03d}_{label}.jpg", out_img)
288
+ for label, out_img in zip(frame_labels[1:], frame_imgs[1:], strict=True):
289
+ write_image(args.out / "bscan_frame" / f"sample_{i:03d}_{label}.jpg", out_img)
290
+ metadata_rows.append(
291
+ {
292
+ "sample_idx": i,
293
+ "cohort": args.bscan_cohort,
294
+ "kind": "bscan",
295
+ "methods": {"blackout": ratios, "crop": ratios, "frame": frame_specs},
296
+ }
297
+ )
298
+
299
+ make_sheet(blackout_groups, blackout_labels, args.out / "bscan_blackout_compare.jpg")
300
+ make_sheet(crop_groups, crop_labels, args.out / "bscan_crop_compare.jpg")
301
+ make_sheet(frame_groups, frame_labels, args.out / "bscan_frame_compare.jpg")
302
+
303
+
304
+ def main() -> None:
305
+ args = parse_args()
306
+ args.out.mkdir(parents=True, exist_ok=True)
307
+ metadata_rows: list[dict[str, object]] = []
308
+
309
+ if args.fundus:
310
+ run_fundus_trial(args, metadata_rows)
311
+ if args.bscan:
312
+ run_bscan_trial(args, metadata_rows)
313
+
314
+ with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f:
315
+ for row in metadata_rows:
316
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
317
+ print(f"DONE -> {args.out}")
318
+
319
+
320
+ def parse_args() -> argparse.Namespace:
321
+ parser = argparse.ArgumentParser()
322
+ parser.add_argument("--out", type=Path, default=Path("/data/team/lisicheng/deid_trial"))
323
+ parser.add_argument("--n", type=int, default=12)
324
+ parser.add_argument("--seed", type=int, default=0)
325
+ parser.add_argument("--scan-limit", type=int, default=50000)
326
+ parser.add_argument("--fundus", action=argparse.BooleanOptionalAction, default=True)
327
+ parser.add_argument("--bscan", action=argparse.BooleanOptionalAction, default=True)
328
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
329
+ parser.add_argument("--fundus-cohort", default="tongren_95disease_fundus")
330
+ parser.add_argument("--bscan-cohort", default="xiangya_bscan")
331
+ parser.add_argument("--fundus-radius-ratio", type=float, default=0.97)
332
+ parser.add_argument("--fundus-threshold", type=int, default=25)
333
+ parser.add_argument("--fundus-open-kernel", type=int, default=25)
334
+ parser.add_argument("--bscan-ratios", default="0.06,0.08,0.10")
335
+ parser.add_argument("--bscan-frame-specs", default="0.08,0.05,0.02;0.10,0.05,0.02")
336
+ return parser.parse_args()
337
+
338
+
339
+ def _cohort(key: str) -> dict[str, object]:
340
+ for cohort in C.INCLUDE:
341
+ if cohort["key"] == key:
342
+ return cohort
343
+ raise KeyError(f"unknown cohort: {key}")
344
+
345
+
346
+ def _rows_from_ratio(img: np.ndarray, ratio: float) -> int:
347
+ if not 0 < ratio < 1:
348
+ raise ValueError(f"ratio must be between 0 and 1: {ratio}")
349
+ return max(1, min(img.shape[0] - 1, int(round(img.shape[0] * ratio))))
350
+
351
+
352
+ def _cols_from_ratio(img: np.ndarray, ratio: float) -> int:
353
+ if not 0 < ratio < 1:
354
+ raise ValueError(f"ratio must be between 0 and 1: {ratio}")
355
+ return max(1, min(img.shape[1] - 1, int(round(img.shape[1] * ratio))))
356
+
357
+
358
+ def _parse_frame_specs(raw: str) -> list[tuple[float, float, float]]:
359
+ specs: list[tuple[float, float, float]] = []
360
+ for item in raw.split(";"):
361
+ item = item.strip()
362
+ if not item:
363
+ continue
364
+ parts = [float(part) for part in item.split(",")]
365
+ if len(parts) != 3:
366
+ raise ValueError(f"frame spec must be top,bottom,right: {item}")
367
+ specs.append((parts[0], parts[1], parts[2]))
368
+ return specs
369
+
370
+
371
+ def _to_gray(img: np.ndarray) -> np.ndarray:
372
+ if img.ndim == 2:
373
+ return img
374
+ return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
375
+
376
+
377
+ def _detect_fundus_circle(
378
+ img: np.ndarray, *, threshold: int, open_kernel: int
379
+ ) -> tuple[float, float, float, int] | None:
380
+ gray = _to_gray(img)
381
+ _, th = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
382
+ kernel = np.ones((open_kernel, open_kernel), np.uint8)
383
+ th = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel)
384
+
385
+ n_labels, labels, stats, _ = cv2.connectedComponentsWithStats(th)
386
+ if n_labels <= 1:
387
+ return None
388
+
389
+ areas = stats[1:, cv2.CC_STAT_AREA]
390
+ largest = 1 + int(np.argmax(areas))
391
+ area = int(stats[largest, cv2.CC_STAT_AREA])
392
+ mask = (labels == largest).astype("uint8") * 255
393
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
394
+ if not contours:
395
+ return None
396
+
397
+ contour = max(contours, key=cv2.contourArea)
398
+ (cx, cy), radius = cv2.minEnclosingCircle(contour)
399
+ return cx, cy, radius, area
400
+
401
+
402
+ def _fundus_fallback(
403
+ img: np.ndarray, top_ratio: float, reason: str
404
+ ) -> tuple[np.ndarray, bool, dict[str, str]]:
405
+ return blackout_top_bar(img, top_ratio), False, {"reason": reason}
406
+
407
+
408
+ def _thumb_bgr(img: np.ndarray, cell: int) -> Image.Image:
409
+ if img.ndim == 2:
410
+ rgb = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
411
+ else:
412
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
413
+ im = Image.fromarray(rgb)
414
+ im.thumbnail((cell, cell), Image.Resampling.LANCZOS)
415
+ canvas = Image.new("RGB", (cell, cell), (0, 0, 0))
416
+ canvas.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2))
417
+ return canvas
418
+
419
+
420
+ if __name__ == "__main__":
421
+ main()
tools/data_processing/deidentification/fundus_pii_trial.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small QC trial for fundus-like left-corner PII de-identification.
2
+
3
+ Reads samples from the final manifest, masks the detected circular field of view, and writes
4
+ comparison sheets plus non-identifying metadata. Source images are never modified.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import math
12
+ import tarfile
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import cv2
17
+ import numpy as np
18
+ import pandas as pd
19
+ from PIL import Image
20
+
21
+ from deidentify_trial import (
22
+ deidentify_fundus_circle,
23
+ deidentify_fundus_left_outside_circle,
24
+ load_easyocr_reader,
25
+ make_sheet,
26
+ )
27
+
28
+
29
+ DEFAULT_MANIFEST = Path(
30
+ "/data/team/lisicheng/new_data_manifest/"
31
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
32
+ )
33
+ DEFAULT_TONGREN_META = Path("/data/team/lisicheng/Dataser/tongren_metadata.csv")
34
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/fundus_pii_trial_20260702")
35
+ COHORTS = [
36
+ "tongren_fundus",
37
+ "tongren_external_fundus",
38
+ "fq_testfundus",
39
+ "fq_rawfundus",
40
+ "fq_validfundus",
41
+ ]
42
+
43
+
44
+ def main() -> None:
45
+ args = parse_args()
46
+ args.out.mkdir(parents=True, exist_ok=True)
47
+ reader = load_easyocr_reader(args.ocr)
48
+ tongren_meta = load_tongren_metadata(args.tongren_metadata)
49
+ df = pd.read_parquet(
50
+ args.manifest,
51
+ columns=["image_id", "cohort", "modality", "train_path", "file_path", "rel_path"],
52
+ )
53
+ df = df[df["cohort"].isin(args.cohorts)].copy()
54
+ records = []
55
+ for cohort, group in df.groupby("cohort", sort=True):
56
+ sample = group.sample(n=min(args.per_cohort, len(group)), random_state=args.seed)
57
+ rows = []
58
+ for idx, row in enumerate(sample.to_dict("records")):
59
+ img = read_image_any(str(row.get("train_path") or row.get("file_path")))
60
+ meta = metadata_for_row(row, tongren_meta)
61
+ if not meta and reader is not None:
62
+ meta = ocr_metadata(img, reader)
63
+ masked, ok, info = deidentify_fundus_circle(
64
+ img,
65
+ radius_ratio=args.radius_ratio,
66
+ threshold=args.threshold,
67
+ open_kernel=args.open_kernel,
68
+ )
69
+ left_masked, left_ok, left_info = deidentify_fundus_left_outside_circle(
70
+ img,
71
+ radius_ratio=args.left_radius_ratio,
72
+ left_ratio=args.left_ratio,
73
+ threshold=args.threshold,
74
+ open_kernel=args.open_kernel,
75
+ )
76
+ rows.append([img, masked, left_masked])
77
+ rec = {
78
+ "image_id": row["image_id"],
79
+ "cohort": cohort,
80
+ "source_path": row.get("train_path") or row.get("file_path"),
81
+ "circle_ok": ok,
82
+ "circle_info": info,
83
+ "left_circle_ok": left_ok,
84
+ "left_circle_info": left_info,
85
+ "ocr_age": meta.get("age"),
86
+ "ocr_sex": meta.get("sex"),
87
+ "ocr_eye": meta.get("eye"),
88
+ }
89
+ records.append(rec)
90
+ save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_masked.jpg", masked)
91
+ save_rgb(args.out / "images" / f"{cohort}_{idx:02d}_left_masked.jpg", left_masked)
92
+ make_sheet(
93
+ rows,
94
+ ["source", "full_circle", "left_only_circle"],
95
+ args.out / f"{cohort}_compare.jpg",
96
+ cell=args.cell,
97
+ )
98
+ with (args.out / "metadata.jsonl").open("w", encoding="utf-8") as f:
99
+ for rec in records:
100
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
101
+ print(f"DONE -> {args.out} ({len(records)} samples)")
102
+
103
+
104
+ def load_tongren_metadata(path: Path) -> dict[str, dict[str, Any]]:
105
+ if not path.exists():
106
+ return {}
107
+ meta = pd.read_csv(path)
108
+ out: dict[str, dict[str, Any]] = {}
109
+ for row in meta.itertuples(index=False):
110
+ sex = {"男": "M", "女": "F"}.get(str(row.sex), None)
111
+ age = None if pd.isna(row.age) else int(row.age)
112
+ eye = eye_from_seq(row.eye_seq)
113
+ out[str(row.filename)] = {"age": age, "sex": sex, "eye": eye}
114
+ return out
115
+
116
+
117
+ def eye_from_seq(value: Any) -> str | None:
118
+ if value is None or (isinstance(value, float) and math.isnan(value)):
119
+ return None
120
+ text = str(int(value)) if isinstance(value, float) else str(value)
121
+ if text == "1":
122
+ return "OD"
123
+ if text == "2":
124
+ return "OS"
125
+ return None
126
+
127
+
128
+ def metadata_for_row(row: dict[str, Any], tongren_meta: dict[str, dict[str, Any]]) -> dict[str, Any]:
129
+ name = str(row.get("rel_path") or Path(str(row.get("train_path") or "")).name)
130
+ return {k: v for k, v in tongren_meta.get(name, {}).items() if v is not None}
131
+
132
+
133
+ def ocr_metadata(img: np.ndarray, reader: object) -> dict[str, Any]:
134
+ from deidentify_trial import parse_ocr_metadata
135
+
136
+ h = img.shape[0]
137
+ crop = img[: int(h * 0.55), :]
138
+ rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
139
+ results = reader.readtext(rgb, detail=0)
140
+ return parse_ocr_metadata(" ".join(str(item) for item in results))
141
+
142
+
143
+ def read_image_any(path: str) -> np.ndarray:
144
+ if "::" in path:
145
+ tar_path, member = path.split("::", 1)
146
+ with tarfile.open(tar_path) as tf:
147
+ fp = tf.extractfile(member)
148
+ if fp is None:
149
+ raise FileNotFoundError(path)
150
+ data = fp.read()
151
+ arr = np.frombuffer(data, dtype=np.uint8)
152
+ else:
153
+ arr = np.fromfile(path, dtype=np.uint8)
154
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
155
+ if img is None:
156
+ raise ValueError(f"failed to decode image: {path}")
157
+ return img
158
+
159
+
160
+ def save_rgb(path: Path, img: np.ndarray) -> None:
161
+ path.parent.mkdir(parents=True, exist_ok=True)
162
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
163
+ Image.fromarray(rgb).save(path, quality=92)
164
+
165
+
166
+ def parse_args() -> argparse.Namespace:
167
+ parser = argparse.ArgumentParser()
168
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
169
+ parser.add_argument("--tongren-metadata", type=Path, default=DEFAULT_TONGREN_META)
170
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
171
+ parser.add_argument("--cohorts", nargs="+", default=COHORTS)
172
+ parser.add_argument("--per-cohort", type=int, default=8)
173
+ parser.add_argument("--seed", type=int, default=20260702)
174
+ parser.add_argument("--ocr", action=argparse.BooleanOptionalAction, default=True)
175
+ parser.add_argument("--cell", type=int, default=320)
176
+ parser.add_argument("--radius-ratio", type=float, default=0.97)
177
+ parser.add_argument("--left-radius-ratio", type=float, default=0.985)
178
+ parser.add_argument("--left-ratio", type=float, default=0.55)
179
+ parser.add_argument("--threshold", type=int, default=25)
180
+ parser.add_argument("--open-kernel", type=int, default=25)
181
+ return parser.parse_args()
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
tools/data_processing/deidentification/test_deidentify_trial.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from argparse import Namespace
3
+ from pathlib import Path
4
+ import sys
5
+ import tarfile
6
+ from tempfile import TemporaryDirectory
7
+
8
+ import cv2
9
+ import numpy as np
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
12
+
13
+ from deidentify_batch import metadata_for_row, process_one
14
+ from deidentify_trial import (
15
+ blackout_frame,
16
+ blackout_top_bar,
17
+ crop_top_bar,
18
+ deidentify_fundus_circle,
19
+ deidentify_fundus_left_outside_circle,
20
+ parse_ocr_metadata,
21
+ )
22
+
23
+
24
+ class DeidentifyTrialTest(unittest.TestCase):
25
+ def test_parse_ocr_metadata_keeps_only_non_identifier_fields(self):
26
+ meta = parse_ocr_metadata("张三 61岁 男 OD 2021/05/21 15:15")
27
+
28
+ self.assertEqual(meta, {"age": 61, "sex": "M", "eye": "OD"})
29
+
30
+ def test_fundus_circle_mask_blacks_corner_and_keeps_retina(self):
31
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
32
+ yy, xx = np.ogrid[:160, :160]
33
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
34
+ img[circle] = (90, 80, 70)
35
+ img[:16, :35] = (255, 255, 255)
36
+
37
+ out, ok, _ = deidentify_fundus_circle(img, radius_ratio=0.94, open_kernel=9)
38
+
39
+ self.assertTrue(ok)
40
+ self.assertTrue(np.all(out[4, 4] == 0))
41
+ self.assertTrue(np.all(out[80, 80] == img[80, 80]))
42
+
43
+ def test_left_only_circle_mask_keeps_right_outside_circle(self):
44
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
45
+ yy, xx = np.ogrid[:160, :160]
46
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
47
+ img[circle] = (90, 80, 70)
48
+ img[4, 4] = (255, 255, 255)
49
+ img[4, 150] = (123, 45, 67)
50
+
51
+ out, ok, _ = deidentify_fundus_left_outside_circle(
52
+ img, radius_ratio=0.985, left_ratio=0.55, open_kernel=9
53
+ )
54
+
55
+ self.assertTrue(ok)
56
+ self.assertTrue(np.all(out[4, 4] == 0))
57
+ self.assertTrue(np.all(out[80, 80] == img[80, 80]))
58
+ self.assertTrue(np.array_equal(out[4, 150], img[4, 150]))
59
+
60
+ def test_blackout_top_bar_preserves_shape_and_masks_top_rows(self):
61
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
62
+
63
+ out = blackout_top_bar(img, ratio=0.12)
64
+
65
+ self.assertEqual(out.shape, img.shape)
66
+ self.assertTrue(np.all(out[:12] == 0))
67
+ self.assertTrue(np.all(out[12:] == 128))
68
+
69
+ def test_blackout_frame_masks_top_bottom_and_right_without_resizing(self):
70
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
71
+
72
+ out = blackout_frame(img, top=0.08, bottom=0.05, right=0.02)
73
+
74
+ self.assertEqual(out.shape, img.shape)
75
+ self.assertTrue(np.all(out[:8, :] == 0))
76
+ self.assertTrue(np.all(out[95:, :] == 0))
77
+ self.assertTrue(np.all(out[:, 78:] == 0))
78
+ self.assertTrue(np.all(out[8:95, :78] == 128))
79
+
80
+ def test_crop_top_bar_removes_requested_fraction(self):
81
+ img = np.arange(100 * 80 * 3, dtype=np.uint8).reshape(100, 80, 3)
82
+
83
+ out = crop_top_bar(img, ratio=0.12)
84
+
85
+ self.assertEqual(out.shape, (88, 80, 3))
86
+ self.assertTrue(np.array_equal(out[0], img[12]))
87
+
88
+ def test_process_one_bscan_writes_opaque_jpeg_and_metadata(self):
89
+ with TemporaryDirectory() as tmp:
90
+ tmp_path = Path(tmp)
91
+ src = tmp_path / "source.bmp"
92
+ img = np.full((100, 80, 3), 128, dtype=np.uint8)
93
+ ok, encoded = cv2.imencode(".bmp", img)
94
+ self.assertTrue(ok)
95
+ encoded.tofile(str(src))
96
+
97
+ args = Namespace(
98
+ out_root=tmp_path / "out",
99
+ bscan_top=0.10,
100
+ bscan_bottom=0.05,
101
+ bscan_right=0.02,
102
+ overwrite_images=False,
103
+ jpeg_quality=95,
104
+ )
105
+ row = {
106
+ "image_id": "xiangya_bscan_00000001",
107
+ "cohort": "xiangya_bscan",
108
+ "file_path": str(src),
109
+ }
110
+
111
+ result = process_one(row, args, reader=None)
112
+
113
+ out_path = tmp_path / "out" / "images" / "xiangya_bscan" / "xiangya_bscan_00000001.jpg"
114
+ self.assertTrue(out_path.exists())
115
+ self.assertEqual(result["deid_path"], str(out_path))
116
+ self.assertEqual(result["deid_method"], "bscan_blackout_top10_bottom5_right2")
117
+ self.assertTrue(result["pii_masked"])
118
+
119
+ def test_process_one_left_fundus_reads_tar_member(self):
120
+ with TemporaryDirectory() as tmp:
121
+ tmp_path = Path(tmp)
122
+ img = np.zeros((160, 160, 3), dtype=np.uint8)
123
+ yy, xx = np.ogrid[:160, :160]
124
+ circle = (xx - 80) ** 2 + (yy - 80) ** 2 <= 58**2
125
+ img[circle] = (90, 80, 70)
126
+ img[4, 4] = (255, 255, 255)
127
+ ok, encoded = cv2.imencode(".png", img)
128
+ self.assertTrue(ok)
129
+
130
+ tar_path = tmp_path / "sample.tar"
131
+ png_path = tmp_path / "sample.png"
132
+ encoded.tofile(str(png_path))
133
+ with tarfile.open(tar_path, "w") as tf:
134
+ tf.add(png_path, arcname="sample.png")
135
+
136
+ args = Namespace(
137
+ out_root=tmp_path / "out",
138
+ overwrite_images=False,
139
+ jpeg_quality=95,
140
+ fundus_threshold=25,
141
+ fundus_open_kernel=9,
142
+ left_fundus_radius_ratio=0.985,
143
+ left_fundus_ratio=0.55,
144
+ )
145
+ row = {
146
+ "image_id": "tongren_fundus_00000001",
147
+ "cohort": "tongren_fundus",
148
+ "train_path": f"{tar_path}::sample.png",
149
+ "file_path": f"{tar_path}::sample.png",
150
+ "ocr_age": 61,
151
+ "ocr_sex": "F",
152
+ "ocr_eye": "OD",
153
+ }
154
+
155
+ result = process_one(row, args, reader=None)
156
+
157
+ self.assertTrue(Path(result["deid_path"]).exists())
158
+ self.assertEqual(result["deid_method"], "fundus_left_outside_circle_mask_r0985_l055")
159
+ self.assertEqual(result["ocr_age"], 61)
160
+ self.assertEqual(result["ocr_sex"], "F")
161
+
162
+ def test_tongren_metadata_is_not_applied_to_fq_rows(self):
163
+ meta = {"1005653-1.png": {"age": 63, "sex": "F", "eye": "OD"}}
164
+
165
+ self.assertEqual(
166
+ metadata_for_row(
167
+ {
168
+ "cohort": "fq_rawfundus",
169
+ "rel_path": "1005653-1.png",
170
+ "train_path": "/nfs01/FQ_Datasets/data/rawFundus/1005653-1.png",
171
+ },
172
+ meta,
173
+ ),
174
+ {},
175
+ )
176
+ self.assertEqual(
177
+ metadata_for_row(
178
+ {
179
+ "cohort": "tongren_fundus",
180
+ "rel_path": "1005653-1.png",
181
+ "train_path": "/data/team/lisicheng/Dataser/shards_tongren/fundus/a.tar::1005653-1.png",
182
+ },
183
+ meta,
184
+ ),
185
+ {"age": 63, "sex": "F", "eye": "OD"},
186
+ )
187
+
188
+
189
+ if __name__ == "__main__":
190
+ unittest.main()
tools/data_processing/quality_control/asrm_preprocess.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
6
+ from torchvision import transforms
7
+ from typing import List, Tuple, Dict
8
+ import random
9
+
10
+
11
+ class FundusQualityDataset(Dataset):
12
+ """
13
+ Dataset for fundus quality classification
14
+ Combines:
15
+ - Labeled invalid images
16
+ - Labeled valid images
17
+ - Unlabeled raw images (optional)
18
+ """
19
+ def __init__(
20
+ self,
21
+ invalid_dir: str,
22
+ valid_dir: str,
23
+ raw_dir: str = None,
24
+ img_size: int = 512,
25
+ transform=None,
26
+ use_raw: bool = False,
27
+ raw_pseudo_label_threshold: float = 0.5
28
+ ):
29
+ self.img_size = img_size
30
+ self.transform = transform
31
+ self.use_raw = use_raw
32
+ self.raw_pseudo_label_threshold = raw_pseudo_label_threshold
33
+
34
+ # Load labeled data
35
+ self.invalid_paths = self._load_image_paths(invalid_dir)
36
+ self.valid_paths = self._load_image_paths(valid_dir)
37
+
38
+ # Load unlabeled raw data
39
+ self.raw_paths = []
40
+ if use_raw and raw_dir is not None:
41
+ self.raw_paths = self._load_image_paths(raw_dir)
42
+
43
+ # Combine all paths and create labels
44
+ self.image_paths = []
45
+ self.labels = []
46
+ self.is_labeled = []
47
+
48
+ # Invalid images (label=0)
49
+ for path in self.invalid_paths:
50
+ self.image_paths.append(path)
51
+ self.labels.append(0)
52
+ self.is_labeled.append(True)
53
+
54
+ # Valid images (label=1)
55
+ for path in self.valid_paths:
56
+ self.image_paths.append(path)
57
+ self.labels.append(1)
58
+ self.is_labeled.append(True)
59
+
60
+ # Raw images (unlabeled, label=-1 initially)
61
+ if use_raw:
62
+ for path in self.raw_paths:
63
+ self.image_paths.append(path)
64
+ self.labels.append(-1) # Pseudo label placeholder
65
+ self.is_labeled.append(False)
66
+
67
+ # Pseudo labels dict (for raw images)
68
+ self.pseudo_labels = {}
69
+
70
+ print(f"Dataset loaded: {len(self.invalid_paths)} invalid, "
71
+ f"{len(self.valid_paths)} valid, "
72
+ f"{len(self.raw_paths)} raw")
73
+
74
+ # f:\oinn\image_filter\FQ-ManifoldNet\model_ASRMNet\asrm_preprocess.py
75
+
76
+ # 修改第30行附近的 _load_image_paths 函数
77
+ def _load_image_paths(self, directory: str) -> List[str]:
78
+ """Load all image paths from directory"""
79
+ if not os.path.exists(directory):
80
+ print(f"⚠️ 目录不存在: {directory}")
81
+ return []
82
+
83
+ image_paths = []
84
+ # 支持的扩展名(包含DICOM格式)
85
+ valid_extensions = ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.bmp', '.dcm')
86
+
87
+ # 列出所有文件进行调试
88
+ all_files = os.listdir(directory)
89
+ print(f"📂 {os.path.basename(directory)}: 找到 {len(all_files)} 个文件")
90
+
91
+ # 尝试多种方式扫描
92
+ for filename in all_files:
93
+ # 方法1: 检查小写扩展名
94
+ if filename.lower().endswith(valid_extensions):
95
+ image_paths.append(os.path.join(directory, filename))
96
+
97
+ print(f"✅ {os.path.basename(directory)}: 成功加载 {len(image_paths)} 张图像")
98
+
99
+ # 如果还是0,尝试直接使用所有文件(跳过目录)
100
+ if len(image_paths) == 0:
101
+ print(f"🔍 {os.path.basename(directory)}: 尝试直接使用所有文件...")
102
+ for filename in all_files:
103
+ filepath = os.path.join(directory, filename)
104
+ if os.path.isfile(filepath):
105
+ image_paths.append(filepath)
106
+ print(f" 第二次尝试: 加载了 {len(image_paths)} 张")
107
+
108
+ return image_paths
109
+
110
+ def set_pseudo_labels(self, pseudo_label_dict: Dict[str, float]):
111
+ """
112
+ Set pseudo labels for raw images
113
+ Args:
114
+ pseudo_label_dict: {image_path: quality_score} (0-1)
115
+ """
116
+ self.pseudo_labels = pseudo_label_dict
117
+
118
+ def __len__(self) -> int:
119
+ return len(self.image_paths)
120
+
121
+ def __getitem__(self, idx: int) -> Dict:
122
+ img_path = self.image_paths[idx]
123
+
124
+ # Load image
125
+ img = cv2.imread(img_path)
126
+ if img is None:
127
+ # Return empty image if loading fails
128
+ img = np.zeros((self.img_size, self.img_size, 3), dtype=np.uint8)
129
+
130
+ # Convert to RGB
131
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
132
+
133
+ # Resize
134
+ img = cv2.resize(img, (self.img_size, self.img_size))
135
+
136
+ # Apply transforms
137
+ if self.transform is not None:
138
+ img = self.transform(img)
139
+
140
+ # Get label
141
+ if self.is_labeled[idx]:
142
+ label = self.labels[idx]
143
+ else:
144
+ # Use pseudo label if available, else return -1
145
+ if img_path in self.pseudo_labels:
146
+ score = self.pseudo_labels[img_path]
147
+ label = 1 if score > self.raw_pseudo_label_threshold else 0
148
+ else:
149
+ label = -1
150
+
151
+ return {
152
+ 'image': img,
153
+ 'label': label,
154
+ 'is_labeled': self.is_labeled[idx],
155
+ 'path': img_path
156
+ }
157
+
158
+
159
+ def get_train_transforms(img_size: int = 512):
160
+ """Training data transforms with augmentation"""
161
+ return transforms.Compose([
162
+ transforms.ToPILImage(),
163
+ transforms.RandomHorizontalFlip(p=0.5),
164
+ transforms.RandomRotation(degrees=15),
165
+ transforms.ColorJitter(
166
+ brightness=0.2,
167
+ contrast=0.2,
168
+ saturation=0.2,
169
+ hue=0.1
170
+ ),
171
+ transforms.ToTensor(),
172
+ transforms.Normalize(
173
+ mean=[0.485, 0.456, 0.406],
174
+ std=[0.229, 0.224, 0.225]
175
+ )
176
+ ])
177
+
178
+
179
+ def get_val_transforms(img_size: int = 512):
180
+ """Validation/test data transforms (no augmentation)"""
181
+ return transforms.Compose([
182
+ transforms.ToPILImage(),
183
+ transforms.ToTensor(),
184
+ transforms.Normalize(
185
+ mean=[0.485, 0.456, 0.406],
186
+ std=[0.229, 0.224, 0.225]
187
+ )
188
+ ])
189
+
190
+
191
+ def create_data_loaders(
192
+ invalid_dir: str,
193
+ valid_dir: str,
194
+ raw_dir: str = None,
195
+ img_size: int = 512,
196
+ batch_size: int = 32,
197
+ num_workers: int = 8,
198
+ use_raw: bool = False,
199
+ use_weighted_sampler: bool = True
200
+ ) -> Tuple[DataLoader, DataLoader]:
201
+ """
202
+ Create train and validation data loaders
203
+ Args:
204
+ invalid_dir: Directory with invalid fundus images
205
+ valid_dir: Directory with valid fundus images
206
+ raw_dir: Directory with raw unlabeled images (optional)
207
+ img_size: Target image size
208
+ batch_size: Batch size
209
+ num_workers: Number of data loading workers
210
+ use_raw: Whether to include raw unlabeled images
211
+ use_weighted_sampler: Whether to use weighted sampler for class imbalance
212
+ Returns:
213
+ (train_loader, val_loader)
214
+ """
215
+ # Create train dataset
216
+ train_dataset = FundusQualityDataset(
217
+ invalid_dir=invalid_dir,
218
+ valid_dir=valid_dir,
219
+ raw_dir=raw_dir,
220
+ img_size=img_size,
221
+ transform=get_train_transforms(img_size),
222
+ use_raw=use_raw
223
+ )
224
+
225
+ # Split into train/val
226
+ dataset_size = len(train_dataset)
227
+ val_size = int(0.2 * dataset_size)
228
+ train_size = dataset_size - val_size
229
+
230
+ from torch.utils.data import random_split
231
+ train_subset, val_subset = random_split(
232
+ train_dataset,
233
+ [train_size, val_size],
234
+ generator=torch.Generator().manual_seed(42)
235
+ )
236
+
237
+ # Create samplers
238
+ if use_weighted_sampler:
239
+ # Weighted sampler to handle class imbalance
240
+ labeled_indices = [i for i in range(len(train_dataset))
241
+ if train_dataset.is_labeled[i]]
242
+
243
+ if len(labeled_indices) > 0:
244
+ labeled_labels = [train_dataset.labels[i] for i in labeled_indices]
245
+ class_counts = np.bincount(labeled_labels, minlength=2)
246
+ class_weights = 1.0 / (class_counts + 1e-8)
247
+
248
+ # Create weights for all samples (unlabeled get weight 1)
249
+ weights = torch.ones(len(train_subset))
250
+ for idx_in_subset, idx_in_dataset in enumerate(train_subset.indices):
251
+ if train_dataset.is_labeled[idx_in_dataset]:
252
+ label = train_dataset.labels[idx_in_dataset]
253
+ weights[idx_in_subset] = class_weights[label]
254
+
255
+ sampler = WeightedRandomSampler(weights, len(weights))
256
+ else:
257
+ sampler = None
258
+ else:
259
+ sampler = None
260
+
261
+ # Create data loaders
262
+ train_loader = DataLoader(
263
+ train_subset,
264
+ batch_size=batch_size,
265
+ sampler=sampler,
266
+ shuffle=(sampler is None),
267
+ num_workers=num_workers,
268
+ pin_memory=True,
269
+ drop_last=True
270
+ )
271
+
272
+ val_loader = DataLoader(
273
+ val_subset,
274
+ batch_size=batch_size,
275
+ shuffle=False,
276
+ num_workers=num_workers,
277
+ pin_memory=True
278
+ )
279
+
280
+ return train_loader, val_loader
tools/data_processing/quality_control/build_quality_risk_review.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build an embedded HTML review page for high-risk training rows.
2
+
3
+ This is a targeted human-QC sampler for prompt-adapter manifests. It does not
4
+ modify source images or training manifests.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import base64
11
+ import csv
12
+ import html
13
+ import io
14
+ import json
15
+ import math
16
+ import random
17
+ import tarfile
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import pandas as pd
22
+ from PIL import Image
23
+
24
+
25
+ DEFAULT_MANIFEST = Path(
26
+ "/data/team/lisicheng/new_data_manifest/"
27
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/adapter_manifest_mixed_v6.parquet"
28
+ )
29
+ DEFAULT_CAPTIONS = Path(
30
+ "/data/team/lisicheng/new_data_manifest/"
31
+ "prompt_adapter_mixed_v6_exclude_octbuckets_octa/captions_v2.parquet"
32
+ )
33
+ DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/v6_quality_risk_review_20260709")
34
+
35
+ HIGH_RISK_COHORTS = [
36
+ "data0410_master_fundus",
37
+ "chengdu_shiyi_ubm",
38
+ "eryuan_ubm",
39
+ "yinhai_ubm",
40
+ "yinhai_bscan",
41
+ "xiangya_bscan",
42
+ "chengdu_bscan",
43
+ "yinhai_uwf",
44
+ "eryuan_ffa",
45
+ "eryuan_t17_fundus",
46
+ "hcw_fundus",
47
+ ]
48
+ DEID_SANITY_COHORTS = [
49
+ "fundus90wer",
50
+ "tongren_fundus",
51
+ "tongren_95disease_fundus",
52
+ "tongren_external_fundus",
53
+ "fq_rawfundus",
54
+ "fq_testfundus",
55
+ ]
56
+ RARE_OR_CONFUSABLE_SUBTYPES = [
57
+ "octa_enface",
58
+ "oct_enface",
59
+ "slit_lamp_anterior_segment",
60
+ "reflectance_slo_gray",
61
+ "fundus_fluorescein_angiography",
62
+ "uwf_color_fundus",
63
+ "external_anterior_segment_photo",
64
+ "ocular_bscan_ultrasound",
65
+ "ubm_anterior_segment",
66
+ ]
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 clean(value: Any) -> Any:
93
+ if value is None:
94
+ return None
95
+ if isinstance(value, float) and math.isnan(value):
96
+ return None
97
+ return value
98
+
99
+
100
+ def json_safe(value: Any) -> Any:
101
+ if isinstance(value, dict):
102
+ return {str(k): json_safe(v) for k, v in value.items()}
103
+ if isinstance(value, list | tuple):
104
+ return [json_safe(v) for v in value]
105
+ if value is None:
106
+ return None
107
+ if isinstance(value, float):
108
+ return value if math.isfinite(value) else None
109
+ try:
110
+ if pd.isna(value):
111
+ return None
112
+ except (TypeError, ValueError):
113
+ pass
114
+ return value
115
+
116
+
117
+ def sample_group(group: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:
118
+ if len(group) <= n:
119
+ return group
120
+ return group.sample(n=n, random_state=seed)
121
+
122
+
123
+ def add_samples(
124
+ selected: dict[str, dict[str, Any]],
125
+ frame: pd.DataFrame,
126
+ reason: str,
127
+ n: int,
128
+ seed: int,
129
+ group_col: str | None = None,
130
+ ) -> None:
131
+ if len(frame) == 0:
132
+ return
133
+ if group_col:
134
+ pieces = [sample_group(g, n, seed) for _, g in frame.groupby(group_col, sort=True)]
135
+ rows = pd.concat(pieces, ignore_index=True) if pieces else frame.head(0)
136
+ else:
137
+ rows = sample_group(frame, n, seed)
138
+ for row in rows.to_dict("records"):
139
+ image_id = str(row["image_id"])
140
+ if image_id in selected:
141
+ selected[image_id]["risk_reason"] += f"; {reason}"
142
+ else:
143
+ row["risk_reason"] = reason
144
+ selected[image_id] = row
145
+
146
+
147
+ def build_review_rows(args: argparse.Namespace) -> tuple[list[dict[str, Any]], dict[str, Any]]:
148
+ cols = [
149
+ "image_id",
150
+ "cohort",
151
+ "hospital_domain",
152
+ "modality",
153
+ "modality_family",
154
+ "modality_subtype",
155
+ "view_or_projection",
156
+ "field_of_view",
157
+ "image_quality_band",
158
+ "image_quality_score",
159
+ "image_height_px",
160
+ "image_width_px",
161
+ "file_path",
162
+ "prompt_modality_phrase",
163
+ "diagnosis_group_clean",
164
+ ]
165
+ df = pd.read_parquet(args.manifest, columns=cols)
166
+ rng_seed = args.seed
167
+ selected: dict[str, dict[str, Any]] = {}
168
+
169
+ add_samples(
170
+ selected,
171
+ df[df["image_quality_band"].fillna("").astype(str).eq("poor")],
172
+ "显式 poor quality",
173
+ args.poor_per_modality,
174
+ rng_seed,
175
+ "modality_subtype",
176
+ )
177
+ add_samples(
178
+ selected,
179
+ df[df["cohort"].astype(str).isin(HIGH_RISK_COHORTS)],
180
+ "私有原始路径或水印/PII 高风险 cohort",
181
+ args.high_risk_per_cohort,
182
+ rng_seed + 1,
183
+ "cohort",
184
+ )
185
+ add_samples(
186
+ selected,
187
+ df[df["cohort"].astype(str).isin(DEID_SANITY_COHORTS)],
188
+ "已脱敏大 cohort 抽查",
189
+ args.deid_sanity_per_cohort,
190
+ rng_seed + 2,
191
+ "cohort",
192
+ )
193
+ add_samples(
194
+ selected,
195
+ df[df["modality_subtype"].astype(str).isin(RARE_OR_CONFUSABLE_SUBTYPES)],
196
+ "稀有或易混淆 subtype 抽查",
197
+ args.rare_per_subtype,
198
+ rng_seed + 3,
199
+ "modality_subtype",
200
+ )
201
+ top_cohorts = df["cohort"].value_counts().head(args.top_cohorts).index
202
+ add_samples(
203
+ selected,
204
+ df[df["cohort"].astype(str).isin(top_cohorts.astype(str))],
205
+ "大 cohort 随机兜底抽查",
206
+ args.top_per_cohort,
207
+ rng_seed + 4,
208
+ "cohort",
209
+ )
210
+
211
+ rows = list(selected.values())
212
+ random.Random(args.seed).shuffle(rows)
213
+ if args.max_rows and len(rows) > args.max_rows:
214
+ rows = rows[: args.max_rows]
215
+
216
+ ids = [str(r["image_id"]) for r in rows]
217
+ captions = pd.read_parquet(args.captions, columns=["image_id", "level", "prompt_text"])
218
+ captions["image_id"] = captions["image_id"].astype(str)
219
+ wide = captions[captions["image_id"].isin(ids)].pivot(index="image_id", columns="level", values="prompt_text")
220
+
221
+ opener = ImageOpener()
222
+ records: list[dict[str, Any]] = []
223
+ try:
224
+ for idx, row in enumerate(rows, start=1):
225
+ image_id = str(row["image_id"])
226
+ thumb, open_error = thumbnail(opener, str(row["file_path"]), args.thumb_size)
227
+ record = {
228
+ "review_seq": idx,
229
+ **{k: clean(v) for k, v in row.items()},
230
+ "short_prompt": clean(wide["short"].get(image_id)) if "short" in wide else None,
231
+ "medium_prompt": clean(wide["medium"].get(image_id)) if "medium" in wide else None,
232
+ "dense_prompt": clean(wide["dense"].get(image_id)) if "dense" in wide else None,
233
+ "thumb_data": thumb,
234
+ "open_error": open_error,
235
+ }
236
+ records.append(record)
237
+ finally:
238
+ opener.close()
239
+
240
+ summary = {
241
+ "manifest": str(args.manifest),
242
+ "captions": str(args.captions),
243
+ "rows_in_manifest": int(len(df)),
244
+ "review_rows": int(len(records)),
245
+ "risk_reason_counts": pd.Series([r["risk_reason"] for r in records]).value_counts().astype(int).to_dict(),
246
+ "review_by_cohort": pd.Series([r["cohort"] for r in records]).value_counts().astype(int).to_dict(),
247
+ "review_by_modality_subtype": pd.Series([r["modality_subtype"] for r in records]).value_counts().astype(int).to_dict(),
248
+ "poor_quality_rows": int(df["image_quality_band"].fillna("").astype(str).eq("poor").sum()),
249
+ "high_risk_cohort_rows": int(df["cohort"].astype(str).isin(HIGH_RISK_COHORTS).sum()),
250
+ }
251
+ return records, summary
252
+
253
+
254
+ def thumbnail(opener: ImageOpener, path: str, size: int) -> tuple[str, str]:
255
+ try:
256
+ im = opener.open(path)
257
+ im.thumbnail((size, size), Image.Resampling.LANCZOS)
258
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
259
+ canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
260
+ err = ""
261
+ except Exception as exc:
262
+ canvas = Image.new("RGB", (size, size), (100, 15, 15))
263
+ err = repr(exc)
264
+ buf = io.BytesIO()
265
+ canvas.save(buf, format="JPEG", quality=88)
266
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii"), err
267
+
268
+
269
+ def write_csv(records: list[dict[str, Any]], out: Path) -> None:
270
+ cols = [
271
+ "review_seq",
272
+ "risk_reason",
273
+ "image_id",
274
+ "cohort",
275
+ "hospital_domain",
276
+ "modality",
277
+ "modality_family",
278
+ "modality_subtype",
279
+ "view_or_projection",
280
+ "field_of_view",
281
+ "image_quality_band",
282
+ "image_quality_score",
283
+ "image_height_px",
284
+ "image_width_px",
285
+ "prompt_modality_phrase",
286
+ "diagnosis_group_clean",
287
+ "short_prompt",
288
+ "medium_prompt",
289
+ "dense_prompt",
290
+ "file_path",
291
+ "open_error",
292
+ ]
293
+ with out.open("w", newline="", encoding="utf-8-sig") as handle:
294
+ writer = csv.DictWriter(handle, fieldnames=cols)
295
+ writer.writeheader()
296
+ for row in records:
297
+ writer.writerow({col: row.get(col) for col in cols})
298
+
299
+
300
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
301
+ rows_json = json.dumps(json_safe(records), ensure_ascii=False, allow_nan=False).replace("</", "<\\/")
302
+ 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}}"""
303
+ js = """
304
+ const rows = JSON.parse(document.getElementById('rows-data').textContent);
305
+ const storageKey = 'octflow_v6_quality_risk_review_20260709';
306
+ function loadState(key, fallback) { try { return localStorage.getItem(key) ?? fallback; } catch (_) { return fallback; } }
307
+ let idx = Number(loadState(storageKey + ':idx', '0') || 0);
308
+ let edits = JSON.parse(loadState(storageKey, '{}') || '{}');
309
+ idx = Math.max(0, Math.min(idx, rows.length - 1));
310
+ function esc(v) { return String(v ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
311
+ function edit(id) { return edits[id] || {status:'unreviewed', issue:'', note:''}; }
312
+ function save() { try { localStorage.setItem(storageKey, JSON.stringify(edits)); localStorage.setItem(storageKey + ':idx', String(idx)); } catch (_) {} }
313
+ 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; }
314
+ function go(delta) { idx=Math.max(0, Math.min(rows.length-1, idx+delta)); save(); render(); }
315
+ function gotoIndex(v) { const n=Number(v); if (Number.isFinite(n)) { idx=Math.max(0, Math.min(rows.length-1, n-1)); save(); render(); } }
316
+ 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(); }
317
+ function updateNote(v) { const r=rows[idx]; edits[r.image_id]={...edit(r.image_id),note:v}; save(); }
318
+ function mergedRows() { return rows.map(r=>{ const x={...r, ...edit(r.image_id)}; delete x.thumb_data; return x; }); }
319
+ 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); }
320
+ 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'); }
321
+ function exportJSON() { download('octflow_v6_quality_risk_review_edits.json', JSON.stringify(mergedRows(), null, 2), 'application/json'); }
322
+ function render() {
323
+ if (!rows.length) { document.getElementById('root').innerHTML='<div class=viewer><div class=panel>没有审核样本。</div></div>'; return; }
324
+ const r=rows[idx], e=edit(r.image_id), c=counts();
325
+ 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}`;
326
+ document.getElementById('jump').value=idx+1;
327
+ 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>`;
328
+ }
329
+ document.addEventListener('keydown', ev => {
330
+ const tag=(ev.target && ev.target.tagName || '').toLowerCase();
331
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') return;
332
+ if (ev.key === 'ArrowRight') go(1);
333
+ else if (ev.key === 'ArrowLeft') go(-1);
334
+ else if (ev.key === '1') setStatus('keep');
335
+ else if (ev.key === '2') setStatus('watermark');
336
+ else if (ev.key === '3') setStatus('pii');
337
+ else if (ev.key === '4') setStatus('wrong_modality', false);
338
+ else if (ev.key === '5') setStatus('low_quality');
339
+ else if (ev.key === '6') setStatus('drop');
340
+ else if (ev.key.toLowerCase() === 'c') exportCSV();
341
+ else if (ev.key.toLowerCase() === 'j') exportJSON();
342
+ });
343
+ render();
344
+ """
345
+ doc = f"""<!doctype html><html><head><meta charset="utf-8"><title>OCTFlow v6 风险样本审核</title><style>{css}</style></head>
346
+ <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>"""
347
+ out.write_text(doc, encoding="utf-8")
348
+
349
+
350
+ def parse_args() -> argparse.Namespace:
351
+ parser = argparse.ArgumentParser(description=__doc__)
352
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
353
+ parser.add_argument("--captions", type=Path, default=DEFAULT_CAPTIONS)
354
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
355
+ parser.add_argument("--seed", type=int, default=20260709)
356
+ parser.add_argument("--thumb-size", type=int, default=512)
357
+ parser.add_argument("--poor-per-modality", type=int, default=20)
358
+ parser.add_argument("--high-risk-per-cohort", type=int, default=6)
359
+ parser.add_argument("--deid-sanity-per-cohort", type=int, default=4)
360
+ parser.add_argument("--rare-per-subtype", type=int, default=8)
361
+ parser.add_argument("--top-cohorts", type=int, default=20)
362
+ parser.add_argument("--top-per-cohort", type=int, default=2)
363
+ parser.add_argument("--max-rows", type=int, default=180)
364
+ return parser.parse_args()
365
+
366
+
367
+ def main() -> None:
368
+ args = parse_args()
369
+ args.out.mkdir(parents=True, exist_ok=True)
370
+ records, summary = build_review_rows(args)
371
+ write_csv(records, args.out / "risk_review_rows.csv")
372
+ (args.out / "risk_review_rows.json").write_text(
373
+ json.dumps(json_safe(records), ensure_ascii=False, indent=2, allow_nan=False),
374
+ encoding="utf-8",
375
+ )
376
+ (args.out / "summary.json").write_text(
377
+ json.dumps(summary, ensure_ascii=False, indent=2, allow_nan=False),
378
+ encoding="utf-8",
379
+ )
380
+ write_html(records, args.out / "OPEN_THIS_V6_QUALITY_RISK_REVIEW.html")
381
+ print(json.dumps({"out": str(args.out), **summary}, ensure_ascii=False), flush=True)
382
+
383
+
384
+ if __name__ == "__main__":
385
+ main()
tools/data_processing/quality_control/clean_excel.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+
4
+
5
+ def main():
6
+ # --- 1. 路径配置 ---
7
+ original_excel_path = "/data/team/huchengwei/fundus/fundus_csv/paired_fundus_image_dramdrvo.xlsx"
8
+ missing_log_path = "/data/team/huchengwei/fundus/fundus_csv/missing_images_dramdrvo.txt" # 上一步脚本自动生成的缺失名单
9
+ # 新的干净表格保存路径
10
+ new_excel_path = "/data/team/huchengwei/fundus/fundus_csv/dramdrvo_cleaned.xlsx"
11
+
12
+ # --- 2. 加载缺失黑名单 ---
13
+ if not os.path.exists(missing_log_path):
14
+ raise FileNotFoundError(f"找不到 {missing_log_path},请确认上一步脚本是否正确生成了该文件。")
15
+
16
+ with open(missing_log_path, "r", encoding="utf-8") as f:
17
+ # 去除换行符并存入哈希集合 (Set) 以获得 O(1) 的查询速度
18
+ missing_basenames = set(line.strip() for line in f if line.strip())
19
+
20
+ print(f"[*] 成功加载缺失名单,共计 {len(missing_basenames)} 个目标。")
21
+
22
+ # --- 3. 读取原始 DataFrame ---
23
+ print(f"[*] 正在读取原始 Excel 表格...")
24
+ df = pd.read_excel(original_excel_path)
25
+ original_len = len(df)
26
+
27
+ # --- 4. 核心清洗逻辑 ---
28
+ # 定义过滤条件:提取 image_name 的无后缀基础名,判断其是否在黑名单中
29
+ def is_valid_row(image_name):
30
+ basename = os.path.splitext(str(image_name))[0]
31
+ return basename not in missing_basenames
32
+
33
+ # 应用掩码 (Boolean Mask) 过滤
34
+ mask = df['image_name'].apply(is_valid_row)
35
+ df_cleaned = df[mask]
36
+
37
+ cleaned_len = len(df_cleaned)
38
+ removed_count = original_len - cleaned_len
39
+
40
+ # --- 5. 校验与保存 ---
41
+ print(f"[*] 清洗完成!")
42
+ print(f" -> 原始数据行数: {original_len}")
43
+ print(f" -> 清洗后数据行数: {cleaned_len} (正好对应你成功复制的 5505 张图)")
44
+ print(f" -> 实际排除行数: {removed_count}")
45
+
46
+ # 保存新的 Excel
47
+ df_cleaned.to_excel(new_excel_path, index=False)
48
+ print(f"[*] 新的干净表格已生成并保存至:\n {new_excel_path}")
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
tools/data_processing/quality_control/filter_prompt_artifacts.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filter prompt-adapter manifest/caption artifacts without touching images.
2
+
3
+ The script removes selected cohorts from a prompt-adapter directory and writes a
4
+ new manifest/caption pair plus an audit summary. It is intended for quality or
5
+ privacy exclusions after prompt construction.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+
14
+ import pandas as pd
15
+
16
+
17
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6")
18
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6_exclude_octbuckets_octa")
19
+
20
+
21
+ def _status_from_counts(subtype: str, counts: pd.Series) -> str:
22
+ count = int(counts.get(subtype, 0))
23
+ if count >= 2000:
24
+ return "formal"
25
+ if count >= 500:
26
+ return "supplemental"
27
+ return "tiny"
28
+
29
+
30
+ def _count_dict(frame: pd.DataFrame, column: str) -> dict[str, int]:
31
+ if column not in frame.columns:
32
+ return {}
33
+ return frame[column].fillna("unknown").astype(str).value_counts().astype(int).to_dict()
34
+
35
+
36
+ def _write_readme(out: Path, summary: dict) -> None:
37
+ excluded = ", ".join(summary["excluded_cohorts"])
38
+ text = f"""# Prompt Adapter Filtered Artifacts
39
+
40
+ Source: `{summary["input_dir"]}`
41
+
42
+ Output: `{summary["out_dir"]}`
43
+
44
+ Excluded cohorts: `{excluded}`
45
+
46
+ Reason: manual review found pervasive watermark/low-quality/ambiguous images in
47
+ the excluded cohort, so the whole cohort is removed from training artifacts.
48
+
49
+ Manifest rows:
50
+
51
+ - before: {summary["manifest_rows_before"]}
52
+ - excluded: {summary["manifest_rows_excluded"]}
53
+ - after: {summary["manifest_rows_after"]}
54
+
55
+ Caption rows:
56
+
57
+ - before: {summary["caption_rows_before"]}
58
+ - excluded: {summary["caption_rows_excluded"]}
59
+ - after: {summary["caption_rows_after"]}
60
+
61
+ Files:
62
+
63
+ - `adapter_manifest_mixed_v6.parquet`: filtered training manifest
64
+ - `captions_v2.parquet`: filtered prompts/captions
65
+ - `excluded_rows.parquet`: removed manifest rows
66
+ - `excluded_image_ids.txt`: removed image IDs, one per line
67
+ - `summary.json`: counts and distribution checks
68
+ """
69
+ (out / "README.md").write_text(text, encoding="utf-8")
70
+
71
+
72
+ def parse_args() -> argparse.Namespace:
73
+ parser = argparse.ArgumentParser(description=__doc__)
74
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
75
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
76
+ parser.add_argument("--manifest-name", default="adapter_manifest_mixed_v6.parquet")
77
+ parser.add_argument("--captions-name", default="captions_v2.parquet")
78
+ parser.add_argument("--exclude-cohort", action="append", default=["octbuckets_octa"])
79
+ parser.add_argument("--overwrite", action="store_true")
80
+ return parser.parse_args()
81
+
82
+
83
+ def main() -> None:
84
+ args = parse_args()
85
+ args.out.mkdir(parents=True, exist_ok=True)
86
+ manifest_out = args.out / args.manifest_name
87
+ captions_out = args.out / args.captions_name
88
+ if not args.overwrite:
89
+ for path in [manifest_out, captions_out]:
90
+ if path.exists():
91
+ raise FileExistsError(f"{path} exists; pass --overwrite")
92
+
93
+ manifest_in = args.input / args.manifest_name
94
+ captions_in = args.input / args.captions_name
95
+ manifest = pd.read_parquet(manifest_in)
96
+ captions = pd.read_parquet(captions_in)
97
+ exclude_cohorts = set(args.exclude_cohort)
98
+
99
+ if "cohort" not in manifest.columns:
100
+ raise KeyError("manifest must contain a 'cohort' column")
101
+ if "image_id" not in manifest.columns:
102
+ raise KeyError("manifest must contain an 'image_id' column")
103
+ if "image_id" not in captions.columns:
104
+ raise KeyError("captions must contain an 'image_id' column")
105
+
106
+ cohort_values = manifest["cohort"].fillna("").astype(str)
107
+ excluded_mask = cohort_values.isin(exclude_cohorts)
108
+ excluded = manifest.loc[excluded_mask].copy()
109
+ kept = manifest.loc[~excluded_mask].copy()
110
+
111
+ if "modality_subtype" in kept.columns and "subtype_sample_status" in kept.columns:
112
+ subtype_counts = kept["modality_subtype"].fillna("unknown").astype(str).value_counts()
113
+ kept["subtype_sample_status"] = [
114
+ _status_from_counts(subtype, subtype_counts)
115
+ for subtype in kept["modality_subtype"].fillna("unknown").astype(str)
116
+ ]
117
+
118
+ keep_ids = set(kept["image_id"].astype(str))
119
+ caption_image_ids = captions["image_id"].astype(str)
120
+ kept_captions = captions.loc[caption_image_ids.isin(keep_ids)].copy()
121
+ excluded_caption_rows = int(len(captions) - len(kept_captions))
122
+
123
+ kept.to_parquet(manifest_out, index=False, compression="zstd")
124
+ kept_captions.to_parquet(captions_out, index=False, compression="zstd")
125
+ excluded.to_parquet(args.out / "excluded_rows.parquet", index=False, compression="zstd")
126
+ (args.out / "excluded_image_ids.txt").write_text(
127
+ "\n".join(excluded["image_id"].astype(str).tolist()) + ("\n" if len(excluded) else ""),
128
+ encoding="utf-8",
129
+ )
130
+
131
+ summary = {
132
+ "input_dir": str(args.input),
133
+ "out_dir": str(args.out),
134
+ "excluded_cohorts": sorted(exclude_cohorts),
135
+ "manifest_rows_before": int(len(manifest)),
136
+ "manifest_rows_excluded": int(len(excluded)),
137
+ "manifest_rows_after": int(len(kept)),
138
+ "caption_rows_before": int(len(captions)),
139
+ "caption_rows_excluded": excluded_caption_rows,
140
+ "caption_rows_after": int(len(kept_captions)),
141
+ "excluded_by_modality": _count_dict(excluded, "modality"),
142
+ "excluded_by_modality_family": _count_dict(excluded, "modality_family"),
143
+ "excluded_by_modality_subtype": _count_dict(excluded, "modality_subtype"),
144
+ "after_by_modality": _count_dict(kept, "modality"),
145
+ "after_by_modality_family": _count_dict(kept, "modality_family"),
146
+ "after_by_modality_subtype": _count_dict(kept, "modality_subtype"),
147
+ "after_by_subtype_sample_status": _count_dict(kept, "subtype_sample_status"),
148
+ }
149
+ (args.out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
150
+ _write_readme(args.out, summary)
151
+ print(json.dumps(summary, ensure_ascii=False), flush=True)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ main()
tools/data_processing/quality_control/prompt_qc.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build prompt QC samples for the de-identified new-data manifest."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import html
7
+ import io
8
+ import math
9
+ import re
10
+ import tarfile
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import pandas as pd
15
+ from PIL import Image, ImageOps
16
+
17
+
18
+ DEFAULT_MANIFEST = Path(
19
+ "/data/team/lisicheng/new_data_manifest/"
20
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
21
+ )
22
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_qc")
23
+
24
+ MODALITY_TEXT = {
25
+ "fundus_color": "color fundus photograph",
26
+ "oct_bscan": "OCT B-scan",
27
+ "octa": "optical coherence tomography angiography image",
28
+ "ffa": "fluorescein fundus angiography image",
29
+ "bscan_us": "ocular B-scan ultrasound image",
30
+ "ubm": "ultrasound biomicroscopy image",
31
+ "uwf": "ultra-widefield fundus photograph",
32
+ }
33
+
34
+ BANNED_PROMPT_TERMS = {
35
+ "tongren",
36
+ "xiangya",
37
+ "yinhai",
38
+ "chengdu",
39
+ "eryuan",
40
+ "handan",
41
+ "data0410",
42
+ "hcw",
43
+ "fq_unlabeled",
44
+ "mixed_unlabeled",
45
+ "octbuckets",
46
+ "train",
47
+ "test",
48
+ "internal_test",
49
+ "external_test",
50
+ "unlabeled",
51
+ }
52
+
53
+ DIAG_MAP = {
54
+ "amd": "age-related macular degeneration",
55
+ "年龄相关性黄斑变性": "age-related macular degeneration",
56
+ "老年性黄斑变性": "age-related macular degeneration",
57
+ "dr": "diabetic retinopathy",
58
+ "糖尿病视网膜病变": "diabetic retinopathy",
59
+ "糖网": "diabetic retinopathy",
60
+ "normal": "normal",
61
+ "正常": "normal",
62
+ "rvo": "retinal vein occlusion",
63
+ "视网膜静脉阻塞": "retinal vein occlusion",
64
+ "csc": "central serous chorioretinopathy",
65
+ "中心性浆液性脉络膜视网膜病变": "central serous chorioretinopathy",
66
+ "中浆": "central serous chorioretinopathy",
67
+ "erm": "epiretinal membrane",
68
+ "黄斑前膜": "epiretinal membrane",
69
+ "mh": "macular hole",
70
+ "黄斑裂孔": "macular hole",
71
+ "rao": "retinal artery occlusion",
72
+ "视网膜动脉阻塞": "retinal artery occlusion",
73
+ "rd": "retinal detachment",
74
+ "视网膜脱离": "retinal detachment",
75
+ "vkh": "Vogt-Koyanagi-Harada disease",
76
+ "葡萄膜炎": "uveitis",
77
+ "青光眼": "glaucoma",
78
+ "白内障": "cataract",
79
+ }
80
+
81
+ FINDING_RULES = [
82
+ (re.compile(r"玻璃体混浊|中低回声光点|中低回声光斑"), "vitreous opacity"),
83
+ (re.compile(r"玻璃体积血"), "vitreous hemorrhage"),
84
+ (re.compile(r"玻璃体后脱离"), "posterior vitreous detachment"),
85
+ (re.compile(r"后巩膜葡萄肿"), "posterior staphyloma"),
86
+ (re.compile(r"视网膜脱离"), "retinal detachment"),
87
+ (re.compile(r"视网膜裂孔"), "retinal tear"),
88
+ (re.compile(r"眼内占位|占位性病变"), "intraocular mass"),
89
+ (re.compile(r"脉络膜黑色素瘤"), "choroidal melanoma"),
90
+ (re.compile(r"硅油眼"), "silicone oil eye"),
91
+ (re.compile(r"黄斑囊样水肿|黄斑水肿|囊样水肿"), "macular edema"),
92
+ (re.compile(r"黄斑前膜"), "epiretinal membrane"),
93
+ (re.compile(r"黄斑裂孔"), "macular hole"),
94
+ (re.compile(r"分支静脉阻塞"), "branch retinal vein occlusion"),
95
+ (re.compile(r"视网膜静脉阻塞|静脉阻塞"), "retinal vein occlusion"),
96
+ (re.compile(r"视网膜动脉阻塞|动脉阻塞"), "retinal artery occlusion"),
97
+ (re.compile(r"糖尿病视网膜病变|糖网"), "diabetic retinopathy"),
98
+ (re.compile(r"高血压视网膜病变"), "hypertensive retinopathy"),
99
+ (re.compile(r"新生血管|CNV", re.I), "neovascularization"),
100
+ (re.compile(r"荧光渗漏|渗漏"), "fluorescein leakage"),
101
+ (re.compile(r"无灌注"), "capillary nonperfusion"),
102
+ (re.compile(r"微动脉瘤"), "microaneurysms"),
103
+ (re.compile(r"硬性渗出|硬渗"), "hard exudates"),
104
+ (re.compile(r"棉絮斑"), "cotton-wool spots"),
105
+ (re.compile(r"出血"), "retinal hemorrhage"),
106
+ (re.compile(r"视盘.*高荧光|视盘.*渗漏"), "optic disc leakage"),
107
+ (re.compile(r"房角开放"), "open anterior chamber angle"),
108
+ (re.compile(r"房角偏窄|窄房角|房角狭窄"), "narrow anterior chamber angle"),
109
+ (re.compile(r"虹膜平坦"), "flat iris configuration"),
110
+ (re.compile(r"睫状体.*囊|囊样暗区|囊样无回声区"), "ciliary body cyst"),
111
+ (re.compile(r"晶体内回声增强"), "lens opacity"),
112
+ (re.compile(r"前房.*浅"), "shallow anterior chamber"),
113
+ ]
114
+
115
+ PII_PATTERNS = [
116
+ re.compile(r"(姓名|患者姓名|病人姓名|name)\s*[::]?\s*[\u4e00-\u9fffA-Za-z·]{1,8}", re.I),
117
+ re.compile(r"(ID号|\bID\b|编号|住院号|门诊号|检查号|patient\s*id)\s*[::]?\s*[A-Za-z0-9_-]+", re.I),
118
+ re.compile(r"(检查日期|出生日期|DOB)\s*[::]?\s*\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?", re.I),
119
+ re.compile(r"\b\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?\b"),
120
+ re.compile(r"\b\d{8,}\b"),
121
+ ]
122
+
123
+
124
+ def clean_text(text: Any) -> str:
125
+ if text is None:
126
+ return ""
127
+ if isinstance(text, float) and math.isnan(text):
128
+ return ""
129
+ out = str(text)
130
+ for pattern in PII_PATTERNS:
131
+ out = pattern.sub("", out)
132
+ out = re.sub(r"(医师签名|医生签名|签名|建议门诊|门诊时间).*", "", out, flags=re.I)
133
+ out = re.sub(r"(待删|删除)", "", out)
134
+ out = re.sub(r"\s+", " ", out)
135
+ out = re.sub(r"[,。;;,\s]+$", "", out)
136
+ return out.strip(" ,。;;,")
137
+
138
+
139
+ def build_prompts(row: dict[str, Any]) -> dict[str, str]:
140
+ modality = str(row.get("modality") or "")
141
+ base = base_prompt(row, modality)
142
+ descriptors = _clinical_descriptors(row)
143
+ demographics = _demographics(row)
144
+
145
+ short_parts = [base]
146
+ medium_parts = [base] + demographics + descriptors[:3]
147
+ dense_parts = [base] + demographics + descriptors[:8]
148
+
149
+ return {
150
+ "short": _join(short_parts),
151
+ "medium": _join(medium_parts),
152
+ "dense": _join(dense_parts),
153
+ }
154
+
155
+
156
+ def base_prompt(row: dict[str, Any], modality: str) -> str:
157
+ if str(row.get("cohort") or "") == "tongren_external_fundus":
158
+ return "anterior segment photograph"
159
+ return MODALITY_TEXT.get(modality, f"{modality.replace('_', ' ')} ophthalmic image")
160
+
161
+
162
+ def main() -> None:
163
+ args = parse_args()
164
+ args.out.mkdir(parents=True, exist_ok=True)
165
+ (args.out / "imgs").mkdir(exist_ok=True)
166
+
167
+ df = pd.read_parquet(args.manifest)
168
+ df = df[df.get("split", "train") == "train"].copy() if "split" in df.columns else df.copy()
169
+ for col in ["center", "modality"]:
170
+ if col not in df.columns:
171
+ raise KeyError(f"manifest missing {col!r}")
172
+
173
+ samples = sample_by_center_modality(df, args.per_group, args.seed)
174
+ records = []
175
+ caption_rows = []
176
+ for idx, row in enumerate(samples.to_dict("records")):
177
+ prompts = build_prompts(row)
178
+ for level, prompt in prompts.items():
179
+ caption_rows.append(
180
+ {"image_id": row["image_id"], "level": level, "prompt_text": prompt}
181
+ )
182
+ image_rel = render_thumb(row, args.out / "imgs", idx, args.thumb)
183
+ record = {
184
+ "idx": idx,
185
+ "image_rel": image_rel,
186
+ "prompts": prompts,
187
+ **{k: row.get(k) for k in [
188
+ "image_id",
189
+ "center",
190
+ "modality",
191
+ "cohort",
192
+ "diagnosis_raw",
193
+ "group_raw",
194
+ "diagnosis_group",
195
+ "caption",
196
+ "train_path",
197
+ "pii_masked",
198
+ "ocr_age",
199
+ "ocr_sex",
200
+ "ocr_eye",
201
+ ]},
202
+ }
203
+ records.append(record)
204
+
205
+ caps = pd.DataFrame(caption_rows)
206
+ caps.to_parquet(args.out / "prompt_qc_captions.parquet", index=False)
207
+ caps.to_csv(args.out / "prompt_qc_captions.csv", index=False)
208
+ write_html(records, args.out / "prompt_qc.html")
209
+ write_design(args.out / "prompt_design.md")
210
+ print(f"DONE -> {args.out / 'prompt_qc.html'} ({len(records)} samples)")
211
+
212
+
213
+ def sample_by_center_modality(df: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:
214
+ groups = []
215
+ for (_, _), group in df.groupby(["center", "modality"], dropna=False):
216
+ groups.append(group.sample(n=min(n, len(group)), random_state=seed))
217
+ out = pd.concat(groups, ignore_index=True)
218
+ return out.sort_values(["modality", "center", "cohort", "image_id"]).reset_index(drop=True)
219
+
220
+
221
+ def render_thumb(row: dict[str, Any], img_dir: Path, idx: int, size: int) -> str:
222
+ path = str(row.get("train_path") or row.get("file_path"))
223
+ name = f"{idx:04d}_{safe_name(row.get('modality'))}_{safe_name(row.get('center'))}.jpg"
224
+ out = img_dir / name
225
+ try:
226
+ if "::" in path:
227
+ im = open_wds_member(path).convert("RGB")
228
+ else:
229
+ im = Image.open(path).convert("RGB")
230
+ im.thumbnail((size, size), Image.Resampling.LANCZOS)
231
+ canvas = Image.new("RGB", (size, size), (0, 0, 0))
232
+ canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
233
+ im = canvas
234
+ im.save(out, quality=90)
235
+ except Exception:
236
+ im = Image.new("RGB", (size, size), (80, 20, 20))
237
+ im = ImageOps.expand(im, border=2, fill=(255, 0, 0))
238
+ im.save(out, quality=90)
239
+ return f"imgs/{name}"
240
+
241
+
242
+ def open_wds_member(path: str) -> Image.Image:
243
+ tar_path, member_name = path.split("::", 1)
244
+ with tarfile.open(tar_path, "r:*") as tf:
245
+ member = tf.getmember(member_name)
246
+ fp = tf.extractfile(member)
247
+ if fp is None:
248
+ raise FileNotFoundError(path)
249
+ data = fp.read()
250
+ return Image.open(io.BytesIO(data))
251
+
252
+
253
+ def write_html(records: list[dict[str, Any]], out: Path) -> None:
254
+ css = """
255
+ body{font-family:Arial,sans-serif;margin:20px;background:#f7f7f7;color:#222}
256
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(460px,1fr));gap:14px}
257
+ .card{background:white;border:1px solid #ddd;border-radius:6px;padding:12px}
258
+ img{width:180px;height:180px;object-fit:contain;background:#000;float:left;margin-right:12px}
259
+ .meta{font-size:12px;color:#555;line-height:1.35}
260
+ .prompt{font-size:13px;margin:6px 0}.level{font-weight:bold;color:#333}
261
+ .caption{clear:both;font-size:12px;color:#555;border-top:1px solid #eee;margin-top:10px;padding-top:8px}
262
+ h1{margin-bottom:4px}.note{color:#555;margin-bottom:18px}
263
+ """
264
+ parts = [
265
+ "<!doctype html><html><head><meta charset='utf-8'>",
266
+ f"<style>{css}</style></head><body>",
267
+ "<h1>New-data prompt QC</h1>",
268
+ "<div class='note'>Grouped by center × modality, sampled 5 rows per group. "
269
+ "Prompts intentionally exclude center/cohort names and raw identifiers.</div>",
270
+ "<div class='grid'>",
271
+ ]
272
+ for r in records:
273
+ parts.append("<div class='card'>")
274
+ parts.append(f"<img src='{html.escape(r['image_rel'])}'>")
275
+ parts.append("<div class='meta'>")
276
+ for k in ["image_id", "modality", "center", "cohort", "pii_masked", "ocr_age", "ocr_sex", "ocr_eye"]:
277
+ parts.append(f"<b>{k}</b>: {html.escape(str(r.get(k)))}<br>")
278
+ parts.append(f"<b>train_path</b>: {html.escape(str(r.get('train_path'))[:180])}</div>")
279
+ for level in ["short", "medium", "dense"]:
280
+ parts.append(
281
+ f"<div class='prompt'><span class='level'>{level}</span>: "
282
+ f"{html.escape(r['prompts'][level])}</div>"
283
+ )
284
+ parts.append("<div class='caption'>")
285
+ for k in ["diagnosis_raw", "group_raw", "diagnosis_group", "caption"]:
286
+ v = r.get(k)
287
+ if v is not None and not (isinstance(v, float) and math.isnan(v)):
288
+ parts.append(f"<b>{k}</b>: {html.escape(str(v)[:400])}<br>")
289
+ parts.append("</div></div>")
290
+ parts.append("</div></body></html>")
291
+ out.write_text("\n".join(parts), encoding="utf-8")
292
+
293
+
294
+ def write_design(out: Path) -> None:
295
+ text = """# Prompt design logic
296
+
297
+ The training prompt space follows the previous private-data SD3 logic: each image has
298
+ multiple candidate prompts (`short`, `medium`, `dense`), and training samples one
299
+ prompt level at random per step.
300
+
301
+ Prompt levels:
302
+ - `short`: modality phrase only, matching the old private-data minimal prompt style.
303
+ - `medium`: modality phrase plus age/sex/eye if available and up to three English labels.
304
+ - `dense`: modality phrase plus age/sex/eye if available and up to eight English labels.
305
+
306
+ Modality phrases:
307
+ - `fundus_color`: color fundus photograph
308
+ - `tongren_external_fundus`: anterior segment photograph, overriding the
309
+ `fundus_color` modality phrase because these images are external/anterior-eye photos.
310
+ - `uwf`: ultra-widefield fundus photograph
311
+ - `ffa`: fluorescein fundus angiography image
312
+ - `octa`: optical coherence tomography angiography image
313
+ - `bscan_us`: ocular B-scan ultrasound image
314
+ - `ubm`: ultrasound biomicroscopy image
315
+
316
+ Safety rules:
317
+ - Never include center, hospital, cohort, dataset name, file name, ID, exact date, DOB, or raw OCR text.
318
+ - Store only non-identifying OCR-derived attributes: age, sex, eye laterality.
319
+ - Rows without labels still receive a modality-only prompt.
320
+ - Long free-text reports are never copied into prompts; they are reduced to English finding labels.
321
+ """
322
+ out.write_text(text, encoding="utf-8")
323
+
324
+
325
+ def _clinical_descriptors(row: dict[str, Any]) -> list[str]:
326
+ desc: list[str] = []
327
+ for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
328
+ val = clean_text(row.get(key))
329
+ val = translate_diag(val)
330
+ candidates = [val] if _is_prompt_ready_label(val) else extract_finding_tags(val)
331
+ _extend_unique(desc, candidates)
332
+ cap = clean_text(row.get("caption"))
333
+ _extend_unique(desc, extract_finding_tags(cap))
334
+ return desc
335
+
336
+
337
+ def extract_finding_tags(text: str) -> list[str]:
338
+ if not text:
339
+ return []
340
+ tags = [label for pattern, label in FINDING_RULES if pattern.search(text)]
341
+ return _unique(tags)
342
+
343
+
344
+ def _extend_unique(out: list[str], values: list[str]) -> None:
345
+ seen = {v.lower() for v in out}
346
+ for value in values:
347
+ if _allowed_descriptor(value) and value.lower() not in seen:
348
+ out.append(value)
349
+ seen.add(value.lower())
350
+
351
+
352
+ def _unique(values: list[str]) -> list[str]:
353
+ out = []
354
+ seen = set()
355
+ for value in values:
356
+ key = value.lower()
357
+ if key not in seen:
358
+ out.append(value)
359
+ seen.add(key)
360
+ return out
361
+
362
+
363
+ def _is_prompt_ready_label(text: str) -> bool:
364
+ if not _allowed_descriptor(text):
365
+ return False
366
+ if re.search(r"[\u4e00-\u9fff]", text):
367
+ return False
368
+ return _is_concise_label(text)
369
+
370
+
371
+ def _allowed_descriptor(text: str) -> bool:
372
+ if not text:
373
+ return False
374
+ lowered = text.lower().strip()
375
+ if lowered in BANNED_PROMPT_TERMS:
376
+ return False
377
+ if "_" in text or re.match(r"^group\d+\b", lowered):
378
+ return False
379
+ return not any(term in lowered for term in BANNED_PROMPT_TERMS)
380
+
381
+
382
+ def _is_concise_label(text: str) -> bool:
383
+ if len(text) > 80:
384
+ return False
385
+ return not re.search(r"[。;;]|提示|所��|检查", text)
386
+
387
+
388
+ def _clip_text(text: str, max_chars: int) -> str:
389
+ if len(text) <= max_chars:
390
+ return text
391
+ return text[: max_chars - 3].rstrip(" ,。;;,") + "..."
392
+
393
+
394
+ def _demographics(row: dict[str, Any]) -> list[str]:
395
+ out: list[str] = []
396
+ age = row.get("ocr_age")
397
+ if age is not None and not (isinstance(age, float) and math.isnan(age)):
398
+ bucket = age_bucket(age)
399
+ if bucket:
400
+ out.append(bucket)
401
+ sex = str(row.get("ocr_sex") or "").upper()
402
+ if sex == "M":
403
+ out.append("male")
404
+ elif sex == "F":
405
+ out.append("female")
406
+ eye = str(row.get("ocr_eye") or "").upper()
407
+ if eye == "OD":
408
+ out.append("right eye")
409
+ elif eye == "OS":
410
+ out.append("left eye")
411
+ elif eye == "OU":
412
+ out.append("both eyes")
413
+ if len(out) >= 2 and out[1] in {"male", "female"}:
414
+ out = [f"{out[1]} patient {out[0]}"] + out[2:]
415
+ return out
416
+
417
+
418
+ def age_bucket(age: Any) -> str:
419
+ try:
420
+ value = int(age)
421
+ except (TypeError, ValueError):
422
+ return ""
423
+ if value < 0 or value > 120:
424
+ return ""
425
+ if value < 2:
426
+ return "infant"
427
+ if value < 13:
428
+ return "child"
429
+ if value < 20:
430
+ return "teenage patient"
431
+ decade = min((value // 10) * 10, 90)
432
+ return f"in their {decade}s"
433
+
434
+
435
+ def _join(parts: list[str]) -> str:
436
+ clean = [p for p in (clean_text(part) for part in parts) if p]
437
+ return ", ".join(clean)
438
+
439
+
440
+ def translate_diag(text: str) -> str:
441
+ if not text:
442
+ return ""
443
+ key = text.strip().lower()
444
+ return DIAG_MAP.get(key, text.strip())
445
+
446
+
447
+ def safe_name(value: Any) -> str:
448
+ return re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "na"))[:80]
449
+
450
+
451
+ def parse_args() -> argparse.Namespace:
452
+ parser = argparse.ArgumentParser()
453
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
454
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
455
+ parser.add_argument("--per-group", type=int, default=5)
456
+ parser.add_argument("--seed", type=int, default=20260701)
457
+ parser.add_argument("--thumb", type=int, default=320)
458
+ return parser.parse_args()
459
+
460
+
461
+ if __name__ == "__main__":
462
+ main()
tools/data_processing/quality_control/resize_mode_qc.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build a visual QC sheet comparing center-crop vs aspect-preserving padding."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import io
7
+ import tarfile
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import pandas as pd
12
+ from PIL import Image, ImageDraw, ImageFont
13
+
14
+ import sys
15
+ import types
16
+
17
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
18
+ omegaconf_stub = types.ModuleType("omegaconf")
19
+ omegaconf_stub.DictConfig = object
20
+ sys.modules.setdefault("omegaconf", omegaconf_stub)
21
+ from utils.train_utils import center_crop_arr, resize_pad_arr
22
+
23
+
24
+ DEFAULT_MANIFEST = Path(
25
+ "/data/team/lisicheng/new_data_manifest/"
26
+ "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
27
+ )
28
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/resize_mode_qc_20260702")
29
+
30
+
31
+ def main() -> None:
32
+ args = parse_args()
33
+ args.out.mkdir(parents=True, exist_ok=True)
34
+ df = pd.read_parquet(args.manifest, columns=["image_id", "cohort", "modality", "train_path", "file_path"])
35
+ samples = []
36
+ for (_, _), group in df.groupby(["modality", "cohort"], sort=True):
37
+ samples.append(group.sample(n=min(args.per_group, len(group)), random_state=args.seed))
38
+ sample = pd.concat(samples, ignore_index=True).sort_values(["modality", "cohort", "image_id"])
39
+
40
+ rows = []
41
+ records = []
42
+ for row in sample.to_dict("records"):
43
+ path = str(row.get("train_path") or row.get("file_path"))
44
+ try:
45
+ im = open_image(path).convert("RGB")
46
+ crop = center_crop_arr(im, args.size)
47
+ pad = resize_pad_arr(im, args.size)
48
+ rows.append((row, im, crop, pad))
49
+ records.append({**row, "width": im.width, "height": im.height})
50
+ except Exception as exc:
51
+ records.append({**row, "error": repr(exc)})
52
+ write_sheet(rows, args.out / "resize_mode_qc.jpg", args.size)
53
+ pd.DataFrame(records).to_csv(args.out / "resize_mode_qc.csv", index=False)
54
+ print(f"DONE -> {args.out / 'resize_mode_qc.jpg'} ({len(rows)} images)")
55
+
56
+
57
+ def open_image(path: str) -> Image.Image:
58
+ if "::" in path:
59
+ tar_path, member = path.split("::", 1)
60
+ with tarfile.open(tar_path) as tf:
61
+ fp = tf.extractfile(member)
62
+ if fp is None:
63
+ raise FileNotFoundError(path)
64
+ data = fp.read()
65
+ return Image.open(io.BytesIO(data))
66
+ return Image.open(path)
67
+
68
+
69
+ def write_sheet(rows: list[tuple[dict[str, Any], Image.Image, Image.Image, Image.Image]], out: Path, cell: int) -> None:
70
+ header = 52
71
+ cols = 3
72
+ sheet = Image.new("RGB", (cols * cell, len(rows) * (cell + header)), (20, 20, 20))
73
+ draw = ImageDraw.Draw(sheet)
74
+ font = ImageFont.load_default()
75
+ for r, (meta, original, crop, pad) in enumerate(rows):
76
+ y = r * (cell + header)
77
+ label = f"{meta.get('modality')} | {meta.get('cohort')} | {meta.get('image_id')}"
78
+ draw.text((6, y + 4), label[:140], fill=(235, 235, 235), font=font)
79
+ for c, (name, im) in enumerate([("original", original), ("center_crop", crop), ("resize_pad", pad)]):
80
+ x = c * cell
81
+ draw.text((x + 6, y + 22), name, fill=(210, 210, 210), font=font)
82
+ thumb = fit_thumb(im, cell)
83
+ sheet.paste(thumb, (x, y + header))
84
+ out.parent.mkdir(parents=True, exist_ok=True)
85
+ sheet.save(out, quality=92)
86
+
87
+
88
+ def fit_thumb(im: Image.Image, cell: int) -> Image.Image:
89
+ im = im.copy()
90
+ im.thumbnail((cell, cell), Image.Resampling.LANCZOS)
91
+ canvas = Image.new("RGB", (cell, cell), (0, 0, 0))
92
+ canvas.paste(im, ((cell - im.width) // 2, (cell - im.height) // 2))
93
+ return canvas
94
+
95
+
96
+ def parse_args() -> argparse.Namespace:
97
+ parser = argparse.ArgumentParser()
98
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
99
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
100
+ parser.add_argument("--per-group", type=int, default=2)
101
+ parser.add_argument("--seed", type=int, default=20260702)
102
+ parser.add_argument("--size", type=int, default=320)
103
+ return parser.parse_args()
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
tools/data_processing/report_parsing/attach_labels.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attach clinical captions / dx to the manifest for FILE-labeled cohorts (json/jsonl/xlsx).
2
+ Folder-labeled cohorts (eryuan/eryuan_t17/tongren_95disease/dual/eyfrd6) are already labeled by
3
+ build_manifest (diagnosis_raw=parent dir). Join keys verified by the 2026-06-30 label-schema recon.
4
+
5
+ PII discipline: ONLY clinical findings/impression/dx text -> caption. Names/IDs/DOB/exam-dates/
6
+ doctor-signatures are NEVER read into caption (separate fields, dropped); embedded scheduling/
7
+ signature/boilerplate tails in free text are stripped by clean_caption().
8
+
9
+ All joins are STUDY/scan-level except data0410 (image-level 1:1) and hcw (image-level) -> a scan's
10
+ caption is fanned out to all its frames.
11
+
12
+ Output: adds `caption` + `diagnosis_group` columns -> <manifest>_labeled.parquet
13
+ Usage: /data/team/lisicheng/octdata_venv/bin/python attach_labels.py --manifest .../new_data_manifest.parquet [--only k1,k2]
14
+ """
15
+ import argparse, json, re, os
16
+ from collections import Counter
17
+ from pathlib import Path
18
+ import pandas as pd
19
+ import cohorts as C
20
+
21
+ NFS = "/nfs01/datasetsBackup"
22
+ LBL = {
23
+ "handan": f"{NFS}/ffa/handan_ffa/data.json",
24
+ "chengdu_ffa": f"{NFS}/ffa/chengdu_ffa/visionoph4.jsonl",
25
+ "yinhai_ffa": f"{NFS}/ffa/yinhai_ffa/output2.jsonl",
26
+ "yinhai_bscan": f"{NFS}/pretrainNewDS/BUltrasound/YinhaiBscan/YinhaiBscan.json", # RAW (has findings)
27
+ "xiangya_bscan":f"{NFS}/pretrainNewDS/BUltrasound/XiangyaBscan/xiangyaBUltrasound_cleanedv3.json",
28
+ "chengdu_ubm": f"{NFS}/pretrainNewDS/ubm/ChengduShiyiUBM/ChengdushiyiUBM_cleanedv3.json",
29
+ "yinhai_ubm": f"{NFS}/pretrainNewDS/ubm/YinhaiUBM/YinHaiUBM_cleanedv3.json",
30
+ }
31
+
32
+ _TAIL = re.compile(r'(建议[::]|门诊时间[::]|医[师生]签[名字]|签[名字][::]|医师[::]|检查者|报告医[师生]|TOPCON|Corporation).*$', re.S)
33
+ def clean_caption(t):
34
+ if t is None: return None
35
+ t = str(t).strip()
36
+ if not t or t == "18": return None # chengdu_ubm degenerate
37
+ t = _TAIL.split(t)[0] # drop scheduling/signature tail (PII)
38
+ t = re.sub(r'请结合临床[。.]?\s*$', '', t) # UBM boilerplate
39
+ t = t.replace("&&", " ").replace("\n", " ") # yinhai_ubm per-eye joiner / newlines
40
+ t = re.sub(r'\s+', ' ', t).strip(" >]")
41
+ return t or None
42
+
43
+ def _basename(p): return os.path.basename(str(p))
44
+ def _stem(p): return Path(str(p)).stem
45
+ def _load_array(path, tolerant=False):
46
+ s = open(path, encoding="utf-8", errors="replace").read()
47
+ if tolerant: s = re.sub(r',(\s*[}\]])', r'\1', s) # xiangya malformed trailing commas
48
+ return json.loads(s)
49
+
50
+ # each builder returns (lookup_dict, key_fn) ; lookup value = caption_str OR (caption, dx)
51
+ def b_handan():
52
+ recs = json.load(open(LBL["handan"]))["data"]
53
+ dup = {k for k, c in Counter(r.get("ID号", "").strip() for r in recs if r.get("ID号", "").strip()).items() if c > 1}
54
+ m = {}
55
+ for r in recs:
56
+ i = r.get("ID号", "").strip()
57
+ if not i or i in dup: continue # drop ambiguous/empty
58
+ m[i] = clean_caption(" ".join(x for x in [r.get("影像所见"), r.get("印象")] if x))
59
+ def key(p):
60
+ idp = _basename(p).rsplit("_", 1)[0]
61
+ return idp if idp in m else re.sub(r'\D+$', '', idp) # strip trailing non-digit (e.g. 1809243Coats)
62
+ return m, key
63
+
64
+ def b_chengdu_ffa():
65
+ m = {}
66
+ for r in _load_array(LBL["chengdu_ffa"]):
67
+ cap = clean_caption(r.get("description"))
68
+ dx = ";".join(dict.fromkeys(d for d in (r.get("diagnosis") or []) if d)) or None
69
+ for im in r.get("images", []):
70
+ b = re.split(r'[\\/]', im.get("image_path", ""))[-1] # basename, NO cleanup (mangled names are real)
71
+ if b and b not in m: m[b] = (cap, dx)
72
+ return m, _basename
73
+
74
+ def b_yinhai_ffa():
75
+ recs = [json.loads(l) for l in open(LBL["yinhai_ffa"]) if l.strip()]
76
+ m = {}
77
+ for r in recs:
78
+ f = r.get("file", ""); stem = f[:-4] if f.endswith(".csv") else f
79
+ if stem: m[stem] = clean_caption(r.get("second_column2"))
80
+ return m, lambda p: _basename(p).rsplit("-", 1)[0] # <stem>-<frame>.bmp
81
+
82
+ def b_by_images(path, tolerant=False, ubm_clean=False):
83
+ m = {}
84
+ for r in _load_array(path, tolerant=tolerant):
85
+ cap = r.get("description")
86
+ if ubm_clean and cap and not (cap[:1].isdigit() or ("一" <= cap[:1] <= "鿿")):
87
+ cap = cap[1:] # strip 1 leading junk char (chengdu_ubm)
88
+ cap = clean_caption(cap)
89
+ for im in r.get("images", []):
90
+ b = _basename(re.split(r'[\\/]', im.get("image_path", ""))[-1])
91
+ if b and b not in m: m[b] = cap
92
+ return m, _basename
93
+
94
+ def b_hcw():
95
+ rp = Path(C.EXTRACT_ROOT) / "hcw_fundus" / "fundus" / "fundus_csv"
96
+ frames = [pd.read_excel(rp / x) for x in ["dramdrvo_cleaned.xlsx", "glaucoma_cleaned.xlsx"] if (rp / x).exists()]
97
+ if not frames: print(" [hcw] xlsx missing -> run extract.sh (needs fundus_csv glob)"); return {}, _stem
98
+ lab = pd.concat(frames, ignore_index=True)
99
+ lab["stem"] = lab["image_name"].map(_stem)
100
+ m = {}
101
+ for stem, g in lab.groupby("stem"):
102
+ prim = g[g["is_primary"] == "是"]
103
+ names = ";".join(dict.fromkeys(g["diag_name"].dropna().astype(str)))
104
+ main = (prim.iloc[0] if len(prim) else g.iloc[0]).get("diag_name")
105
+ m[stem] = (clean_caption(names), str(main) if pd.notna(main) else None)
106
+ return m, _stem
107
+
108
+ def b_data0410():
109
+ fp = Path(C.EXTRACT_ROOT) / "data0410_master_fundus" / "data" / "reports_2020_2025_cleaned.xlsx"
110
+ if not fp.exists(): print(" [data0410] xlsx missing -> run extract.sh"); return {}, _basename
111
+ df = pd.read_excel(fp)
112
+ return {str(n): clean_caption(c) for n, c in zip(df["ImageName"], df["Notes_clean"])}, _basename
113
+
114
+ BUILDERS = {
115
+ "handan_fundus": b_handan, "handan_ffa": b_handan,
116
+ "chengdu_ffa": b_chengdu_ffa, "yinhai_ffa": b_yinhai_ffa,
117
+ "yinhai_bscan": lambda: b_by_images(LBL["yinhai_bscan"]),
118
+ "xiangya_bscan": lambda: b_by_images(LBL["xiangya_bscan"], tolerant=True),
119
+ "chengdu_shiyi_ubm": lambda: b_by_images(LBL["chengdu_ubm"], ubm_clean=True),
120
+ "yinhai_ubm": lambda: b_by_images(LBL["yinhai_ubm"], ubm_clean=True),
121
+ "hcw_fundus": b_hcw, "data0410_master_fundus": b_data0410,
122
+ }
123
+
124
+
125
+ def main():
126
+ ap = argparse.ArgumentParser()
127
+ ap.add_argument("--manifest", required=True)
128
+ ap.add_argument("--only", default=None)
129
+ args = ap.parse_args()
130
+ df = pd.read_parquet(args.manifest)
131
+ for col in ("caption", "diagnosis_group"):
132
+ if col not in df: df[col] = None
133
+ only = set(args.only.split(",")) if args.only else None
134
+
135
+ for cohort, builder in BUILDERS.items():
136
+ if only and cohort not in only: continue
137
+ sub = df[df["cohort"] == cohort]
138
+ if not len(sub): continue
139
+ try:
140
+ lookup, key_fn = builder()
141
+ except Exception as e:
142
+ print(f"[{cohort}] builder FAILED: {e}"); continue
143
+ # vectorized: build aligned Series on sub.index (preserves df index) -> O(N), not O(N^2)
144
+ caps, dxs = [], []
145
+ for k in sub["file_path"].map(key_fn):
146
+ v = lookup.get(k)
147
+ if v is None: caps.append(None); dxs.append(None); continue
148
+ c, d = v if isinstance(v, tuple) else (v, None)
149
+ caps.append(c); dxs.append(d)
150
+ caps = pd.Series(caps, index=sub.index); dxs = pd.Series(dxs, index=sub.index)
151
+ df.loc[sub.index, "caption"] = caps
152
+ df.loc[sub.index, "diagnosis_group"] = dxs
153
+ nhit = int((caps.notna() | dxs.notna()).sum())
154
+ print(f"[{cohort}] {len(sub)} imgs -> {nhit} captioned ({100*nhit/max(1,len(sub)):.0f}%)")
155
+
156
+ outp = args.manifest.replace(".parquet", "_labeled.parquet")
157
+ df.to_parquet(outp, index=False)
158
+ cov = df["caption"].notna().sum()
159
+ print(f"\n=== {len(df)} rows, {cov} with caption -> {outp} ===")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
tools/data_processing/report_parsing/batch_retrieve_reports.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import sys
5
+ from collections import Counter
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import yaml
12
+ from PIL import Image
13
+ from torch.utils.data import DataLoader, Dataset
14
+ from torchvision import transforms
15
+ from tqdm import tqdm
16
+ from transformers import BertTokenizer
17
+
18
+
19
+ PROJECT_ROOT = Path(__file__).resolve().parents[3]
20
+ if str(PROJECT_ROOT) not in sys.path:
21
+ sys.path.insert(0, str(PROJECT_ROOT))
22
+
23
+ from siglip.model import OcularRoBERTaSigLIP, clean_state_dict
24
+
25
+
26
+ IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}
27
+
28
+
29
+ def parse_args():
30
+ parser = argparse.ArgumentParser(
31
+ description=(
32
+ "Retrieve the most compatible report texts for a folder of OCT images. "
33
+ "This model ranks existing reports; it does not generate new text."
34
+ )
35
+ )
36
+ parser.add_argument("--image-dir", required=True, help="Directory containing OCT images")
37
+ parser.add_argument(
38
+ "--config",
39
+ default=str(PROJECT_ROOT / "siglip" / "train_config.yaml"),
40
+ help="Phase 2 training config",
41
+ )
42
+ parser.add_argument("--checkpoint", default=None, help="Phase 2 checkpoint")
43
+ parser.add_argument(
44
+ "--ijepa-path",
45
+ default=None,
46
+ help="Optional Phase 1 initialization; normally omit for a complete Phase 2 checkpoint",
47
+ )
48
+ parser.add_argument("--report-bank", default=None, help="XLSX/CSV containing candidate report texts")
49
+ parser.add_argument("--text-column", default=None)
50
+ parser.add_argument("--image-column", default=None)
51
+ parser.add_argument("--text-model-name", default=None)
52
+ parser.add_argument("--hf-cache-dir", default=None)
53
+ parser.add_argument("--local-files-only", action="store_true", default=None)
54
+ parser.add_argument("--allow-download", action="store_true")
55
+ parser.add_argument("--output-dir", default="phase2_retrieval_results")
56
+ parser.add_argument("--top-k", type=int, default=5)
57
+ parser.add_argument("--image-batch-size", type=int, default=64)
58
+ parser.add_argument("--text-batch-size", type=int, default=256)
59
+ parser.add_argument("--retrieval-chunk-size", type=int, default=16384)
60
+ parser.add_argument("--num-workers", type=int, default=8)
61
+ parser.add_argument("--precision", choices=["bf16", "fp16", "fp32"], default="bf16")
62
+ parser.add_argument("--device", default=None)
63
+ parser.add_argument("--num-images", type=int, default=0, help="0 uses every image")
64
+ parser.add_argument("--seed", type=int, default=42)
65
+ parser.add_argument("--non-recursive", action="store_true")
66
+ parser.add_argument("--write-text-files", action="store_true")
67
+ parser.add_argument("--rebuild-text-cache", action="store_true")
68
+ return parser.parse_args()
69
+
70
+
71
+ def load_config(path):
72
+ with open(path, "r", encoding="utf-8") as f:
73
+ return yaml.safe_load(f)
74
+
75
+
76
+ def resolve_args(args, config):
77
+ data_cfg = config.get("data", {})
78
+ model_cfg = config.get("model", {})
79
+ checkpoint_cfg = config.get("checkpoint", {})
80
+
81
+ output_root = Path(checkpoint_cfg.get("output_dir", PROJECT_ROOT / "BioCliFM"))
82
+ run_name = checkpoint_cfg.get("run_name", "phase2")
83
+ default_checkpoint = output_root / "checkpoints" / run_name / "siglip_best.pth"
84
+
85
+ args.checkpoint = args.checkpoint or str(default_checkpoint)
86
+ args.report_bank = args.report_bank or data_cfg.get("excel_path")
87
+ args.text_column = args.text_column or data_cfg.get("text_col", "Notes_clean")
88
+ args.image_column = args.image_column or data_cfg.get("image_col", "ImageName")
89
+ args.text_model_name = args.text_model_name or model_cfg.get(
90
+ "text_model_name", "hfl/chinese-roberta-wwm-ext-large"
91
+ )
92
+ args.hf_cache_dir = args.hf_cache_dir or model_cfg.get("hf_cache_dir")
93
+ if args.allow_download:
94
+ args.local_files_only = False
95
+ elif args.local_files_only is None:
96
+ args.local_files_only = model_cfg.get("local_files_only", False)
97
+ args.embed_dim = model_cfg.get("embed_dim", 512)
98
+ args.max_length = data_cfg.get("max_length", 256)
99
+ args.input_size = data_cfg.get("input_size", 224)
100
+
101
+ required_paths = {
102
+ "image directory": args.image_dir,
103
+ "Phase 2 checkpoint": args.checkpoint,
104
+ "report bank": args.report_bank,
105
+ }
106
+ for label, value in required_paths.items():
107
+ if not value or not Path(value).expanduser().exists():
108
+ raise FileNotFoundError(f"{label} does not exist: {value}")
109
+
110
+ if args.ijepa_path and not Path(args.ijepa_path).expanduser().exists():
111
+ raise FileNotFoundError(f"Phase 1 checkpoint does not exist: {args.ijepa_path}")
112
+ if args.top_k <= 0:
113
+ raise ValueError("--top-k must be greater than zero")
114
+ return args
115
+
116
+
117
+ def read_table(path, columns=None, nrows=None):
118
+ path = Path(path)
119
+ if path.suffix.lower() == ".csv":
120
+ return pd.read_csv(path, usecols=columns, nrows=nrows)
121
+ return pd.read_excel(path, usecols=columns, nrows=nrows)
122
+
123
+
124
+ def load_report_bank(path, text_column, image_column):
125
+ header = read_table(path, columns=None, nrows=0).columns
126
+ if text_column not in header:
127
+ raise KeyError(f"Text column '{text_column}' not found. Available columns: {list(header)}")
128
+
129
+ columns = [text_column]
130
+ has_image_column = image_column in header
131
+ if has_image_column:
132
+ columns.append(image_column)
133
+ df = read_table(path, columns=columns)
134
+
135
+ texts = []
136
+ text_to_index = {}
137
+ ground_truth = {}
138
+ skipped = 0
139
+
140
+ for _, row in df.iterrows():
141
+ raw_text = row.get(text_column)
142
+ if pd.isna(raw_text):
143
+ skipped += 1
144
+ continue
145
+ text = str(raw_text).strip()
146
+ if not text:
147
+ skipped += 1
148
+ continue
149
+ if text not in text_to_index:
150
+ text_to_index[text] = len(texts)
151
+ texts.append(text)
152
+
153
+ if has_image_column:
154
+ raw_image = row.get(image_column)
155
+ if not pd.isna(raw_image):
156
+ image_key = Path(str(raw_image).strip()).name
157
+ if image_key:
158
+ ground_truth.setdefault(image_key, set()).add(text)
159
+
160
+ if not texts:
161
+ raise RuntimeError(f"No valid reports found in {path}")
162
+ print(f"[Info] Report bank: rows={len(df)}, unique_reports={len(texts)}, skipped={skipped}")
163
+ if has_image_column:
164
+ print(f"[Info] Ground-truth image names available: {len(ground_truth)}")
165
+ return texts, ground_truth
166
+
167
+
168
+ def discover_images(image_dir, recursive, num_images, seed):
169
+ image_dir = Path(image_dir).expanduser().resolve()
170
+ iterator = image_dir.rglob("*") if recursive else image_dir.glob("*")
171
+ paths = sorted(path for path in iterator if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS)
172
+ if not paths:
173
+ raise RuntimeError(f"No supported images found under {image_dir}")
174
+ if num_images > 0 and len(paths) > num_images:
175
+ generator = torch.Generator().manual_seed(seed)
176
+ indices = torch.randperm(len(paths), generator=generator)[:num_images].tolist()
177
+ paths = [paths[index] for index in sorted(indices)]
178
+ print(f"[Info] OCT images selected: {len(paths)}")
179
+ return image_dir, paths
180
+
181
+
182
+ class OCTImageDataset(Dataset):
183
+ def __init__(self, image_root, image_paths, transform):
184
+ self.image_root = image_root
185
+ self.image_paths = image_paths
186
+ self.transform = transform
187
+
188
+ def __len__(self):
189
+ return len(self.image_paths)
190
+
191
+ def __getitem__(self, index):
192
+ path = self.image_paths[index]
193
+ try:
194
+ with Image.open(path) as image:
195
+ tensor = self.transform(image.convert("RGB"))
196
+ except Exception as exc:
197
+ raise RuntimeError(f"Failed to read image: {path}") from exc
198
+ return tensor, str(path.relative_to(self.image_root)), path.name
199
+
200
+
201
+ def autocast_context(device, precision):
202
+ enabled = device.type == "cuda" and precision != "fp32"
203
+ dtype = torch.bfloat16 if precision == "bf16" else torch.float16
204
+ return torch.amp.autocast(device_type=device.type, dtype=dtype, enabled=enabled)
205
+
206
+
207
+ def checkpoint_signature(path):
208
+ path = Path(path).expanduser().resolve()
209
+ stat = path.stat()
210
+ return {"path": str(path), "size": stat.st_size, "mtime_ns": stat.st_mtime_ns}
211
+
212
+
213
+ def load_phase2_model(args, device):
214
+ checkpoint = torch.load(args.checkpoint, map_location="cpu")
215
+ state_dict = clean_state_dict(checkpoint.get("model_state_dict", checkpoint))
216
+ projection_weight = state_dict.get("visual_projection.weight")
217
+ embed_dim = projection_weight.shape[0] if projection_weight is not None else args.embed_dim
218
+
219
+ model = OcularRoBERTaSigLIP(
220
+ ijepa_ckpt_path=args.ijepa_path,
221
+ ijepa_encoder_source="target",
222
+ text_model_name=args.text_model_name,
223
+ embed_dim=embed_dim,
224
+ hf_cache_dir=args.hf_cache_dir,
225
+ local_files_only=args.local_files_only,
226
+ )
227
+ incompatible = model.load_state_dict(state_dict, strict=True)
228
+ if incompatible.missing_keys or incompatible.unexpected_keys:
229
+ raise RuntimeError(
230
+ f"Checkpoint mismatch: missing={incompatible.missing_keys}, "
231
+ f"unexpected={incompatible.unexpected_keys}"
232
+ )
233
+ model.to(device).eval()
234
+ epoch = checkpoint.get("epoch", "unknown")
235
+ loss = checkpoint.get("loss", "unknown")
236
+ print(f"[Info] Loaded Phase 2 checkpoint: epoch={epoch}, loss={loss}, embed_dim={embed_dim}")
237
+ if args.ijepa_path is None:
238
+ print("[Info] Phase 1 is already incorporated in the complete Phase 2 vision tower.")
239
+ return model
240
+
241
+
242
+ def encode_text_bank(model, tokenizer, texts, args, device, output_dir):
243
+ cache_path = output_dir / "text_bank_embeddings.pt"
244
+ expected_meta = {
245
+ "checkpoint": checkpoint_signature(args.checkpoint),
246
+ "report_bank": str(Path(args.report_bank).expanduser().resolve()),
247
+ "text_column": args.text_column,
248
+ "text_model_name": args.text_model_name,
249
+ "max_length": args.max_length,
250
+ "num_texts": len(texts),
251
+ }
252
+ if cache_path.exists() and not args.rebuild_text_cache:
253
+ cache = torch.load(cache_path, map_location="cpu")
254
+ if cache.get("metadata") == expected_meta and cache.get("texts") == texts:
255
+ print(f"[Info] Reusing text embedding cache: {cache_path}")
256
+ return cache["embeddings"].float()
257
+ print("[Info] Text embedding cache is stale; rebuilding it.")
258
+
259
+ chunks = []
260
+ for start in tqdm(range(0, len(texts), args.text_batch_size), desc="Encoding report bank"):
261
+ batch_texts = texts[start:start + args.text_batch_size]
262
+ inputs = tokenizer(
263
+ batch_texts,
264
+ padding=True,
265
+ truncation=True,
266
+ max_length=args.max_length,
267
+ return_tensors="pt",
268
+ ).to(device)
269
+ with torch.inference_mode(), autocast_context(device, args.precision):
270
+ embeddings = F.normalize(
271
+ model.encode_text(inputs["input_ids"], inputs["attention_mask"]), dim=-1
272
+ )
273
+ chunks.append(embeddings.float().cpu())
274
+
275
+ embeddings = torch.cat(chunks, dim=0)
276
+ torch.save({"metadata": expected_meta, "texts": texts, "embeddings": embeddings}, cache_path)
277
+ print(f"[Info] Saved text embedding cache: {cache_path}")
278
+ return embeddings
279
+
280
+
281
+ def chunked_topk(image_embeddings, text_embeddings, top_k, chunk_size, device):
282
+ batch_size = image_embeddings.shape[0]
283
+ best_scores = torch.full((batch_size, top_k), -math.inf, device=device)
284
+ best_indices = torch.full((batch_size, top_k), -1, dtype=torch.long, device=device)
285
+
286
+ for start in range(0, text_embeddings.shape[0], chunk_size):
287
+ text_chunk = text_embeddings[start:start + chunk_size].to(device, non_blocking=True)
288
+ scores = image_embeddings @ text_chunk.t()
289
+ local_k = min(top_k, scores.shape[1])
290
+ chunk_scores, chunk_indices = scores.topk(local_k, dim=1)
291
+ chunk_indices += start
292
+
293
+ combined_scores = torch.cat([best_scores, chunk_scores], dim=1)
294
+ combined_indices = torch.cat([best_indices, chunk_indices], dim=1)
295
+ best_scores, positions = combined_scores.topk(top_k, dim=1)
296
+ best_indices = combined_indices.gather(1, positions)
297
+
298
+ return best_scores.float().cpu(), best_indices.cpu()
299
+
300
+
301
+ def retrieve_reports(model, image_loader, text_embeddings, texts, ground_truth, args, device):
302
+ results = []
303
+ scale = model.criterion.t_prime.detach().exp().clamp(max=model.criterion.max_temperature).float().cpu()
304
+ bias = model.criterion.b.detach().float().cpu()
305
+ top_k = min(args.top_k, len(texts))
306
+
307
+ for images, relative_paths, basenames in tqdm(image_loader, desc="Retrieving reports"):
308
+ images = images.to(device, non_blocking=True)
309
+ with torch.inference_mode(), autocast_context(device, args.precision):
310
+ image_embeddings = F.normalize(model.encode_image(images), dim=-1)
311
+ cosine_scores, indices = chunked_topk(
312
+ image_embeddings.float(), text_embeddings, top_k, args.retrieval_chunk_size, device
313
+ )
314
+
315
+ for row_index, (relative_path, basename) in enumerate(zip(relative_paths, basenames)):
316
+ candidates = []
317
+ for rank in range(top_k):
318
+ text_index = indices[row_index, rank].item()
319
+ cosine = cosine_scores[row_index, rank].item()
320
+ logit = cosine * scale.item() + bias.item()
321
+ candidates.append({
322
+ "rank": rank + 1,
323
+ "report": texts[text_index],
324
+ "cosine_similarity": cosine,
325
+ "siglip_logit": logit,
326
+ "sigmoid_score": torch.sigmoid(torch.tensor(logit)).item(),
327
+ })
328
+
329
+ expected = ground_truth.get(basename, set())
330
+ expected_rank = next(
331
+ (candidate["rank"] for candidate in candidates if candidate["report"] in expected),
332
+ None,
333
+ )
334
+ results.append({
335
+ "image_path": relative_path,
336
+ "image_name": basename,
337
+ "retrieved_report": candidates[0]["report"],
338
+ "top1_cosine": candidates[0]["cosine_similarity"],
339
+ "top1_siglip_logit": candidates[0]["siglip_logit"],
340
+ "top1_sigmoid_score": candidates[0]["sigmoid_score"],
341
+ "top1_top2_margin": (
342
+ candidates[0]["cosine_similarity"] - candidates[1]["cosine_similarity"]
343
+ if len(candidates) > 1 else None
344
+ ),
345
+ "ground_truth_reports": sorted(expected),
346
+ "ground_truth_rank_at_k": expected_rank,
347
+ "candidates": candidates,
348
+ })
349
+ return results
350
+
351
+
352
+ def save_results(results, output_dir, top_k, write_text_files):
353
+ jsonl_path = output_dir / "retrieval_results.jsonl"
354
+ with open(jsonl_path, "w", encoding="utf-8") as f:
355
+ for result in results:
356
+ f.write(json.dumps(result, ensure_ascii=False) + "\n")
357
+
358
+ rows = []
359
+ for result in results:
360
+ row = {
361
+ "image_path": result["image_path"],
362
+ "image_name": result["image_name"],
363
+ "retrieved_report": result["retrieved_report"],
364
+ "top1_cosine": result["top1_cosine"],
365
+ "top1_siglip_logit": result["top1_siglip_logit"],
366
+ "top1_sigmoid_score": result["top1_sigmoid_score"],
367
+ "top1_top2_margin": result["top1_top2_margin"],
368
+ "ground_truth_report": " || ".join(result["ground_truth_reports"]),
369
+ "ground_truth_rank_at_k": result["ground_truth_rank_at_k"],
370
+ }
371
+ for candidate in result["candidates"][:top_k]:
372
+ rank = candidate["rank"]
373
+ row[f"report_{rank}"] = candidate["report"]
374
+ row[f"cosine_{rank}"] = candidate["cosine_similarity"]
375
+ row[f"sigmoid_score_{rank}"] = candidate["sigmoid_score"]
376
+ rows.append(row)
377
+
378
+ csv_path = output_dir / "retrieval_results.csv"
379
+ pd.DataFrame(rows).to_csv(csv_path, index=False, encoding="utf-8-sig")
380
+
381
+ if write_text_files:
382
+ reports_dir = output_dir / "reports"
383
+ reports_dir.mkdir(parents=True, exist_ok=True)
384
+ for index, result in enumerate(results, start=1):
385
+ safe_stem = Path(result["image_name"]).stem.replace("/", "_").replace("\\", "_")
386
+ report_path = reports_dir / f"{index:04d}_{safe_stem}.txt"
387
+ report_path.write_text(result["retrieved_report"] + "\n", encoding="utf-8")
388
+
389
+ return csv_path, jsonl_path
390
+
391
+
392
+ def print_summary(results, top_k):
393
+ top1_scores = torch.tensor([item["top1_cosine"] for item in results])
394
+ margins = [item["top1_top2_margin"] for item in results if item["top1_top2_margin"] is not None]
395
+ evaluated = [item for item in results if item["ground_truth_reports"]]
396
+ report_counts = Counter(item["retrieved_report"] for item in results)
397
+ most_common_report, most_common_count = report_counts.most_common(1)[0]
398
+
399
+ print("\n=== Phase 1 + Phase 2 OCT Report Retrieval Summary ===")
400
+ print(f"Images: {len(results)}")
401
+ print(
402
+ "Top-1 cosine mean/min/max: "
403
+ f"{top1_scores.mean().item():.4f} / {top1_scores.min().item():.4f} / {top1_scores.max().item():.4f}"
404
+ )
405
+ if margins:
406
+ print(f"Top-1/Top-2 cosine margin mean: {sum(margins) / len(margins):.4f}")
407
+ print(f"Unique Top-1 reports: {len(report_counts)}/{len(results)}")
408
+ print(
409
+ "Most frequent Top-1 report share: "
410
+ f"{most_common_count}/{len(results)} ({most_common_count / len(results):.2%})"
411
+ )
412
+ print(f"Most frequent Top-1 report: {most_common_report}")
413
+ if evaluated:
414
+ recall1 = sum(item["ground_truth_rank_at_k"] == 1 for item in evaluated) / len(evaluated)
415
+ recallk = sum(item["ground_truth_rank_at_k"] is not None for item in evaluated) / len(evaluated)
416
+ reciprocal_ranks = [
417
+ 1.0 / item["ground_truth_rank_at_k"] if item["ground_truth_rank_at_k"] else 0.0
418
+ for item in evaluated
419
+ ]
420
+ print(f"Ground-truth matched images: {len(evaluated)}/{len(results)}")
421
+ print(f"Recall@1: {recall1:.4f}")
422
+ print(f"Recall@{top_k}: {recallk:.4f}")
423
+ print(f"MRR@{top_k}: {sum(reciprocal_ranks) / len(reciprocal_ranks):.4f}")
424
+ else:
425
+ print("Ground-truth metrics: unavailable (image names were not found in the report table).")
426
+
427
+
428
+ def main():
429
+ args = parse_args()
430
+ args = resolve_args(args, load_config(args.config))
431
+ device = torch.device(args.device or ("cuda:0" if torch.cuda.is_available() else "cpu"))
432
+ output_dir = Path(args.output_dir).expanduser().resolve()
433
+ output_dir.mkdir(parents=True, exist_ok=True)
434
+
435
+ print("[Info] Mode: report retrieval/ranking, not free-text generation")
436
+ print(f"[Info] Device={device}, precision={args.precision}, local_files_only={args.local_files_only}")
437
+ texts, ground_truth = load_report_bank(args.report_bank, args.text_column, args.image_column)
438
+ image_root, image_paths = discover_images(
439
+ args.image_dir, not args.non_recursive, args.num_images, args.seed
440
+ )
441
+
442
+ model = load_phase2_model(args, device)
443
+ tokenizer = BertTokenizer.from_pretrained(
444
+ args.text_model_name,
445
+ cache_dir=args.hf_cache_dir,
446
+ local_files_only=args.local_files_only,
447
+ )
448
+ text_embeddings = encode_text_bank(model, tokenizer, texts, args, device, output_dir)
449
+
450
+ transform = transforms.Compose([
451
+ transforms.Resize((args.input_size, args.input_size)),
452
+ transforms.ToTensor(),
453
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
454
+ ])
455
+ image_loader = DataLoader(
456
+ OCTImageDataset(image_root, image_paths, transform),
457
+ batch_size=args.image_batch_size,
458
+ shuffle=False,
459
+ num_workers=args.num_workers,
460
+ pin_memory=device.type == "cuda",
461
+ )
462
+ results = retrieve_reports(model, image_loader, text_embeddings, texts, ground_truth, args, device)
463
+ csv_path, jsonl_path = save_results(results, output_dir, args.top_k, args.write_text_files)
464
+ print_summary(results, min(args.top_k, len(texts)))
465
+ print(f"[Info] CSV: {csv_path}")
466
+ print(f"[Info] JSONL: {jsonl_path}")
467
+
468
+
469
+ if __name__ == "__main__":
470
+ main()
tools/data_processing/report_parsing/cohorts.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verified cohort registry for the h100 cross-center new-data consolidation (2026-06-30).
2
+
3
+ Single source of truth, encoding the 11-agent read-only recon (see memory reference_h100_newdata).
4
+ HARD RULES baked in: originals on /nfs01 are READ-ONLY and NEVER modified/deleted. Archives
5
+ extract ONLY to EXTRACT_ROOT (work dir on /data). Already-extracted dirs are read in place.
6
+ Dedup/skip is done at MANIFEST level (drop rows), never by touching files.
7
+
8
+ Each cohort dict:
9
+ key unique cohort id (also the manifest `cohort` namespace)
10
+ modality fundus_color | octa | ffa | bscan_us | ubm | uwf
11
+ center hospital/source (for multi-center splits)
12
+ src path to the extracted dir OR the archive
13
+ comp none | zip | targz | rar5 | 7z (archive type if not extracted)
14
+ extracted True -> read `src` in place (0 disk); False -> extract to EXTRACT_ROOT/key
15
+ extract_glob optional member filter for selective extraction (e.g. images only)
16
+ exts image extensions to enumerate
17
+ label_kind folder | json | jsonl | xlsx | none
18
+ label_path label file (abs), or None (folder labels come from dir names)
19
+ pii none | low | t1 (t1 = must strip identifiers before any export; see register)
20
+ dedup_group cohorts sharing a group are cross-checked for duplicates
21
+ role train | external_test (external_test = held out, never trained)
22
+ note
23
+ """
24
+ import os
25
+
26
+ EXTRACT_ROOT = "/data/team/lisicheng/new_data_extracted" # all extraction lands here (/data, 2.9T free); /nfs01 is read-only
27
+ WORK = "/data/team/lisicheng"
28
+ NFS_BACKUP = "/nfs01/datasetsBackup"
29
+ NFS_FQ = "/nfs01/FQ_Datasets/data"
30
+ DATASETS = "/data/datasets"
31
+ UNRAR = "/data/team/lisicheng/miniconda3/envs/ocr/bin/unrar" # not on PATH; full path
32
+
33
+ IMG_EXTS = (".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp")
34
+
35
+
36
+ def read_path(c):
37
+ """Where images are actually read from."""
38
+ return c["src"] if c.get("extracted") else os.path.join(EXTRACT_ROOT, c["key"])
39
+
40
+
41
+ # ----------------------------------------------------------------------------- COHORTS
42
+ COHORTS = [
43
+ # ===================== FUNDUS (color fundus photography) =====================
44
+ dict(key="fundus90wer", modality="fundus_color", center="mixed_unlabeled",
45
+ src=f"{DATASETS}/fundus90wER", comp="none", extracted=True, exts=(".png", ".jpg"),
46
+ label_kind="none", label_path=None, pii="t1", dedup_group="fundus_pool", role="train",
47
+ note="899,266 (verified). Chinese names in filenames -> t1 (filename PII only, not in pixels). md5 in cleaning_report usable as dedup key."),
48
+ dict(key="fq_rawfundus", modality="fundus_color", center="fq_unlabeled",
49
+ src=f"{NFS_FQ}/rawFundus", comp="none", extracted=True, exts=(".png",),
50
+ label_kind="none", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
51
+ note="208,138 (verified). <id>-<n>.png. SKIP rawFundus_predicted (same imgs, quality-resorted)."),
52
+ dict(key="fq_testfundus", modality="fundus_color", center="fq_unlabeled",
53
+ src=f"{NFS_FQ}/testFundus", comp="none", extracted=True, exts=(".png",),
54
+ label_kind="none", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
55
+ note="52,034 (verified). SKIP testFundus_predicted."),
56
+ dict(key="fq_validfundus", modality="fundus_color", center="fq_unlabeled",
57
+ src=f"{NFS_FQ}/validFundus", comp="none", extracted=True, exts=(".png",),
58
+ label_kind="folder", label_path=None, pii="low", dedup_group="fq_tongren_idname", role="train",
59
+ note="4,000 (verified). quality=gradable (whole-dir tag)."),
60
+ dict(key="eryuan_t17_fundus", modality="fundus_color", center="eryuan",
61
+ src=f"{NFS_FQ}/eryuanFundusT17RDCls", comp="none", extracted=True, exts=(".tif",),
62
+ label_kind="folder", label_path=None, pii="low", dedup_group="eryuan_pool", role="train",
63
+ note="31,621 (verified). 17 disease classes; has train/val/test -> reserve its test split as INTERNAL test. class = immediate parent dir."),
64
+ dict(key="tongren_fundus", modality="fundus_color", center="tongren",
65
+ src=f"{WORK}/Dataser/shards_tongren", comp="none", extracted=True, exts=(".png",),
66
+ label_kind="json", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
67
+ 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)."),
68
+ dict(key="tongren_external_fundus", modality="fundus_color", center="tongren",
69
+ src=f"{NFS_BACKUP}/同仁/external.zip", comp="zip", extracted=False, exts=(".png",),
70
+ label_kind="none", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
71
+ note="209,091 (verified). 99.5% SAME PATIENTS as tongren_fundus but 0 same-file -> OK as extra TRAIN, NEVER as eval (leakage)."),
72
+ dict(key="tongren_95disease_fundus", modality="fundus_color", center="tongren",
73
+ src=f"{NFS_BACKUP}/tr/tr1695L2/tongren16G95DFundus", comp="none", extracted=True, exts=(".png",),
74
+ label_kind="folder", label_path=None, pii="low", dedup_group="tongren_pool", role="train",
75
+ 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."),
76
+ dict(key="eryuan_fundus", modality="fundus_color", center="eryuan",
77
+ src=f"{NFS_BACKUP}/data0410/eryuan.zip", comp="zip", extracted=False, exts=(".tif", ".png"),
78
+ label_kind="folder", label_path=None, pii="low", dedup_group="eryuan_pool", role="train",
79
+ note="19,599 (verified): 4 classes AMD/DR/Normal/RVO (NOT 17 as md said). SKIP eryuan_split (subset). dedup vs data0410_master."),
80
+ dict(key="dual_comorbidity_fundus", modality="fundus_color", center="data0410",
81
+ src=f"{NFS_BACKUP}/data0410/Dual_comornidity.tar.gz", comp="targz", extracted=False, exts=(".png",),
82
+ label_kind="folder", label_path=None, pii="low", dedup_group="data0410_pool", role="train",
83
+ note="~12k unique (24,120 entries = 6-class scheme + 4-class scheme of SAME pool). Keep ONE scheme in manifest. hypertension comorbidity classes."),
84
+ dict(key="hcw_fundus", modality="fundus_color", center="hcw",
85
+ src=f"{NFS_BACKUP}/data0410/fundus_hcw.zip", comp="zip", extracted=False, exts=(".tif", ".png"),
86
+ extract_glob="fundus/fundus_img/*", label_kind="xlsx", label_path=None, pii="low",
87
+ dedup_group="data0410_pool", role="train",
88
+ note="~15,503 imgs ONLY (extract_glob excludes 150G .pth + code!). dx-pairing xlsx keyed by image_name."),
89
+ dict(key="data0410_master_fundus", modality="fundus_color", center="data0410",
90
+ src=f"{NFS_BACKUP}/data0410/data.tar.gz", comp="targz", extracted=False, exts=(".png", ".jpg"),
91
+ label_kind="xlsx", label_path=None, pii="t1", dedup_group="data0410_pool", role="train",
92
+ 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."),
93
+ dict(key="eyfrd6_fundus", modality="fundus_color", center="eryuan",
94
+ src=f"{DATASETS}/eyFRDCls", comp="none", extracted=True, exts=(".tif",),
95
+ label_kind="folder", label_path=None, pii="low", dedup_group="fundus_pool", role="train",
96
+ note="~645. 6 classes CSC/ERM/MH/RAO/RD/VKH (has train/val/test). tiny."),
97
+ dict(key="handan_fundus", modality="fundus_color", center="handan",
98
+ src=f"{NFS_BACKUP}/ffa/handan_ffa/only_image", comp="none", extracted=True, exts=(".png",),
99
+ label_kind="json", label_path=f"{NFS_BACKUP}/ffa/handan_ffa/data.json", pii="t1",
100
+ dedup_group="handan", role="external_test",
101
+ note="6,432 fundus = filenames ending _1/_2 ONLY (must filter by suffix at enumerate). HELD OUT (邯郸 external). data.json 印象 dx; strip 姓名/年龄/检查日期/ID号."),
102
+
103
+ # ===================== OCTA =====================
104
+ dict(key="octbuckets_octa", modality="octa", center="octbuckets",
105
+ src=f"{WORK}/Dataser/shards_oct", comp="none", extracted=True, exts=(".png",),
106
+ label_kind="json", label_path=None, pii="none", dedup_group="octa", role="train",
107
+ 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."),
108
+
109
+ # ===================== FFA (fluorescein angiography) -- NEW modality =====================
110
+ dict(key="handan_ffa", modality="ffa", center="handan",
111
+ src=f"{NFS_BACKUP}/ffa/handan_ffa/only_image", comp="none", extracted=True, exts=(".png",),
112
+ label_kind="json", label_path=f"{NFS_BACKUP}/ffa/handan_ffa/data.json", pii="t1",
113
+ dedup_group="handan", role="external_test",
114
+ note="23,212 FFA = filenames _3 and higher suffix (filter by suffix). HELD OUT (邯郸 external). 3,226 study impressions; strip PII."),
115
+ dict(key="chengdu_ffa", modality="ffa", center="chengdu",
116
+ src=f"{NFS_BACKUP}/ffa/chengdu_ffa/jpg", comp="none", extracted=True, exts=(".png",),
117
+ label_kind="jsonl", label_path=f"{NFS_BACKUP}/ffa/chengdu_ffa/visionoph4.jsonl", pii="low",
118
+ dedup_group="chengdu_ffa", role="external_test",
119
+ 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."),
120
+ dict(key="yinhai_ffa", modality="ffa", center="yinhai",
121
+ src=f"{NFS_BACKUP}/ffa/yinhai_ffa/jpg", comp="none", extracted=True, exts=(".bmp",),
122
+ label_kind="jsonl", label_path=f"{NFS_BACKUP}/ffa/yinhai_ffa/output2.jsonl", pii="t1",
123
+ dedup_group="yinhai_ffa", role="train",
124
+ note="1,058 BMP (dir misnamed 'jpg', holds .bmp). output2.jsonl 拟诊报告; strip 姓名+P-ID+签名."),
125
+ dict(key="eryuan_ffa", modality="ffa", center="eryuan",
126
+ src=f"{NFS_BACKUP}/ffa/Final_eryuan_FFA/FFA", comp="none", extracted=True, exts=(".tif",),
127
+ label_kind="none", label_path=None, pii="low", dedup_group="eryuan_ffa", role="train",
128
+ note="18,543 tif (verified). SKIP the redundant 72.5G Final_eryuan_FFA.zip. no labels."),
129
+
130
+ # ===================== B-scan ocular ultrasound -- NEW modality =====================
131
+ dict(key="yinhai_bscan", modality="bscan_us", center="yinhai",
132
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/YinhaiBscan", comp="none", extracted=True, exts=(".png",),
133
+ label_kind="json", label_path=None, pii="low", dedup_group="yinhai_bscan", role="train",
134
+ note="71,289 (verified). images in image/ subdir. Use RAW json (超声所见 findings); cleanedv3 nulls findings. no name/dob."),
135
+ dict(key="xiangya_bscan", modality="bscan_us", center="xiangya",
136
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/XiangyaBscan", comp="none", extracted=True, exts=(".bmp",),
137
+ label_kind="json", label_path=None, pii="t1", dedup_group="xiangya_bscan", role="train",
138
+ note="33,740 (verified) bmp in image/. cleanedv3.json 4,939 records: findings + name/dob/examdate (STRIP)."),
139
+ dict(key="chengdu_bscan", modality="bscan_us", center="chengdu",
140
+ src=f"{NFS_BACKUP}/pretrainNewDS/BUltrasound/chengdu_Bscan", comp="none", extracted=True, exts=(".jpg",),
141
+ label_kind="none", label_path=None, pii="none", dedup_group="chengdu_bscan", role="train",
142
+ note="8,726 (verified) jpg flat. no labels."),
143
+
144
+ # ===================== UBM (ultrasound biomicroscopy) -- NEW modality =====================
145
+ dict(key="chengdu_shiyi_ubm", modality="ubm", center="chengdu",
146
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/ChengduShiyiUBM", comp="none", extracted=True, exts=(".png",),
147
+ label_kind="json", label_path=None, pii="low", dedup_group="chengdu_ubm", role="train",
148
+ note="236,028 (verified) png in image/. Use cleanedv3 json (clinical report; raw json has corrupted blobs/false-PII)."),
149
+ dict(key="yinhai_ubm", modality="ubm", center="yinhai",
150
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/YinhaiUBM", comp="none", extracted=True, exts=(".png",),
151
+ label_kind="json", label_path=None, pii="low", dedup_group="yinhai_ubm", role="train",
152
+ note="83,750 (verified). cleanedv3 clinical text."),
153
+ dict(key="eryuan_ubm", modality="ubm", center="eryuan",
154
+ src=f"{NFS_BACKUP}/pretrainNewDS/ubm/Final_eryuan_ubm", comp="none", extracted=True, exts=(".tif",),
155
+ label_kind="none", label_path=None, pii="low", dedup_group="eryuan_ubm", role="train",
156
+ note="134,350 (verified) tif. truly no labels. SKIP the 2 redundant UBM .rar packs. ms-timestamp in filename (quasi-id)."),
157
+
158
+ # ===================== UWF (ultra-widefield) -- NEW modality, single center =====================
159
+ dict(key="yinhai_uwf", modality="uwf", center="yinhai",
160
+ src=f"{NFS_BACKUP}/pretrainNewDS/uwf/yinhai_uwf", comp="rar5", extracted=False, exts=(".jpg",),
161
+ label_kind="none", label_path=None, pii="low", dedup_group="yinhai_uwf", role="train",
162
+ 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)."),
163
+ ]
164
+
165
+ # Archives explicitly NOT ingested (dups / products-superseded / code). Documented for transparency; never deleted.
166
+ SKIP = {
167
+ "rawFundus_predicted": "dup of fq_rawfundus (quality-resorted)",
168
+ "testFundus_predicted": "dup of fq_testfundus",
169
+ "eryuan_split.tar.gz": "subset of eryuan_fundus",
170
+ "handan_ffa2": "strict subset of handan (0 unique files)",
171
+ "Final_eryuan_FFA.zip": "redundant archive of eryuan_ffa extracted dir",
172
+ "2-UBM-SW3200L-去噪声处理.rar / 3-UBM-SW3200L2-dataset.rar": "redundant with eryuan_ubm",
173
+ "同仁/fundus.zip": "superseded by tongren_fundus shards (de-id)",
174
+ "octBuckets.zip": "superseded by octbuckets_octa shards (de-id)",
175
+ "tr/*.7z": "extracted copy tr1695L2 already present",
176
+ "BioCliFM.tar.gz": "code, not data",
177
+ "fundus_hcw .pth/code": "150G checkpoints+code; only images extracted via extract_glob",
178
+ }
179
+
180
+ INCLUDE = COHORTS
181
+ def by_role(role): return [c for c in COHORTS if c["role"] == role]
182
+ def to_extract(): return [c for c in COHORTS if not c.get("extracted")]
183
+ def modalities(): return sorted({c["modality"] for c in COHORTS})
tools/data_processing/report_parsing/materialize_newdata_prompts.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Materialize new-data prompt artifacts in the old OCTFlow caption format.
2
+
3
+ Outputs:
4
+ - adapter_manifest_v1.parquet: 41-column OCTFlow-style structured manifest.
5
+ - captions_v2.parquet: caption_id, image_id, level, prompt_text, language, generator, grounded_in.
6
+ - sidecar_v1.parquet: raw non-prompt details needed to audit how fields were derived.
7
+ - README.md: artifact and prompt design summary.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import pandas as pd
19
+ import pyarrow as pa
20
+ import pyarrow.parquet as pq
21
+
22
+ from prompt_qc import build_prompts, clean_text, extract_finding_tags, translate_diag
23
+
24
+
25
+ DEFAULT_MANIFEST = Path(
26
+ "/data/team/lisicheng/new_data_manifest/"
27
+ "new_data_manifest_dedup_split_labeled_with_wds_deid_leftfundus.parquet"
28
+ )
29
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_v1")
30
+
31
+ V2_MODALITY_OVERRIDES = {
32
+ "data0410_master_fundus": "oct_bscan",
33
+ "octbuckets_octa": "oct_bscan",
34
+ }
35
+
36
+ V2_EXCLUDE_COHORTS = {
37
+ "fq_validfundus",
38
+ "dual_comorbidity_fundus",
39
+ }
40
+
41
+ ADAPTER_COLUMNS = [
42
+ "cohort",
43
+ "study_id",
44
+ "patient_hash",
45
+ "visit_date",
46
+ "eye",
47
+ "device_vendor",
48
+ "device_model",
49
+ "device_serial_hash",
50
+ "device_software_version",
51
+ "hospital_domain",
52
+ "ethnicity",
53
+ "image_quality_score",
54
+ "image_quality_band",
55
+ "diagnosis_group",
56
+ "lesion_tags",
57
+ "lesion_location",
58
+ "layer_involvement",
59
+ "severity",
60
+ "diagnosis_source",
61
+ "label_confidence",
62
+ "schema_version",
63
+ "image_id",
64
+ "file_path",
65
+ "file_format",
66
+ "modality",
67
+ "anatomy",
68
+ "device_technology",
69
+ "scan_protocol",
70
+ "scan_x_mm",
71
+ "bscan_index",
72
+ "image_height_px",
73
+ "image_width_px",
74
+ "axial_resolution_um",
75
+ "has_segmentation",
76
+ "n_layers_visible",
77
+ "fovea_x_norm",
78
+ "crt_um",
79
+ "choroid_thickness_um",
80
+ "oct_footprint_bbox_fundus",
81
+ "oct_footprint_bbox_slo",
82
+ "is_valid",
83
+ ]
84
+
85
+ SIDECAR_COLUMNS = [
86
+ "image_id",
87
+ "source_cohort",
88
+ "center",
89
+ "role",
90
+ "split",
91
+ "original_file_path",
92
+ "train_path",
93
+ "deid_path",
94
+ "pii_masked",
95
+ "deid_method",
96
+ "diagnosis_raw",
97
+ "group_raw",
98
+ "diagnosis_group_raw",
99
+ "caption_raw",
100
+ "ocr_age",
101
+ "ocr_sex",
102
+ "ocr_eye",
103
+ "storage",
104
+ ]
105
+
106
+ ADAPTER_SCHEMA = pa.schema(
107
+ [
108
+ ("cohort", pa.string()),
109
+ ("study_id", pa.string()),
110
+ ("patient_hash", pa.string()),
111
+ ("visit_date", pa.string()),
112
+ ("eye", pa.string()),
113
+ ("device_vendor", pa.string()),
114
+ ("device_model", pa.string()),
115
+ ("device_serial_hash", pa.string()),
116
+ ("device_software_version", pa.string()),
117
+ ("hospital_domain", pa.string()),
118
+ ("ethnicity", pa.string()),
119
+ ("image_quality_score", pa.float64()),
120
+ ("image_quality_band", pa.string()),
121
+ ("diagnosis_group", pa.list_(pa.string())),
122
+ ("lesion_tags", pa.list_(pa.string())),
123
+ ("lesion_location", pa.list_(pa.string())),
124
+ ("layer_involvement", pa.list_(pa.string())),
125
+ ("severity", pa.string()),
126
+ ("diagnosis_source", pa.string()),
127
+ ("label_confidence", pa.float64()),
128
+ ("schema_version", pa.string()),
129
+ ("image_id", pa.string()),
130
+ ("file_path", pa.string()),
131
+ ("file_format", pa.string()),
132
+ ("modality", pa.string()),
133
+ ("anatomy", pa.string()),
134
+ ("device_technology", pa.string()),
135
+ ("scan_protocol", pa.string()),
136
+ ("scan_x_mm", pa.float64()),
137
+ ("bscan_index", pa.float64()),
138
+ ("image_height_px", pa.float64()),
139
+ ("image_width_px", pa.float64()),
140
+ ("axial_resolution_um", pa.float64()),
141
+ ("has_segmentation", pa.bool_()),
142
+ ("n_layers_visible", pa.int64()),
143
+ ("fovea_x_norm", pa.float64()),
144
+ ("crt_um", pa.float64()),
145
+ ("choroid_thickness_um", pa.float64()),
146
+ ("oct_footprint_bbox_fundus", pa.list_(pa.int64())),
147
+ ("oct_footprint_bbox_slo", pa.list_(pa.int64())),
148
+ ("is_valid", pa.bool_()),
149
+ ]
150
+ )
151
+
152
+ CAPTIONS_SCHEMA = pa.schema(
153
+ [
154
+ ("caption_id", pa.string()),
155
+ ("image_id", pa.string()),
156
+ ("level", pa.string()),
157
+ ("prompt_text", pa.string()),
158
+ ("language", pa.string()),
159
+ ("generator", pa.string()),
160
+ ("grounded_in", pa.string()),
161
+ ]
162
+ )
163
+
164
+ SIDECAR_SCHEMA = pa.schema(
165
+ [
166
+ ("image_id", pa.string()),
167
+ ("source_cohort", pa.string()),
168
+ ("center", pa.string()),
169
+ ("role", pa.string()),
170
+ ("split", pa.string()),
171
+ ("original_file_path", pa.string()),
172
+ ("train_path", pa.string()),
173
+ ("deid_path", pa.string()),
174
+ ("pii_masked", pa.bool_()),
175
+ ("deid_method", pa.string()),
176
+ ("diagnosis_raw", pa.string()),
177
+ ("group_raw", pa.string()),
178
+ ("diagnosis_group_raw", pa.string()),
179
+ ("caption_raw", pa.string()),
180
+ ("ocr_age", pa.float64()),
181
+ ("ocr_sex", pa.string()),
182
+ ("ocr_eye", pa.string()),
183
+ ("storage", pa.string()),
184
+ ]
185
+ )
186
+
187
+ MODALITY_META = {
188
+ "fundus_color": ("macula", "fundus_camera", "single_shot"),
189
+ "oct_bscan": ("macula", "oct", "bscan"),
190
+ "uwf": ("wide-field", "fundus_camera", "widefield"),
191
+ "ffa": ("retina", "fluorescein_angiography", "angiography"),
192
+ "octa": ("macula", "octa", "enface"),
193
+ "bscan_us": ("globe", "ultrasound", "bscan"),
194
+ "ubm": ("anterior_segment", "ultrasound_biomicroscopy", "bscan"),
195
+ }
196
+
197
+
198
+ def main() -> None:
199
+ args = parse_args()
200
+ args.out.mkdir(parents=True, exist_ok=True)
201
+
202
+ df = pd.read_parquet(args.manifest)
203
+ if args.limit:
204
+ df = df.head(args.limit).copy()
205
+ if args.policy in {"v2", "v3"}:
206
+ df = apply_v2_policy(df)
207
+
208
+ adapter_path = args.out / f"adapter_manifest_{args.policy}.parquet"
209
+ captions_path = args.out / "captions_v2.parquet"
210
+ sidecar_path = args.out / f"sidecar_{args.policy}.parquet"
211
+
212
+ for path in [adapter_path, captions_path, sidecar_path]:
213
+ if path.exists() and not args.overwrite:
214
+ raise FileExistsError(f"{path} exists; pass --overwrite")
215
+ if path.exists():
216
+ path.unlink()
217
+
218
+ adapter_writer: pq.ParquetWriter | None = None
219
+ captions_writer: pq.ParquetWriter | None = None
220
+ sidecar_writer: pq.ParquetWriter | None = None
221
+
222
+ total_adapter = 0
223
+ total_captions = 0
224
+ for start in range(0, len(df), args.chunk_size):
225
+ chunk = df.iloc[start : start + args.chunk_size]
226
+ adapter_rows: list[dict[str, Any]] = []
227
+ caption_rows: list[dict[str, Any]] = []
228
+ sidecar_rows: list[dict[str, Any]] = []
229
+
230
+ for row in chunk.to_dict("records"):
231
+ adapter_rows.append(build_adapter_row(row))
232
+ sidecar_rows.append(build_sidecar_row(row))
233
+ prompts = build_prompts(row)
234
+ grounded = grounded_in(row)
235
+ for level in ["short", "medium", "dense"]:
236
+ caption_rows.append(
237
+ {
238
+ "caption_id": f"{row['image_id']}_{level}",
239
+ "image_id": row["image_id"],
240
+ "level": level,
241
+ "prompt_text": prompts[level],
242
+ "language": "en",
243
+ "generator": f"newdata_prompt_adapter_{args.policy}",
244
+ "grounded_in": grounded,
245
+ }
246
+ )
247
+
248
+ adapter_writer = append_parquet(
249
+ pd.DataFrame(adapter_rows, columns=ADAPTER_COLUMNS),
250
+ adapter_path,
251
+ adapter_writer,
252
+ ADAPTER_SCHEMA,
253
+ )
254
+ captions_writer = append_parquet(
255
+ pd.DataFrame(caption_rows), captions_path, captions_writer, CAPTIONS_SCHEMA
256
+ )
257
+ sidecar_writer = append_parquet(
258
+ pd.DataFrame(sidecar_rows, columns=SIDECAR_COLUMNS),
259
+ sidecar_path,
260
+ sidecar_writer,
261
+ SIDECAR_SCHEMA,
262
+ )
263
+ total_adapter += len(adapter_rows)
264
+ total_captions += len(caption_rows)
265
+ if total_adapter % args.log_every < len(adapter_rows):
266
+ print(f"rows={total_adapter} captions={total_captions}", flush=True)
267
+
268
+ for writer in [adapter_writer, captions_writer, sidecar_writer]:
269
+ if writer is not None:
270
+ writer.close()
271
+
272
+ write_readme(args.out, args.manifest, len(df), total_captions, args.policy)
273
+ write_summary(args.out, df, total_captions, args.policy)
274
+ print(json.dumps({"out": str(args.out), "rows": len(df), "captions": total_captions}, ensure_ascii=False))
275
+
276
+
277
+ def apply_v2_policy(df: pd.DataFrame) -> pd.DataFrame:
278
+ """Apply the first human-reviewed new-data policy before prompt materialization."""
279
+ out = df.copy()
280
+ if "split" not in out.columns:
281
+ raise KeyError("v2 policy requires a split column")
282
+ if "cohort" not in out.columns:
283
+ raise KeyError("v2 policy requires a cohort column")
284
+ if "modality" not in out.columns:
285
+ raise KeyError("v2 policy requires a modality column")
286
+
287
+ out = out[out["split"].eq("train")].copy()
288
+ out = out[~out["cohort"].isin(V2_EXCLUDE_COHORTS)].copy()
289
+ for cohort, modality in V2_MODALITY_OVERRIDES.items():
290
+ out.loc[out["cohort"].eq(cohort), "modality"] = modality
291
+ return out.reset_index(drop=True)
292
+
293
+
294
+ def append_parquet(
295
+ frame: pd.DataFrame, path: Path, writer: pq.ParquetWriter | None, schema: pa.Schema
296
+ ) -> pq.ParquetWriter:
297
+ table = pa.Table.from_pandas(frame, schema=schema, preserve_index=False)
298
+ if writer is None:
299
+ writer = pq.ParquetWriter(path, table.schema, compression="zstd")
300
+ writer.write_table(table)
301
+ return writer
302
+
303
+
304
+ def build_adapter_row(row: dict[str, Any]) -> dict[str, Any]:
305
+ modality = str(row.get("modality") or "unknown")
306
+ anatomy, technology, protocol = MODALITY_META.get(
307
+ modality, ("unknown", "unknown", "unknown")
308
+ )
309
+ if row.get("cohort") == "tongren_external_fundus":
310
+ anatomy = "anterior_segment"
311
+ technology = "external_photography"
312
+ protocol = "single_shot"
313
+
314
+ train_path = str(row.get("train_path") or row.get("file_path") or "")
315
+ diagnosis_group = canonical_diagnoses(row)
316
+ lesion_tags = canonical_lesions(row)
317
+ has_label = bool(diagnosis_group or lesion_tags or clean_text(row.get("caption")))
318
+
319
+ return {
320
+ "cohort": row.get("cohort"),
321
+ "study_id": row.get("image_id"),
322
+ "patient_hash": None,
323
+ "visit_date": None,
324
+ "eye": normalize_eye(row.get("ocr_eye")),
325
+ "device_vendor": "unknown",
326
+ "device_model": "unknown",
327
+ "device_serial_hash": None,
328
+ "device_software_version": None,
329
+ "hospital_domain": "new_data",
330
+ "ethnicity": "unknown",
331
+ "image_quality_score": None,
332
+ "image_quality_band": "unknown",
333
+ "diagnosis_group": diagnosis_group,
334
+ "lesion_tags": lesion_tags,
335
+ "lesion_location": [],
336
+ "layer_involvement": [],
337
+ "severity": "unknown",
338
+ "diagnosis_source": diagnosis_source(row),
339
+ "label_confidence": 1.0 if has_label else None,
340
+ "schema_version": "newdata_adapter_v1",
341
+ "image_id": row.get("image_id"),
342
+ "file_path": train_path,
343
+ "file_format": file_format(train_path),
344
+ "modality": modality,
345
+ "anatomy": anatomy,
346
+ "device_technology": technology,
347
+ "scan_protocol": protocol,
348
+ "scan_x_mm": None,
349
+ "bscan_index": None,
350
+ "image_height_px": None,
351
+ "image_width_px": None,
352
+ "axial_resolution_um": None,
353
+ "has_segmentation": False,
354
+ "n_layers_visible": 0,
355
+ "fovea_x_norm": None,
356
+ "crt_um": None,
357
+ "choroid_thickness_um": None,
358
+ "oct_footprint_bbox_fundus": None,
359
+ "oct_footprint_bbox_slo": None,
360
+ "is_valid": True,
361
+ }
362
+
363
+
364
+ def build_sidecar_row(row: dict[str, Any]) -> dict[str, Any]:
365
+ return {
366
+ "image_id": row.get("image_id"),
367
+ "source_cohort": row.get("cohort"),
368
+ "center": row.get("center"),
369
+ "role": row.get("role"),
370
+ "split": row.get("split"),
371
+ "original_file_path": row.get("file_path"),
372
+ "train_path": row.get("train_path"),
373
+ "deid_path": row.get("deid_path"),
374
+ "pii_masked": bool(row.get("pii_masked")),
375
+ "deid_method": row.get("deid_method"),
376
+ "diagnosis_raw": row.get("diagnosis_raw"),
377
+ "group_raw": row.get("group_raw"),
378
+ "diagnosis_group_raw": row.get("diagnosis_group"),
379
+ "caption_raw": row.get("caption"),
380
+ "ocr_age": clean_scalar(row.get("ocr_age")),
381
+ "ocr_sex": clean_scalar(row.get("ocr_sex")),
382
+ "ocr_eye": clean_scalar(row.get("ocr_eye")),
383
+ "storage": row.get("storage"),
384
+ }
385
+
386
+
387
+ def canonical_diagnoses(row: dict[str, Any]) -> list[str]:
388
+ out: list[str] = []
389
+ for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
390
+ text = clean_text(row.get(key))
391
+ if not text:
392
+ continue
393
+ val = translate_diag(text)
394
+ if is_canonical_label(val):
395
+ add_unique(out, val)
396
+ return out
397
+
398
+
399
+ def canonical_lesions(row: dict[str, Any]) -> list[str]:
400
+ out: list[str] = []
401
+ for key in ["caption", "diagnosis_raw", "diagnosis_group", "group_raw"]:
402
+ for tag in extract_finding_tags(clean_text(row.get(key))):
403
+ add_unique(out, tag)
404
+ return out
405
+
406
+
407
+ def is_canonical_label(text: str) -> bool:
408
+ if not text or "_" in text or len(text) > 80:
409
+ return False
410
+ return not any("\u4e00" <= ch <= "\u9fff" for ch in text)
411
+
412
+
413
+ def add_unique(out: list[str], value: str) -> None:
414
+ if value and value.lower() not in {v.lower() for v in out}:
415
+ out.append(value)
416
+
417
+
418
+ def diagnosis_source(row: dict[str, Any]) -> str:
419
+ if clean_text(row.get("caption")):
420
+ return "clinical_report"
421
+ if clean_text(row.get("diagnosis_raw")) or clean_text(row.get("diagnosis_group")):
422
+ return "file_label"
423
+ if clean_text(row.get("group_raw")):
424
+ return "folder_label"
425
+ return "none"
426
+
427
+
428
+ def grounded_in(row: dict[str, Any]) -> str:
429
+ parts = ["manifest_fields"]
430
+ if (
431
+ clean_scalar(row.get("ocr_age")) is not None
432
+ or clean_scalar(row.get("ocr_sex")) is not None
433
+ or clean_scalar(row.get("ocr_eye")) is not None
434
+ ):
435
+ parts.append("nonidentifying_demographics")
436
+ if diagnosis_source(row) != "none":
437
+ parts.append("clinical_labels")
438
+ return "+".join(parts)
439
+
440
+
441
+ def normalize_eye(value: Any) -> str:
442
+ eye = str(value or "").upper()
443
+ if eye in {"OD", "OS", "OU"}:
444
+ return eye
445
+ return "unknown"
446
+
447
+
448
+ def file_format(path: str) -> str:
449
+ suffix = path.split("::", 1)[1] if "::" in path else path
450
+ ext = Path(suffix).suffix.lower().lstrip(".")
451
+ return ext or "unknown"
452
+
453
+
454
+ def clean_scalar(value: Any) -> Any:
455
+ if value is None:
456
+ return None
457
+ if isinstance(value, float) and math.isnan(value):
458
+ return None
459
+ return value
460
+
461
+
462
+ def write_readme(out: Path, manifest: Path, rows: int, captions: int, policy: str) -> None:
463
+ policy_note = ""
464
+ if policy in {"v2", "v3"}:
465
+ policy_note = f"""
466
+ Human-reviewed {policy} data policy:
467
+
468
+ - keep only `split=train`;
469
+ - exclude cohorts: `{", ".join(sorted(V2_EXCLUDE_COHORTS))}`;
470
+ - modality overrides: `{json.dumps(V2_MODALITY_OVERRIDES, ensure_ascii=False)}`.
471
+ """
472
+
473
+ text = f"""# New Data Prompt Adapter {policy}
474
+
475
+ Source manifest:
476
+
477
+ ```text
478
+ {manifest}
479
+ ```
480
+
481
+ Artifacts:
482
+
483
+ - `adapter_manifest_{policy}.parquet`: OCTFlow-style structured manifest. It follows the old
484
+ 41-column adapter schema. `file_path` points to the actual training image path.
485
+ - `captions_v2.parquet`: SD3 text-conditioning table with columns
486
+ `caption_id,image_id,level,prompt_text,language,generator,grounded_in`.
487
+ - `sidecar_{policy}.parquet`: raw audit fields that are not copied into prompts.
488
+ - `summary.json`: counts and coverage.
489
+
490
+ Rows: {rows}
491
+ Caption rows: {captions}
492
+
493
+ {policy_note}
494
+
495
+ Prompt policy:
496
+
497
+ - `short`: modality phrase only.
498
+ - `medium`: modality phrase + reliable non-identifying demographics + up to 3 English labels.
499
+ - `dense`: modality phrase + reliable non-identifying demographics + up to 8 English labels.
500
+ - No center, hospital, cohort, dataset name, file name, ID, exact date, DOB, raw OCR text, or
501
+ raw Chinese report text is copied into `prompt_text`.
502
+ - Age enters prompts only as buckets such as `in their 60s`, never exact age.
503
+
504
+ The original de-identified image routing remains controlled by the source manifest's `train_path`.
505
+ """
506
+ (out / "README.md").write_text(text, encoding="utf-8")
507
+
508
+
509
+ def write_summary(out: Path, df: pd.DataFrame, captions: int, policy: str) -> None:
510
+ summary = {
511
+ "policy": policy,
512
+ "rows": int(len(df)),
513
+ "captions": int(captions),
514
+ "by_modality": df.groupby("modality").size().astype(int).to_dict(),
515
+ "by_cohort": df.groupby("cohort").size().astype(int).to_dict(),
516
+ "pii_masked": int(df["pii_masked"].fillna(False).sum()) if "pii_masked" in df else 0,
517
+ }
518
+ if policy in {"v2", "v3"}:
519
+ summary[f"{policy}_exclude_cohorts"] = sorted(V2_EXCLUDE_COHORTS)
520
+ summary[f"{policy}_modality_overrides"] = V2_MODALITY_OVERRIDES
521
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
522
+
523
+
524
+ def parse_args() -> argparse.Namespace:
525
+ parser = argparse.ArgumentParser()
526
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
527
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
528
+ parser.add_argument("--chunk-size", type=int, default=100_000)
529
+ parser.add_argument("--log-every", type=int, default=500_000)
530
+ parser.add_argument("--limit", type=int, default=None)
531
+ parser.add_argument("--overwrite", action="store_true")
532
+ parser.add_argument("--policy", choices=["v1", "v2", "v3"], default="v1")
533
+ return parser.parse_args()
534
+
535
+
536
+ if __name__ == "__main__":
537
+ main()
tools/data_processing/taxonomy/build_mixed_v5_taxonomy.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the mixed v5 prompt/taxonomy artifact from the mixed v4 artifact.
2
+
3
+ v5 keeps the v4 image routing unchanged, but separates raw modality labels from
4
+ paper-facing modality taxonomy. It also rewrites prompt prefixes so UWF, OCT
5
+ views, and SLO variants are described as family/subtype/view/protocol rather
6
+ than as unrelated independent modalities.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import math
14
+ import re
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+
19
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v4")
20
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v5")
21
+
22
+ NEW_COLUMNS = [
23
+ "taxonomy_version",
24
+ "modality_family",
25
+ "modality_subtype",
26
+ "view_or_projection",
27
+ "field_of_view",
28
+ "device_or_acquisition_protocol",
29
+ "prompt_modality_phrase",
30
+ ]
31
+
32
+ OLD_PROMPT_PREFIXES = [
33
+ "optical coherence tomography angiography en face image",
34
+ "fundus fluorescein angiography image",
35
+ "fluorescein fundus angiography image",
36
+ "retinal fluorescein angiography image",
37
+ "ultra-widefield retinal fundus photograph",
38
+ "ultra-widefield color fundus photograph",
39
+ "ultra-widefield fundus photograph",
40
+ "ultra-widefield fundus image",
41
+ "ultra-widefield fundus",
42
+ "ultrasound biomicroscopy image of the anterior segment",
43
+ "ultrasound biomicroscopy image",
44
+ "B-scan ultrasonography image",
45
+ "ocular B-scan ultrasound image",
46
+ "structural OCT en face projection",
47
+ "structural OCT B-scan",
48
+ "OCTA en face image",
49
+ "OCT B-scan",
50
+ "color fundus photograph",
51
+ "color fundus",
52
+ "anterior segment photograph",
53
+ "slit-lamp anterior segment photograph",
54
+ "infrared SLO",
55
+ "IR-SLO",
56
+ "SLO",
57
+ ]
58
+
59
+
60
+ def derive_taxonomy(row: dict[str, Any]) -> dict[str, str]:
61
+ modality = _clean(row.get("modality")).lower()
62
+ anatomy = _clean(row.get("anatomy")).lower()
63
+ technology = _clean(row.get("device_technology")).lower()
64
+ protocol = _clean(row.get("scan_protocol")).lower()
65
+
66
+ if modality == "fundus_color" and (
67
+ anatomy == "anterior_segment" or technology == "external_photography"
68
+ ):
69
+ return _tax(
70
+ "anterior_segment_photography",
71
+ "external_anterior_segment_photo",
72
+ "single_shot",
73
+ "anterior_segment",
74
+ technology,
75
+ protocol,
76
+ )
77
+ if modality == "fundus_color":
78
+ return _tax(
79
+ "color_fundus_photography",
80
+ "standard_color_fundus",
81
+ "single_shot",
82
+ _posterior_fov(anatomy, "standard"),
83
+ technology,
84
+ protocol,
85
+ )
86
+ if modality == "uwf":
87
+ return _tax(
88
+ "color_fundus_photography",
89
+ "uwf_color_fundus",
90
+ "single_shot",
91
+ "ultra_widefield",
92
+ technology or "fundus_camera",
93
+ protocol or "widefield",
94
+ )
95
+ if modality == "ffa":
96
+ return _tax(
97
+ "fluorescein_angiography",
98
+ "fundus_fluorescein_angiography",
99
+ "angiography",
100
+ _posterior_fov(anatomy, "standard"),
101
+ technology or "fluorescein_angiography",
102
+ protocol or "angiography",
103
+ )
104
+ if modality == "oct_bscan":
105
+ return _tax(
106
+ "structural_oct",
107
+ "oct_bscan",
108
+ "bscan",
109
+ _posterior_fov(anatomy, "macula"),
110
+ technology or "oct",
111
+ protocol or "bscan",
112
+ )
113
+ if modality == "oct_enface":
114
+ return _tax(
115
+ "structural_oct",
116
+ "oct_enface",
117
+ "en_face_projection",
118
+ _posterior_fov(anatomy, "macula"),
119
+ technology or "oct",
120
+ protocol or "en_face_projection",
121
+ )
122
+ if modality == "octa_enface" or modality == "octa":
123
+ return _tax(
124
+ "oct_angiography",
125
+ "octa_enface",
126
+ "en_face_projection",
127
+ _posterior_fov(anatomy, "macula"),
128
+ technology or "octa",
129
+ protocol or "en_face_projection",
130
+ )
131
+ if modality == "ir_slo":
132
+ return _tax(
133
+ "scanning_laser_ophthalmoscopy",
134
+ "infrared_slo",
135
+ "en_face_reflectance",
136
+ _posterior_fov(anatomy, "macula"),
137
+ technology or "slo",
138
+ protocol or "single_shot",
139
+ )
140
+ if modality == "slo_gray":
141
+ return _tax(
142
+ "scanning_laser_ophthalmoscopy",
143
+ "reflectance_slo_gray",
144
+ "en_face_reflectance",
145
+ _posterior_fov(anatomy, "macula"),
146
+ technology or "slo",
147
+ protocol or "single_shot",
148
+ )
149
+ if modality == "bscan_us":
150
+ return _tax(
151
+ "ocular_ultrasound",
152
+ "ocular_bscan_ultrasound",
153
+ "bscan",
154
+ "globe",
155
+ technology or "ultrasound",
156
+ protocol or "bscan",
157
+ )
158
+ if modality == "ubm":
159
+ return _tax(
160
+ "ultrasound_biomicroscopy",
161
+ "ubm_anterior_segment",
162
+ "bscan",
163
+ "anterior_segment",
164
+ technology or "ultrasound_biomicroscopy",
165
+ protocol or "bscan",
166
+ )
167
+ if modality == "slit_lamp":
168
+ return _tax(
169
+ "anterior_segment_photography",
170
+ "slit_lamp_anterior_segment",
171
+ "single_shot",
172
+ "anterior_segment",
173
+ technology or "slit_lamp",
174
+ protocol or "single_shot",
175
+ )
176
+ return _tax("unknown", modality or "unknown", protocol or "unknown", anatomy or "unknown", technology, protocol)
177
+
178
+
179
+ def base_phrase(row: dict[str, Any], taxonomy: dict[str, str] | None = None) -> str:
180
+ taxonomy = taxonomy or derive_taxonomy(row)
181
+ subtype = taxonomy["modality_subtype"]
182
+ if subtype == "external_anterior_segment_photo":
183
+ return "anterior segment photograph"
184
+ if subtype == "standard_color_fundus":
185
+ return "color fundus photograph"
186
+ if subtype == "uwf_color_fundus":
187
+ return "ultra-widefield color fundus photograph"
188
+ if subtype == "fundus_fluorescein_angiography":
189
+ return "fundus fluorescein angiography image"
190
+ if subtype == "oct_bscan":
191
+ return "structural OCT B-scan"
192
+ if subtype == "oct_enface":
193
+ return "structural OCT en face projection"
194
+ if subtype == "octa_enface":
195
+ return "OCT angiography en face image"
196
+ if subtype == "infrared_slo":
197
+ return "infrared scanning laser ophthalmoscopy image"
198
+ if subtype == "reflectance_slo_gray":
199
+ return "scanning laser ophthalmoscopy reflectance image"
200
+ if subtype == "ocular_bscan_ultrasound":
201
+ return "ocular B-scan ultrasound image"
202
+ if subtype == "ubm_anterior_segment":
203
+ return "ultrasound biomicroscopy image"
204
+ if subtype == "slit_lamp_anterior_segment":
205
+ return "slit-lamp anterior segment photograph"
206
+ return f"{_clean(row.get('modality')).replace('_', ' ')} ophthalmic image".strip()
207
+
208
+
209
+ def rewrite_prompt(old_prompt: Any, level: str, phrase: str) -> str:
210
+ phrase = _squash(phrase)
211
+ if level == "short":
212
+ return phrase
213
+ descriptor = strip_old_prefix(old_prompt)
214
+ if not descriptor:
215
+ return phrase
216
+ if descriptor.lower() == phrase.lower():
217
+ return phrase
218
+ if descriptor.lower().startswith(phrase.lower() + ","):
219
+ return _squash(descriptor)
220
+ return _squash(f"{phrase}, {descriptor}")
221
+
222
+
223
+ def strip_old_prefix(text: Any) -> str:
224
+ text = _squash(_clean(text))
225
+ if not text:
226
+ return ""
227
+ for prefix in OLD_PROMPT_PREFIXES:
228
+ match = re.match(rf"^{re.escape(prefix)}(?:\s*[,,]\s*|\s*$)", text, flags=re.I)
229
+ if match:
230
+ return _squash(text[match.end() :])
231
+ return text
232
+
233
+
234
+ def add_taxonomy_columns(frame):
235
+ import pandas as pd
236
+
237
+ out = frame.copy()
238
+ for col in NEW_COLUMNS:
239
+ if col in out.columns:
240
+ out = out.drop(columns=[col])
241
+
242
+ out["taxonomy_version"] = "mixed_v5_taxonomy_20260706"
243
+ out["modality_family"] = "unknown"
244
+ out["modality_subtype"] = out["modality"].fillna("unknown").astype(str)
245
+ out["view_or_projection"] = "unknown"
246
+ out["field_of_view"] = out.get("anatomy", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
247
+ dev = out.get("device_technology", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
248
+ proto = out.get("scan_protocol", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
249
+ out["device_or_acquisition_protocol"] = dev + "/" + proto
250
+ out["prompt_modality_phrase"] = "ophthalmic image"
251
+
252
+ def set_mask(mask, family, subtype, view, fov, phrase):
253
+ out.loc[mask, "modality_family"] = family
254
+ out.loc[mask, "modality_subtype"] = subtype
255
+ out.loc[mask, "view_or_projection"] = view
256
+ out.loc[mask, "field_of_view"] = fov
257
+ out.loc[mask, "prompt_modality_phrase"] = phrase
258
+
259
+ mod = out["modality"].fillna("").astype(str)
260
+ anatomy = out.get("anatomy", pd.Series("", index=out.index)).fillna("").astype(str)
261
+ technology = out.get("device_technology", pd.Series("", index=out.index)).fillna("").astype(str)
262
+ protocol = out.get("scan_protocol", pd.Series("", index=out.index)).fillna("").astype(str)
263
+
264
+ anterior_fundus = mod.eq("fundus_color") & (
265
+ anatomy.eq("anterior_segment") | technology.eq("external_photography")
266
+ )
267
+ set_mask(anterior_fundus, "anterior_segment_photography", "external_anterior_segment_photo", "single_shot", "anterior_segment", "anterior segment photograph")
268
+ set_mask(mod.eq("fundus_color") & ~anterior_fundus, "color_fundus_photography", "standard_color_fundus", "single_shot", "standard", "color fundus photograph")
269
+ set_mask(mod.eq("uwf"), "color_fundus_photography", "uwf_color_fundus", "single_shot", "ultra_widefield", "ultra-widefield color fundus photograph")
270
+ set_mask(mod.eq("ffa"), "fluorescein_angiography", "fundus_fluorescein_angiography", "angiography", "standard", "fundus fluorescein angiography image")
271
+ set_mask(mod.eq("oct_bscan"), "structural_oct", "oct_bscan", "bscan", "macula", "structural OCT B-scan")
272
+ set_mask(mod.eq("oct_enface"), "structural_oct", "oct_enface", "en_face_projection", "macula", "structural OCT en face projection")
273
+ set_mask(mod.isin(["octa", "octa_enface"]), "oct_angiography", "octa_enface", "en_face_projection", "macula", "OCT angiography en face image")
274
+ set_mask(mod.eq("slo_gray"), "scanning_laser_ophthalmoscopy", "reflectance_slo_gray", "en_face_reflectance", "macula", "scanning laser ophthalmoscopy reflectance image")
275
+ set_mask(mod.eq("ir_slo"), "scanning_laser_ophthalmoscopy", "infrared_slo", "en_face_reflectance", "macula", "infrared scanning laser ophthalmoscopy image")
276
+ set_mask(mod.eq("bscan_us"), "ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe", "ocular B-scan ultrasound image")
277
+ set_mask(mod.eq("ubm"), "ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment", "ultrasound biomicroscopy image")
278
+ set_mask(mod.eq("slit_lamp"), "anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment", "slit-lamp anterior segment photograph")
279
+
280
+ optic = anatomy.eq("optic_disc")
281
+ out.loc[optic & mod.eq("oct_bscan"), "field_of_view"] = "optic_disc"
282
+ out.loc[optic & mod.eq("slo_gray"), "field_of_view"] = "optic_disc"
283
+ wide = anatomy.eq("wide-field") | protocol.str.contains("wide", case=False, na=False) | mod.eq("uwf")
284
+ out.loc[wide, "field_of_view"] = "ultra_widefield"
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
+ phrases = manifest["prompt_modality_phrase"].astype(str).reset_index(drop=True)
300
+ old_short = wide["short"].reindex(ids).reset_index(drop=True) if "short" in wide else pd.Series([None] * len(ids))
301
+ old_medium = wide["medium"].reindex(ids).reset_index(drop=True) if "medium" in wide else pd.Series([None] * len(ids))
302
+ old_dense = wide["dense"].reindex(ids).reset_index(drop=True) if "dense" in wide else pd.Series([None] * len(ids))
303
+ source_by_level = {
304
+ "short": old_short,
305
+ "medium": old_medium.combine_first(old_dense).combine_first(old_short),
306
+ "dense": old_dense.combine_first(old_medium).combine_first(old_short),
307
+ }
308
+
309
+ schema = pa.schema(
310
+ [
311
+ ("caption_id", pa.string()),
312
+ ("image_id", pa.string()),
313
+ ("level", pa.string()),
314
+ ("prompt_text", pa.string()),
315
+ ("language", pa.string()),
316
+ ("generator", pa.string()),
317
+ ("grounded_in", pa.string()),
318
+ ]
319
+ )
320
+ if out_path.exists():
321
+ out_path.unlink()
322
+ writer = pq.ParquetWriter(out_path, schema, compression="zstd")
323
+ total = 0
324
+ try:
325
+ for start in range(0, len(ids), chunk_size):
326
+ end = min(start + chunk_size, len(ids))
327
+ frames = []
328
+ phrase_chunk = phrases.iloc[start:end].tolist()
329
+ id_chunk = ids.iloc[start:end].tolist()
330
+ for level in ["short", "medium", "dense"]:
331
+ old_chunk = source_by_level[level].iloc[start:end].tolist()
332
+ prompt_text = [
333
+ rewrite_prompt(old, level, phrase)
334
+ for old, phrase in zip(old_chunk, phrase_chunk, strict=True)
335
+ ]
336
+ frames.append(
337
+ pd.DataFrame(
338
+ {
339
+ "caption_id": [f"{image_id}_{level}" for image_id in id_chunk],
340
+ "image_id": id_chunk,
341
+ "level": level,
342
+ "prompt_text": prompt_text,
343
+ "language": "en",
344
+ "generator": "mixed_prompt_adapter_v5_taxonomy",
345
+ "grounded_in": "v5_taxonomy+v4_clean_prompt_descriptors",
346
+ }
347
+ )
348
+ )
349
+ table = pa.Table.from_pandas(pd.concat(frames, ignore_index=True), schema=schema, preserve_index=False)
350
+ writer.write_table(table)
351
+ total += table.num_rows
352
+ print(f"captions={total}", flush=True)
353
+ finally:
354
+ writer.close()
355
+ return total
356
+
357
+
358
+ def write_readme(out: Path, manifest_rows: int, caption_rows: int) -> None:
359
+ text = f"""# Mixed Prompt Adapter v5
360
+
361
+ Rows: {manifest_rows}
362
+ Caption rows: {caption_rows}
363
+
364
+ v5 keeps image paths and raw `modality` labels from v4, then adds:
365
+
366
+ - `modality_family`
367
+ - `modality_subtype`
368
+ - `view_or_projection`
369
+ - `field_of_view`
370
+ - `device_or_acquisition_protocol`
371
+ - `prompt_modality_phrase`
372
+
373
+ Design:
374
+
375
+ - UWF is represented as a color fundus photography variant with
376
+ `field_of_view=ultra_widefield`, not as an unrelated independent modality.
377
+ - OCT B-scan and OCT en-face are structural OCT views/projections.
378
+ - OCTA en-face is an OCT angiography en-face image.
379
+ - SLO gray and IR-SLO are scanning-laser-ophthalmoscopy reflectance variants.
380
+ - Ocular B-scan ultrasound and UBM remain separate ultrasound-family subtypes
381
+ because they image different anatomical regions at different frequencies.
382
+ - Anterior-segment external photographs previously carried under
383
+ `fundus_color/anterior_segment` are prompted as anterior segment photographs.
384
+
385
+ Prompt policy:
386
+
387
+ - `short`: v5 modality phrase only.
388
+ - `medium` and `dense`: v5 modality phrase plus the already-cleaned v4 prompt
389
+ descriptors, with only the modality prefix rewritten.
390
+ - No raw Chinese report text or new image-derived labels are introduced here.
391
+ """
392
+ (out / "README.md").write_text(text, encoding="utf-8")
393
+
394
+
395
+ def write_summary(out: Path, manifest, caption_rows: int) -> None:
396
+ summary = {
397
+ "rows": int(len(manifest)),
398
+ "captions": int(caption_rows),
399
+ "by_modality": manifest.groupby("modality").size().astype(int).to_dict(),
400
+ "by_modality_family": manifest.groupby("modality_family").size().astype(int).to_dict(),
401
+ "by_modality_subtype": manifest.groupby("modality_subtype").size().astype(int).to_dict(),
402
+ "by_family_subtype": {
403
+ f"{family}/{subtype}": int(n)
404
+ for (family, subtype), n in manifest.groupby(["modality_family", "modality_subtype"]).size().items()
405
+ },
406
+ }
407
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
408
+
409
+
410
+ def main() -> None:
411
+ import pandas as pd
412
+
413
+ args = parse_args()
414
+ args.out.mkdir(parents=True, exist_ok=True)
415
+ manifest_in = args.input / "adapter_manifest_mixed_v4.parquet"
416
+ captions_in = args.input / "captions_v2.parquet"
417
+ manifest_out = args.out / "adapter_manifest_mixed_v5.parquet"
418
+ captions_out = args.out / "captions_v2.parquet"
419
+
420
+ if not args.overwrite:
421
+ for path in [manifest_out, captions_out]:
422
+ if path.exists():
423
+ raise FileExistsError(f"{path} exists; pass --overwrite")
424
+
425
+ manifest = pd.read_parquet(manifest_in)
426
+ if args.limit:
427
+ manifest = manifest.head(args.limit).copy()
428
+ manifest = add_taxonomy_columns(manifest)
429
+ manifest.to_parquet(manifest_out, index=False, compression="zstd")
430
+
431
+ captions = pd.read_parquet(captions_in, columns=["image_id", "level", "prompt_text"])
432
+ caption_rows = build_captions(manifest, captions, captions_out, args.chunk_size)
433
+ write_summary(args.out, manifest, caption_rows)
434
+ write_readme(args.out, len(manifest), caption_rows)
435
+ print(json.dumps({"out": str(args.out), "rows": len(manifest), "captions": caption_rows}, ensure_ascii=False))
436
+
437
+
438
+ def parse_args() -> argparse.Namespace:
439
+ parser = argparse.ArgumentParser()
440
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
441
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
442
+ parser.add_argument("--chunk-size", type=int, default=250_000)
443
+ parser.add_argument("--limit", type=int, default=None)
444
+ parser.add_argument("--overwrite", action="store_true")
445
+ return parser.parse_args()
446
+
447
+
448
+ def _tax(family: str, subtype: str, view: str, fov: str, technology: str, protocol: str) -> dict[str, str]:
449
+ return {
450
+ "taxonomy_version": "mixed_v5_taxonomy_20260706",
451
+ "modality_family": family,
452
+ "modality_subtype": subtype,
453
+ "view_or_projection": view,
454
+ "field_of_view": fov,
455
+ "device_or_acquisition_protocol": f"{technology or 'unknown'}/{protocol or 'unknown'}",
456
+ }
457
+
458
+
459
+ def _posterior_fov(anatomy: str, default: str) -> str:
460
+ if anatomy == "optic_disc":
461
+ return "optic_disc"
462
+ if anatomy in {"wide-field", "widefield"}:
463
+ return "ultra_widefield"
464
+ if anatomy in {"macula", "retina"}:
465
+ return "macula" if anatomy == "macula" else default
466
+ return default
467
+
468
+
469
+ def _clean(value: Any) -> str:
470
+ if value is None:
471
+ return ""
472
+ if isinstance(value, float) and math.isnan(value):
473
+ return ""
474
+ return str(value).strip()
475
+
476
+
477
+ def _squash(text: str) -> str:
478
+ text = re.sub(r"\s+", " ", text)
479
+ text = re.sub(r"\s*[,,]\s*", ", ", text)
480
+ return text.strip(" ,,")
481
+
482
+
483
+ if __name__ == "__main__":
484
+ main()
tools/data_processing/taxonomy/build_mixed_v6_taxonomy.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build mixed v6 prompt/taxonomy artifacts from the mixed v5 artifacts.
2
+
3
+ v6 keeps image routing unchanged, but makes prompt conditioning hierarchical:
4
+ modality family + view/projection + field of view/anatomy. It also folds the
5
+ tiny IR-SLO split into the reflectance SLO subtype and removes dataset split
6
+ tokens from diagnosis descriptors before they can enter prompts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import math
14
+ import re
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from build_mixed_v5_taxonomy import OLD_PROMPT_PREFIXES, strip_old_prefix
19
+
20
+
21
+ DEFAULT_IN = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v5")
22
+ DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6")
23
+ VERSION = "mixed_v6_hierarchical_taxonomy_20260707"
24
+ SPLIT_TOKENS = {"train", "test", "val", "valid", "validation", "eryuan"}
25
+ V6_EXTRA_OLD_PROMPT_PREFIXES = [
26
+ "infrared scanning laser ophthalmoscopy image",
27
+ "scanning laser ophthalmoscopy reflectance image",
28
+ ]
29
+
30
+
31
+ def derive_taxonomy(row: dict[str, Any]) -> dict[str, str]:
32
+ modality = _clean(row.get("modality")).lower()
33
+ anatomy = _clean(row.get("anatomy")).lower()
34
+ technology = _clean(row.get("device_technology")).lower()
35
+ protocol = _clean(row.get("scan_protocol")).lower()
36
+
37
+ if modality == "fundus_color" and (
38
+ anatomy == "anterior_segment" or technology == "external_photography"
39
+ ):
40
+ return _tax(
41
+ "anterior_segment_photography",
42
+ "external_anterior_segment_photo",
43
+ "single_shot",
44
+ "anterior_segment",
45
+ technology,
46
+ protocol,
47
+ )
48
+ if modality == "fundus_color":
49
+ return _tax(
50
+ "color_fundus_photography",
51
+ "standard_color_fundus",
52
+ "single_shot",
53
+ _posterior_fov(anatomy, "standard"),
54
+ technology,
55
+ protocol,
56
+ )
57
+ if modality == "uwf":
58
+ return _tax(
59
+ "color_fundus_photography",
60
+ "uwf_color_fundus",
61
+ "single_shot",
62
+ "ultra_widefield",
63
+ technology or "fundus_camera",
64
+ protocol or "widefield",
65
+ )
66
+ if modality == "ffa":
67
+ return _tax(
68
+ "fluorescein_angiography",
69
+ "fundus_fluorescein_angiography",
70
+ "angiography",
71
+ _posterior_fov(anatomy, "standard"),
72
+ technology or "fluorescein_angiography",
73
+ protocol or "angiography",
74
+ )
75
+ if modality == "oct_bscan":
76
+ return _tax("structural_oct", "oct_bscan", "bscan", _posterior_fov(anatomy, "macula"), technology or "oct", protocol or "bscan")
77
+ if modality == "oct_enface":
78
+ return _tax("structural_oct", "oct_enface", "en_face_projection", _posterior_fov(anatomy, "macula"), technology or "oct", protocol or "en_face_projection")
79
+ if modality in {"octa", "octa_enface"}:
80
+ return _tax("oct_angiography", "octa_enface", "en_face_projection", _posterior_fov(anatomy, "macula"), technology or "octa", protocol or "en_face_projection")
81
+ if modality in {"slo_gray", "ir_slo"}:
82
+ return _tax(
83
+ "scanning_laser_ophthalmoscopy",
84
+ "reflectance_slo_gray",
85
+ "en_face_reflectance",
86
+ _posterior_fov(anatomy, "macula"),
87
+ technology or "slo",
88
+ protocol or ("infrared" if modality == "ir_slo" else "single_shot"),
89
+ )
90
+ if modality == "bscan_us":
91
+ return _tax("ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe", technology or "ultrasound", protocol or "bscan")
92
+ if modality == "ubm":
93
+ return _tax("ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment", technology or "ultrasound_biomicroscopy", protocol or "bscan")
94
+ if modality == "slit_lamp":
95
+ return _tax("anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment", technology or "slit_lamp", protocol or "single_shot")
96
+ return _tax("unknown", modality or "unknown", protocol or "unknown", anatomy or "unknown", technology, protocol)
97
+
98
+
99
+ def hierarchical_phrase(taxonomy: dict[str, str]) -> str:
100
+ subtype = taxonomy["modality_subtype"]
101
+ fov = taxonomy.get("field_of_view", "unknown")
102
+ if subtype == "standard_color_fundus":
103
+ return _join_prompt_parts("ophthalmic image", "color fundus photography", f"{_fov_text(fov)} field of view", "retina")
104
+ if subtype == "uwf_color_fundus":
105
+ return _join_prompt_parts("ophthalmic image", "color fundus photography", "ultra-widefield view", "retina")
106
+ if subtype == "fundus_fluorescein_angiography":
107
+ return _join_prompt_parts("ophthalmic image", "fundus fluorescein angiography", _fov_text(fov), "retina")
108
+ if subtype == "oct_bscan":
109
+ return _join_prompt_parts("ophthalmic image", "structural OCT", "B-scan view", _fov_text(fov))
110
+ if subtype == "oct_enface":
111
+ return _join_prompt_parts("ophthalmic image", "structural OCT", "en face projection", _fov_text(fov))
112
+ if subtype == "octa_enface":
113
+ return _join_prompt_parts("ophthalmic image", "OCT angiography", "en face projection", _fov_text(fov))
114
+ if subtype == "reflectance_slo_gray":
115
+ return _join_prompt_parts("ophthalmic image", "scanning laser ophthalmoscopy", "reflectance en face view", _fov_text(fov))
116
+ if subtype == "ocular_bscan_ultrasound":
117
+ return _join_prompt_parts("ophthalmic image", "ocular ultrasound", "B-scan view", "globe")
118
+ if subtype == "ubm_anterior_segment":
119
+ return _join_prompt_parts("ophthalmic image", "ultrasound biomicroscopy", "anterior segment", "B-scan view")
120
+ if subtype == "external_anterior_segment_photo":
121
+ return _join_prompt_parts("ophthalmic image", "anterior segment photography", "external photograph")
122
+ if subtype == "slit_lamp_anterior_segment":
123
+ return _join_prompt_parts("ophthalmic image", "slit-lamp anterior segment photography")
124
+ return _join_prompt_parts("ophthalmic image", taxonomy.get("modality_family", "unknown"))
125
+
126
+
127
+ def clean_diagnosis_group(value: Any) -> list[str]:
128
+ if value is None:
129
+ return []
130
+ if isinstance(value, float) and math.isnan(value):
131
+ return []
132
+ if isinstance(value, (list, tuple)):
133
+ tokens = [str(v) for v in value]
134
+ else:
135
+ text = _clean(value)
136
+ if not text or text in {"[]", "None", "nan", "<NA>"}:
137
+ return []
138
+ tokens = re.findall(r"'([^']+)'", text)
139
+ if not tokens:
140
+ tokens = re.split(r"[;,|]", text.strip("[]"))
141
+ cleaned: list[str] = []
142
+ seen: set[str] = set()
143
+ for token in tokens:
144
+ label = _squash(str(token).strip(" \"'[]"))
145
+ if not label:
146
+ continue
147
+ if label.lower() in SPLIT_TOKENS:
148
+ continue
149
+ if label.lower() in seen:
150
+ continue
151
+ seen.add(label.lower())
152
+ cleaned.append(label)
153
+ return cleaned
154
+
155
+
156
+ def rewrite_prompt(old_prompt: Any, level: str, taxonomy: dict[str, str], diagnosis: Any = None) -> str:
157
+ phrase = hierarchical_phrase(taxonomy)
158
+ if level == "short":
159
+ return phrase
160
+ descriptor = clean_prompt_descriptor(strip_old_prefix(old_prompt))
161
+ diagnosis_text = diagnosis_phrase(diagnosis)
162
+ extras = []
163
+ if diagnosis_text and diagnosis_text.lower() not in descriptor.lower():
164
+ extras.append(diagnosis_text)
165
+ if descriptor:
166
+ extras.append(descriptor)
167
+ return _squash(", ".join([phrase, *extras]))
168
+
169
+
170
+ def diagnosis_phrase(value: Any) -> str:
171
+ labels = clean_diagnosis_group(value)
172
+ if not labels:
173
+ return ""
174
+ return "diagnosis: " + "; ".join(labels)
175
+
176
+
177
+ def clean_prompt_descriptor(text: Any) -> str:
178
+ text = _squash(_clean(text))
179
+ if not text:
180
+ return ""
181
+ for prefix in [*V6_EXTRA_OLD_PROMPT_PREFIXES, *OLD_PROMPT_PREFIXES]:
182
+ text = re.sub(rf"^{re.escape(prefix)}(?:\s*[,,]\s*|\s*$)", "", text, flags=re.I)
183
+ parts = []
184
+ for part in re.split(r"[,,;|]+", text):
185
+ part = _squash(part)
186
+ if not part:
187
+ continue
188
+ if part.lower() in SPLIT_TOKENS:
189
+ continue
190
+ part = re.sub(r"\b(?:train|test|val|valid|validation|eryuan)\b", "", part, flags=re.I)
191
+ part = _squash(part.strip(" ,;"))
192
+ if part:
193
+ parts.append(part)
194
+ return _squash(", ".join(dict.fromkeys(parts)))
195
+
196
+
197
+ def add_v6_columns(frame):
198
+ import pandas as pd
199
+
200
+ out = frame.copy()
201
+ for col in [
202
+ "taxonomy_version",
203
+ "modality_family",
204
+ "modality_subtype",
205
+ "view_or_projection",
206
+ "field_of_view",
207
+ "device_or_acquisition_protocol",
208
+ "prompt_modality_phrase",
209
+ "diagnosis_group_clean",
210
+ "subtype_sample_status",
211
+ ]:
212
+ if col in out.columns:
213
+ out = out.drop(columns=[col])
214
+
215
+ out["taxonomy_version"] = VERSION
216
+ out["modality_family"] = "unknown"
217
+ out["modality_subtype"] = out["modality"].fillna("unknown").astype(str)
218
+ out["view_or_projection"] = "unknown"
219
+ out["field_of_view"] = out.get("anatomy", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
220
+ dev = out.get("device_technology", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
221
+ proto = out.get("scan_protocol", pd.Series("unknown", index=out.index)).fillna("unknown").astype(str)
222
+ out["device_or_acquisition_protocol"] = dev + "/" + proto
223
+
224
+ def set_mask(mask, family, subtype, view, fov):
225
+ out.loc[mask, "modality_family"] = family
226
+ out.loc[mask, "modality_subtype"] = subtype
227
+ out.loc[mask, "view_or_projection"] = view
228
+ out.loc[mask, "field_of_view"] = fov
229
+
230
+ mod = out["modality"].fillna("").astype(str)
231
+ anatomy = out.get("anatomy", pd.Series("", index=out.index)).fillna("").astype(str)
232
+ technology = out.get("device_technology", pd.Series("", index=out.index)).fillna("").astype(str)
233
+ protocol = out.get("scan_protocol", pd.Series("", index=out.index)).fillna("").astype(str)
234
+
235
+ anterior_fundus = mod.eq("fundus_color") & (
236
+ anatomy.eq("anterior_segment") | technology.eq("external_photography")
237
+ )
238
+ set_mask(anterior_fundus, "anterior_segment_photography", "external_anterior_segment_photo", "single_shot", "anterior_segment")
239
+ set_mask(mod.eq("fundus_color") & ~anterior_fundus, "color_fundus_photography", "standard_color_fundus", "single_shot", "standard")
240
+ set_mask(mod.eq("uwf"), "color_fundus_photography", "uwf_color_fundus", "single_shot", "ultra_widefield")
241
+ set_mask(mod.eq("ffa"), "fluorescein_angiography", "fundus_fluorescein_angiography", "angiography", "standard")
242
+ set_mask(mod.eq("oct_bscan"), "structural_oct", "oct_bscan", "bscan", "macula")
243
+ set_mask(mod.eq("oct_enface"), "structural_oct", "oct_enface", "en_face_projection", "macula")
244
+ set_mask(mod.isin(["octa", "octa_enface"]), "oct_angiography", "octa_enface", "en_face_projection", "macula")
245
+ set_mask(mod.isin(["slo_gray", "ir_slo"]), "scanning_laser_ophthalmoscopy", "reflectance_slo_gray", "en_face_reflectance", "macula")
246
+ set_mask(mod.eq("bscan_us"), "ocular_ultrasound", "ocular_bscan_ultrasound", "bscan", "globe")
247
+ set_mask(mod.eq("ubm"), "ultrasound_biomicroscopy", "ubm_anterior_segment", "bscan", "anterior_segment")
248
+ set_mask(mod.eq("slit_lamp"), "anterior_segment_photography", "slit_lamp_anterior_segment", "single_shot", "anterior_segment")
249
+
250
+ optic = anatomy.eq("optic_disc")
251
+ out.loc[optic & mod.eq("oct_bscan"), "field_of_view"] = "optic_disc"
252
+ out.loc[optic & mod.isin(["slo_gray", "ir_slo"]), "field_of_view"] = "optic_disc"
253
+ wide = anatomy.eq("wide-field") | protocol.str.contains("wide", case=False, na=False) | mod.eq("uwf")
254
+ out.loc[wide, "field_of_view"] = "ultra_widefield"
255
+
256
+ tax_cols = out[["modality_family", "modality_subtype", "view_or_projection", "field_of_view"]]
257
+ out["prompt_modality_phrase"] = [
258
+ hierarchical_phrase(row)
259
+ for row in tax_cols.to_dict("records")
260
+ ]
261
+ diag = out.get("diagnosis_group", pd.Series([None] * len(out), index=out.index))
262
+ out["diagnosis_group_clean"] = ["; ".join(clean_diagnosis_group(v)) for v in diag]
263
+ counts = out["modality_subtype"].value_counts()
264
+ out["subtype_sample_status"] = out["modality_subtype"].map(
265
+ lambda s: "formal" if counts.get(s, 0) >= 2000 else ("supplemental" if counts.get(s, 0) >= 500 else "tiny")
266
+ )
267
+ return out
268
+
269
+
270
+ def build_captions(manifest, old_captions, out_path: Path, chunk_size: int) -> int:
271
+ import pandas as pd
272
+ import pyarrow as pa
273
+ import pyarrow.parquet as pq
274
+
275
+ caps = old_captions[["image_id", "level", "prompt_text"]].copy()
276
+ caps["image_id"] = caps["image_id"].astype(str)
277
+ caps = caps.drop_duplicates(["image_id", "level"], keep="first")
278
+ wide = caps.pivot(index="image_id", columns="level", values="prompt_text")
279
+
280
+ ids = manifest["image_id"].astype(str).reset_index(drop=True)
281
+ tax_records = manifest[
282
+ ["modality_family", "modality_subtype", "view_or_projection", "field_of_view"]
283
+ ].to_dict("records")
284
+ diagnoses = manifest["diagnosis_group_clean"].astype(str).replace("nan", "").reset_index(drop=True)
285
+ old_short = wide["short"].reindex(ids).reset_index(drop=True) if "short" in wide else pd.Series([None] * len(ids))
286
+ old_medium = wide["medium"].reindex(ids).reset_index(drop=True) if "medium" in wide else pd.Series([None] * len(ids))
287
+ old_dense = wide["dense"].reindex(ids).reset_index(drop=True) if "dense" in wide else pd.Series([None] * len(ids))
288
+ source_by_level = {
289
+ "short": old_short,
290
+ "medium": old_medium.combine_first(old_dense).combine_first(old_short),
291
+ "dense": old_dense.combine_first(old_medium).combine_first(old_short),
292
+ }
293
+
294
+ schema = pa.schema(
295
+ [
296
+ ("caption_id", pa.string()),
297
+ ("image_id", pa.string()),
298
+ ("level", pa.string()),
299
+ ("prompt_text", pa.string()),
300
+ ("language", pa.string()),
301
+ ("generator", pa.string()),
302
+ ("grounded_in", pa.string()),
303
+ ]
304
+ )
305
+ if out_path.exists():
306
+ out_path.unlink()
307
+ writer = pq.ParquetWriter(out_path, schema, compression="zstd")
308
+ total = 0
309
+ try:
310
+ for start in range(0, len(ids), chunk_size):
311
+ end = min(start + chunk_size, len(ids))
312
+ frames = []
313
+ id_chunk = ids.iloc[start:end].tolist()
314
+ tax_chunk = tax_records[start:end]
315
+ diag_chunk = diagnoses.iloc[start:end].tolist()
316
+ for level in ["short", "medium", "dense"]:
317
+ old_chunk = source_by_level[level].iloc[start:end].tolist()
318
+ prompt_text = [
319
+ rewrite_prompt(old, level, tax, diag)
320
+ for old, tax, diag in zip(old_chunk, tax_chunk, diag_chunk, strict=True)
321
+ ]
322
+ frames.append(
323
+ pd.DataFrame(
324
+ {
325
+ "caption_id": [f"{image_id}_{level}" for image_id in id_chunk],
326
+ "image_id": id_chunk,
327
+ "level": level,
328
+ "prompt_text": prompt_text,
329
+ "language": "en",
330
+ "generator": "mixed_prompt_adapter_v6_hierarchical_taxonomy",
331
+ "grounded_in": "v6_taxonomy+clean_diagnosis+v5_descriptors",
332
+ }
333
+ )
334
+ )
335
+ table = pa.Table.from_pandas(pd.concat(frames, ignore_index=True), schema=schema, preserve_index=False)
336
+ writer.write_table(table)
337
+ total += table.num_rows
338
+ print(f"captions={total}", flush=True)
339
+ finally:
340
+ writer.close()
341
+ return total
342
+
343
+
344
+ def write_summary(out: Path, manifest, caption_rows: int) -> None:
345
+ summary = {
346
+ "rows": int(len(manifest)),
347
+ "captions": int(caption_rows),
348
+ "taxonomy_version": VERSION,
349
+ "by_modality": manifest.groupby("modality").size().astype(int).to_dict(),
350
+ "by_modality_family": manifest.groupby("modality_family").size().astype(int).to_dict(),
351
+ "by_modality_subtype": manifest.groupby("modality_subtype").size().astype(int).to_dict(),
352
+ "by_subtype_sample_status": manifest.groupby("subtype_sample_status").size().astype(int).to_dict(),
353
+ }
354
+ (out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
355
+
356
+
357
+ def write_readme(out: Path, manifest_rows: int, caption_rows: int) -> None:
358
+ text = f"""# Mixed Prompt Adapter v6
359
+
360
+ Rows: {manifest_rows}
361
+ Caption rows: {caption_rows}
362
+
363
+ Changes from v5:
364
+
365
+ - Prompt prefixes are hierarchical: modality family + view/projection +
366
+ field-of-view/anatomy.
367
+ - `ir_slo` rows are folded into `reflectance_slo_gray`; 42 images are too few
368
+ for an independent subtype.
369
+ - `diagnosis_group_clean` removes dataset split/source tokens such as
370
+ `train`, `test`, `val`, and `eryuan`.
371
+ - `subtype_sample_status` marks formal/supplemental/tiny groups for reporting.
372
+
373
+ Prompt policy:
374
+
375
+ - `short`: imaging condition only.
376
+ - `medium` and `dense`: imaging condition plus cleaned diagnosis and existing
377
+ cleaned descriptors.
378
+ """
379
+ (out / "README.md").write_text(text, encoding="utf-8")
380
+
381
+
382
+ def main() -> None:
383
+ import pandas as pd
384
+
385
+ args = parse_args()
386
+ args.out.mkdir(parents=True, exist_ok=True)
387
+ manifest_in = args.input / "adapter_manifest_mixed_v5.parquet"
388
+ captions_in = args.input / "captions_v2.parquet"
389
+ manifest_out = args.out / "adapter_manifest_mixed_v6.parquet"
390
+ captions_out = args.out / "captions_v2.parquet"
391
+
392
+ if not args.overwrite:
393
+ for path in [manifest_out, captions_out]:
394
+ if path.exists():
395
+ raise FileExistsError(f"{path} exists; pass --overwrite")
396
+
397
+ manifest = pd.read_parquet(manifest_in)
398
+ if args.limit:
399
+ manifest = manifest.head(args.limit).copy()
400
+ manifest = add_v6_columns(manifest)
401
+ manifest.to_parquet(manifest_out, index=False, compression="zstd")
402
+
403
+ captions = pd.read_parquet(captions_in, columns=["image_id", "level", "prompt_text"])
404
+ caption_rows = build_captions(manifest, captions, captions_out, args.chunk_size)
405
+ write_summary(args.out, manifest, caption_rows)
406
+ write_readme(args.out, len(manifest), caption_rows)
407
+ print(json.dumps({"out": str(args.out), "rows": len(manifest), "captions": caption_rows}, ensure_ascii=False))
408
+
409
+
410
+ def parse_args() -> argparse.Namespace:
411
+ parser = argparse.ArgumentParser()
412
+ parser.add_argument("--input", type=Path, default=DEFAULT_IN)
413
+ parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
414
+ parser.add_argument("--chunk-size", type=int, default=250_000)
415
+ parser.add_argument("--limit", type=int, default=None)
416
+ parser.add_argument("--overwrite", action="store_true")
417
+ return parser.parse_args()
418
+
419
+
420
+ def _tax(family: str, subtype: str, view: str, fov: str, technology: str, protocol: str) -> dict[str, str]:
421
+ return {
422
+ "taxonomy_version": VERSION,
423
+ "modality_family": family,
424
+ "modality_subtype": subtype,
425
+ "view_or_projection": view,
426
+ "field_of_view": fov,
427
+ "device_or_acquisition_protocol": f"{technology or 'unknown'}/{protocol or 'unknown'}",
428
+ "prompt_modality_phrase": "",
429
+ }
430
+
431
+
432
+ def _posterior_fov(anatomy: str, default: str) -> str:
433
+ if anatomy == "optic_disc":
434
+ return "optic_disc"
435
+ if anatomy in {"wide-field", "widefield", "ultra_widefield"}:
436
+ return "ultra_widefield"
437
+ if anatomy == "macula":
438
+ return "macula"
439
+ return default
440
+
441
+
442
+ def _fov_text(value: str) -> str:
443
+ return {
444
+ "standard": "standard",
445
+ "macula": "macula",
446
+ "optic_disc": "optic disc",
447
+ "ultra_widefield": "ultra-widefield",
448
+ "anterior_segment": "anterior segment",
449
+ "globe": "globe",
450
+ }.get(str(value), str(value).replace("_", " "))
451
+
452
+
453
+ def _join_prompt_parts(*parts: str) -> str:
454
+ return _squash(", ".join(part for part in parts if part and part != "unknown"))
455
+
456
+
457
+ def _clean(value: Any) -> str:
458
+ if value is None:
459
+ return ""
460
+ if isinstance(value, float) and math.isnan(value):
461
+ return ""
462
+ return str(value).strip()
463
+
464
+
465
+ def _squash(text: str) -> str:
466
+ return re.sub(r"\s+", " ", str(text).strip())
467
+
468
+
469
+ if __name__ == "__main__":
470
+ main()
tools/data_processing/taxonomy/test_build_mixed_v6_taxonomy.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import unittest
3
+ from pathlib import Path
4
+
5
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
6
+
7
+ from build_mixed_v6_taxonomy import (
8
+ clean_diagnosis_group,
9
+ derive_taxonomy,
10
+ rewrite_prompt,
11
+ )
12
+
13
+
14
+ class BuildMixedV6TaxonomyTest(unittest.TestCase):
15
+ def test_ir_slo_is_folded_into_reflectance_slo_not_own_subtype(self):
16
+ tax = derive_taxonomy(
17
+ {
18
+ "modality": "ir_slo",
19
+ "anatomy": "macula",
20
+ "device_technology": "slo",
21
+ "scan_protocol": "infrared",
22
+ }
23
+ )
24
+
25
+ self.assertEqual(tax["modality_family"], "scanning_laser_ophthalmoscopy")
26
+ self.assertEqual(tax["modality_subtype"], "reflectance_slo_gray")
27
+ self.assertEqual(tax["view_or_projection"], "en_face_reflectance")
28
+
29
+ def test_hierarchical_prompt_names_family_view_and_anatomy(self):
30
+ tax = derive_taxonomy(
31
+ {
32
+ "modality": "oct_bscan",
33
+ "anatomy": "macula",
34
+ "device_technology": "sd_oct",
35
+ "scan_protocol": "volume_3d_macula",
36
+ }
37
+ )
38
+
39
+ prompt = rewrite_prompt("OCT B-scan, normal", "short", tax)
40
+
41
+ self.assertIn("ophthalmic image", prompt)
42
+ self.assertIn("structural OCT", prompt)
43
+ self.assertIn("B-scan view", prompt)
44
+ self.assertIn("macula", prompt)
45
+
46
+ def test_split_tokens_are_removed_from_clean_diagnosis_group(self):
47
+ self.assertEqual(
48
+ clean_diagnosis_group("['diabetic retinopathy' 'train']"),
49
+ ["diabetic retinopathy"],
50
+ )
51
+ self.assertEqual(clean_diagnosis_group("['normal' 'eryuan']"), ["normal"])
52
+ self.assertEqual(clean_diagnosis_group("[]"), [])
53
+
54
+ def test_rewrite_prompt_removes_split_tokens_from_descriptor(self):
55
+ tax = derive_taxonomy({"modality": "fundus_color", "anatomy": "retina"})
56
+
57
+ prompt = rewrite_prompt(
58
+ "color fundus photograph, diabetic retinopathy, train",
59
+ "medium",
60
+ tax,
61
+ )
62
+
63
+ self.assertIn("diabetic retinopathy", prompt)
64
+ self.assertNotIn("train", prompt.lower())
65
+
66
+ def test_rewrite_prompt_removes_folded_ir_slo_legacy_prefix(self):
67
+ tax = derive_taxonomy({"modality": "ir_slo", "anatomy": "macula"})
68
+
69
+ prompt = rewrite_prompt(
70
+ "infrared scanning laser ophthalmoscopy image",
71
+ "medium",
72
+ tax,
73
+ )
74
+
75
+ self.assertEqual(
76
+ prompt,
77
+ "ophthalmic image, scanning laser ophthalmoscopy, reflectance en face view, macula",
78
+ )
79
+
80
+
81
+ if __name__ == "__main__":
82
+ unittest.main()
tools/data_processing/taxonomy/test_taxonomy_sampling.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import types
3
+ import unittest
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
9
+
10
+ omegaconf_stub = types.ModuleType("omegaconf")
11
+ omegaconf_stub.OmegaConf = object
12
+ omegaconf_stub.DictConfig = object
13
+ sys.modules.setdefault("omegaconf", omegaconf_stub)
14
+
15
+ data_stub = types.ModuleType("data")
16
+ octflow_stub = types.ModuleType("data.octflow_dataset")
17
+ octflow_stub.OCTFlowDataset = object
18
+ sys.modules.setdefault("data", data_stub)
19
+ sys.modules.setdefault("data.octflow_dataset", octflow_stub)
20
+
21
+ from train_sd3_t2i import build_balanced_sampling_weights
22
+
23
+
24
+ class TaxonomySamplingTest(unittest.TestCase):
25
+ def test_temperature_sampling_gives_each_group_equal_total_weight_at_zero_temperature(self):
26
+ labels = np.array(["fundus"] * 8 + ["ubm"] * 2)
27
+
28
+ weights, counts, targets = build_balanced_sampling_weights(
29
+ labels,
30
+ temperature=0.0,
31
+ min_count=1,
32
+ )
33
+
34
+ self.assertEqual(counts, {"fundus": 8, "ubm": 2})
35
+ self.assertAlmostEqual(weights[:8].sum(), weights[8:].sum(), places=8)
36
+ self.assertEqual(set(targets), {"fundus", "ubm"})
37
+
38
+ def test_min_count_excludes_tiny_groups(self):
39
+ labels = np.array(["fundus"] * 8 + ["ir_slo"] * 2)
40
+
41
+ weights, counts, targets = build_balanced_sampling_weights(
42
+ labels,
43
+ temperature=0.5,
44
+ min_count=3,
45
+ )
46
+
47
+ self.assertEqual(counts, {"fundus": 8, "ir_slo": 2})
48
+ self.assertGreater(weights[:8].sum(), 0.0)
49
+ self.assertEqual(weights[8:].sum(), 0.0)
50
+ self.assertEqual(targets, {"fundus": 1.0})
51
+
52
+
53
+ if __name__ == "__main__":
54
+ unittest.main()