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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
"""Build prompt QC samples for the de-identified new-data manifest."""

from __future__ import annotations

import argparse
import html
import io
import math
import re
import tarfile
from pathlib import Path
from typing import Any

import pandas as pd
from PIL import Image, ImageOps


DEFAULT_MANIFEST = Path(
    "/data/team/lisicheng/new_data_manifest/"
    "new_data_manifest_dedup_split_labeled_with_wds_deid.parquet"
)
DEFAULT_OUT = Path("/data/team/lisicheng/new_data_manifest/prompt_qc")

MODALITY_TEXT = {
    "fundus_color": "color fundus photograph",
    "oct_bscan": "OCT B-scan",
    "octa": "optical coherence tomography angiography image",
    "ffa": "fluorescein fundus angiography image",
    "bscan_us": "ocular B-scan ultrasound image",
    "ubm": "ultrasound biomicroscopy image",
    "uwf": "ultra-widefield fundus photograph",
}

BANNED_PROMPT_TERMS = {
    "tongren",
    "xiangya",
    "yinhai",
    "chengdu",
    "eryuan",
    "handan",
    "data0410",
    "hcw",
    "fq_unlabeled",
    "mixed_unlabeled",
    "octbuckets",
    "train",
    "test",
    "internal_test",
    "external_test",
    "unlabeled",
}

DIAG_MAP = {
    "amd": "age-related macular degeneration",
    "年龄相关性黄斑变性": "age-related macular degeneration",
    "老年性黄斑变性": "age-related macular degeneration",
    "dr": "diabetic retinopathy",
    "糖尿病视网膜病变": "diabetic retinopathy",
    "糖网": "diabetic retinopathy",
    "normal": "normal",
    "正常": "normal",
    "rvo": "retinal vein occlusion",
    "视网膜静脉阻塞": "retinal vein occlusion",
    "csc": "central serous chorioretinopathy",
    "中心性浆液性脉络膜视网膜病变": "central serous chorioretinopathy",
    "中浆": "central serous chorioretinopathy",
    "erm": "epiretinal membrane",
    "黄斑前膜": "epiretinal membrane",
    "mh": "macular hole",
    "黄斑裂孔": "macular hole",
    "rao": "retinal artery occlusion",
    "视网膜动脉阻塞": "retinal artery occlusion",
    "rd": "retinal detachment",
    "视网膜脱离": "retinal detachment",
    "vkh": "Vogt-Koyanagi-Harada disease",
    "葡萄膜炎": "uveitis",
    "青光眼": "glaucoma",
    "白内障": "cataract",
}

FINDING_RULES = [
    (re.compile(r"玻璃体混浊|中低回声光点|中低回声光斑"), "vitreous opacity"),
    (re.compile(r"玻璃体积血"), "vitreous hemorrhage"),
    (re.compile(r"玻璃体后脱离"), "posterior vitreous detachment"),
    (re.compile(r"后巩膜葡萄肿"), "posterior staphyloma"),
    (re.compile(r"视网膜脱离"), "retinal detachment"),
    (re.compile(r"视网膜裂孔"), "retinal tear"),
    (re.compile(r"眼内占位|占位性病变"), "intraocular mass"),
    (re.compile(r"脉络膜黑色素瘤"), "choroidal melanoma"),
    (re.compile(r"硅油眼"), "silicone oil eye"),
    (re.compile(r"黄斑囊样水肿|黄斑水肿|囊样水肿"), "macular edema"),
    (re.compile(r"黄斑前膜"), "epiretinal membrane"),
    (re.compile(r"黄斑裂孔"), "macular hole"),
    (re.compile(r"分支静脉阻塞"), "branch retinal vein occlusion"),
    (re.compile(r"视网膜静脉阻塞|静脉阻塞"), "retinal vein occlusion"),
    (re.compile(r"视网膜动脉阻塞|动脉阻塞"), "retinal artery occlusion"),
    (re.compile(r"糖尿病视网膜病变|糖网"), "diabetic retinopathy"),
    (re.compile(r"高血压视网膜病变"), "hypertensive retinopathy"),
    (re.compile(r"新生血管|CNV", re.I), "neovascularization"),
    (re.compile(r"荧光渗漏|渗漏"), "fluorescein leakage"),
    (re.compile(r"无灌注"), "capillary nonperfusion"),
    (re.compile(r"微动脉瘤"), "microaneurysms"),
    (re.compile(r"硬性渗出|硬渗"), "hard exudates"),
    (re.compile(r"棉絮斑"), "cotton-wool spots"),
    (re.compile(r"出血"), "retinal hemorrhage"),
    (re.compile(r"视盘.*高荧光|视盘.*渗漏"), "optic disc leakage"),
    (re.compile(r"房角开放"), "open anterior chamber angle"),
    (re.compile(r"房角偏窄|窄房角|房角狭窄"), "narrow anterior chamber angle"),
    (re.compile(r"虹膜平坦"), "flat iris configuration"),
    (re.compile(r"睫状体.*囊|囊样暗区|囊样无回声区"), "ciliary body cyst"),
    (re.compile(r"晶体内回声增强"), "lens opacity"),
    (re.compile(r"前房.*浅"), "shallow anterior chamber"),
]

PII_PATTERNS = [
    re.compile(r"(姓名|患者姓名|病人姓名|name)\s*[::]?\s*[\u4e00-\u9fffA-Za-z·]{1,8}", re.I),
    re.compile(r"(ID号|\bID\b|编号|住院号|门诊号|检查号|patient\s*id)\s*[::]?\s*[A-Za-z0-9_-]+", re.I),
    re.compile(r"(检查日期|出生日期|DOB)\s*[::]?\s*\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?", re.I),
    re.compile(r"\b\d{4}[-/.年]\d{1,2}[-/.月]\d{1,2}(?:日)?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?\b"),
    re.compile(r"\b\d{8,}\b"),
]


def clean_text(text: Any) -> str:
    if text is None:
        return ""
    if isinstance(text, float) and math.isnan(text):
        return ""
    out = str(text)
    for pattern in PII_PATTERNS:
        out = pattern.sub("", out)
    out = re.sub(r"(医师签名|医生签名|签名|建议门诊|门诊时间).*", "", out, flags=re.I)
    out = re.sub(r"(待删|删除)", "", out)
    out = re.sub(r"\s+", " ", out)
    out = re.sub(r"[,。;;,\s]+$", "", out)
    return out.strip(" ,。;;,")


def build_prompts(row: dict[str, Any]) -> dict[str, str]:
    modality = str(row.get("modality") or "")
    base = base_prompt(row, modality)
    descriptors = _clinical_descriptors(row)
    demographics = _demographics(row)

    short_parts = [base]
    medium_parts = [base] + demographics + descriptors[:3]
    dense_parts = [base] + demographics + descriptors[:8]

    return {
        "short": _join(short_parts),
        "medium": _join(medium_parts),
        "dense": _join(dense_parts),
    }


def base_prompt(row: dict[str, Any], modality: str) -> str:
    if str(row.get("cohort") or "") == "tongren_external_fundus":
        return "anterior segment photograph"
    return MODALITY_TEXT.get(modality, f"{modality.replace('_', ' ')} ophthalmic image")


def main() -> None:
    args = parse_args()
    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / "imgs").mkdir(exist_ok=True)

    df = pd.read_parquet(args.manifest)
    df = df[df.get("split", "train") == "train"].copy() if "split" in df.columns else df.copy()
    for col in ["center", "modality"]:
        if col not in df.columns:
            raise KeyError(f"manifest missing {col!r}")

    samples = sample_by_center_modality(df, args.per_group, args.seed)
    records = []
    caption_rows = []
    for idx, row in enumerate(samples.to_dict("records")):
        prompts = build_prompts(row)
        for level, prompt in prompts.items():
            caption_rows.append(
                {"image_id": row["image_id"], "level": level, "prompt_text": prompt}
            )
        image_rel = render_thumb(row, args.out / "imgs", idx, args.thumb)
        record = {
            "idx": idx,
            "image_rel": image_rel,
            "prompts": prompts,
            **{k: row.get(k) for k in [
                "image_id",
                "center",
                "modality",
                "cohort",
                "diagnosis_raw",
                "group_raw",
                "diagnosis_group",
                "caption",
                "train_path",
                "pii_masked",
                "ocr_age",
                "ocr_sex",
                "ocr_eye",
            ]},
        }
        records.append(record)

    caps = pd.DataFrame(caption_rows)
    caps.to_parquet(args.out / "prompt_qc_captions.parquet", index=False)
    caps.to_csv(args.out / "prompt_qc_captions.csv", index=False)
    write_html(records, args.out / "prompt_qc.html")
    write_design(args.out / "prompt_design.md")
    print(f"DONE -> {args.out / 'prompt_qc.html'} ({len(records)} samples)")


def sample_by_center_modality(df: pd.DataFrame, n: int, seed: int) -> pd.DataFrame:
    groups = []
    for (_, _), group in df.groupby(["center", "modality"], dropna=False):
        groups.append(group.sample(n=min(n, len(group)), random_state=seed))
    out = pd.concat(groups, ignore_index=True)
    return out.sort_values(["modality", "center", "cohort", "image_id"]).reset_index(drop=True)


def render_thumb(row: dict[str, Any], img_dir: Path, idx: int, size: int) -> str:
    path = str(row.get("train_path") or row.get("file_path"))
    name = f"{idx:04d}_{safe_name(row.get('modality'))}_{safe_name(row.get('center'))}.jpg"
    out = img_dir / name
    try:
        if "::" in path:
            im = open_wds_member(path).convert("RGB")
        else:
            im = Image.open(path).convert("RGB")
        im.thumbnail((size, size), Image.Resampling.LANCZOS)
        canvas = Image.new("RGB", (size, size), (0, 0, 0))
        canvas.paste(im, ((size - im.width) // 2, (size - im.height) // 2))
        im = canvas
        im.save(out, quality=90)
    except Exception:
        im = Image.new("RGB", (size, size), (80, 20, 20))
        im = ImageOps.expand(im, border=2, fill=(255, 0, 0))
        im.save(out, quality=90)
    return f"imgs/{name}"


def open_wds_member(path: str) -> Image.Image:
    tar_path, member_name = path.split("::", 1)
    with tarfile.open(tar_path, "r:*") as tf:
        member = tf.getmember(member_name)
        fp = tf.extractfile(member)
        if fp is None:
            raise FileNotFoundError(path)
        data = fp.read()
    return Image.open(io.BytesIO(data))


def write_html(records: list[dict[str, Any]], out: Path) -> None:
    css = """
body{font-family:Arial,sans-serif;margin:20px;background:#f7f7f7;color:#222}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(460px,1fr));gap:14px}
.card{background:white;border:1px solid #ddd;border-radius:6px;padding:12px}
img{width:180px;height:180px;object-fit:contain;background:#000;float:left;margin-right:12px}
.meta{font-size:12px;color:#555;line-height:1.35}
.prompt{font-size:13px;margin:6px 0}.level{font-weight:bold;color:#333}
.caption{clear:both;font-size:12px;color:#555;border-top:1px solid #eee;margin-top:10px;padding-top:8px}
h1{margin-bottom:4px}.note{color:#555;margin-bottom:18px}
"""
    parts = [
        "<!doctype html><html><head><meta charset='utf-8'>",
        f"<style>{css}</style></head><body>",
        "<h1>New-data prompt QC</h1>",
        "<div class='note'>Grouped by center × modality, sampled 5 rows per group. "
        "Prompts intentionally exclude center/cohort names and raw identifiers.</div>",
        "<div class='grid'>",
    ]
    for r in records:
        parts.append("<div class='card'>")
        parts.append(f"<img src='{html.escape(r['image_rel'])}'>")
        parts.append("<div class='meta'>")
        for k in ["image_id", "modality", "center", "cohort", "pii_masked", "ocr_age", "ocr_sex", "ocr_eye"]:
            parts.append(f"<b>{k}</b>: {html.escape(str(r.get(k)))}<br>")
        parts.append(f"<b>train_path</b>: {html.escape(str(r.get('train_path'))[:180])}</div>")
        for level in ["short", "medium", "dense"]:
            parts.append(
                f"<div class='prompt'><span class='level'>{level}</span>: "
                f"{html.escape(r['prompts'][level])}</div>"
            )
        parts.append("<div class='caption'>")
        for k in ["diagnosis_raw", "group_raw", "diagnosis_group", "caption"]:
            v = r.get(k)
            if v is not None and not (isinstance(v, float) and math.isnan(v)):
                parts.append(f"<b>{k}</b>: {html.escape(str(v)[:400])}<br>")
        parts.append("</div></div>")
    parts.append("</div></body></html>")
    out.write_text("\n".join(parts), encoding="utf-8")


def write_design(out: Path) -> None:
    text = """# Prompt design logic

The training prompt space follows the previous private-data SD3 logic: each image has
multiple candidate prompts (`short`, `medium`, `dense`), and training samples one
prompt level at random per step.

Prompt levels:
- `short`: modality phrase only, matching the old private-data minimal prompt style.
- `medium`: modality phrase plus age/sex/eye if available and up to three English labels.
- `dense`: modality phrase plus age/sex/eye if available and up to eight English labels.

Modality phrases:
- `fundus_color`: color fundus photograph
- `tongren_external_fundus`: anterior segment photograph, overriding the
  `fundus_color` modality phrase because these images are external/anterior-eye photos.
- `uwf`: ultra-widefield fundus photograph
- `ffa`: fluorescein fundus angiography image
- `octa`: optical coherence tomography angiography image
- `bscan_us`: ocular B-scan ultrasound image
- `ubm`: ultrasound biomicroscopy image

Safety rules:
- Never include center, hospital, cohort, dataset name, file name, ID, exact date, DOB, or raw OCR text.
- Store only non-identifying OCR-derived attributes: age, sex, eye laterality.
- Rows without labels still receive a modality-only prompt.
- Long free-text reports are never copied into prompts; they are reduced to English finding labels.
"""
    out.write_text(text, encoding="utf-8")


def _clinical_descriptors(row: dict[str, Any]) -> list[str]:
    desc: list[str] = []
    for key in ["diagnosis_raw", "diagnosis_group", "group_raw"]:
        val = clean_text(row.get(key))
        val = translate_diag(val)
        candidates = [val] if _is_prompt_ready_label(val) else extract_finding_tags(val)
        _extend_unique(desc, candidates)
    cap = clean_text(row.get("caption"))
    _extend_unique(desc, extract_finding_tags(cap))
    return desc


def extract_finding_tags(text: str) -> list[str]:
    if not text:
        return []
    tags = [label for pattern, label in FINDING_RULES if pattern.search(text)]
    return _unique(tags)


def _extend_unique(out: list[str], values: list[str]) -> None:
    seen = {v.lower() for v in out}
    for value in values:
        if _allowed_descriptor(value) and value.lower() not in seen:
            out.append(value)
            seen.add(value.lower())


def _unique(values: list[str]) -> list[str]:
    out = []
    seen = set()
    for value in values:
        key = value.lower()
        if key not in seen:
            out.append(value)
            seen.add(key)
    return out


def _is_prompt_ready_label(text: str) -> bool:
    if not _allowed_descriptor(text):
        return False
    if re.search(r"[\u4e00-\u9fff]", text):
        return False
    return _is_concise_label(text)


def _allowed_descriptor(text: str) -> bool:
    if not text:
        return False
    lowered = text.lower().strip()
    if lowered in BANNED_PROMPT_TERMS:
        return False
    if "_" in text or re.match(r"^group\d+\b", lowered):
        return False
    return not any(term in lowered for term in BANNED_PROMPT_TERMS)


def _is_concise_label(text: str) -> bool:
    if len(text) > 80:
        return False
    return not re.search(r"[。;;]|提示|所见|检查", text)


def _clip_text(text: str, max_chars: int) -> str:
    if len(text) <= max_chars:
        return text
    return text[: max_chars - 3].rstrip(" ,。;;,") + "..."


def _demographics(row: dict[str, Any]) -> list[str]:
    out: list[str] = []
    age = row.get("ocr_age")
    if age is not None and not (isinstance(age, float) and math.isnan(age)):
        bucket = age_bucket(age)
        if bucket:
            out.append(bucket)
    sex = str(row.get("ocr_sex") or "").upper()
    if sex == "M":
        out.append("male")
    elif sex == "F":
        out.append("female")
    eye = str(row.get("ocr_eye") or "").upper()
    if eye == "OD":
        out.append("right eye")
    elif eye == "OS":
        out.append("left eye")
    elif eye == "OU":
        out.append("both eyes")
    if len(out) >= 2 and out[1] in {"male", "female"}:
        out = [f"{out[1]} patient {out[0]}"] + out[2:]
    return out


def age_bucket(age: Any) -> str:
    try:
        value = int(age)
    except (TypeError, ValueError):
        return ""
    if value < 0 or value > 120:
        return ""
    if value < 2:
        return "infant"
    if value < 13:
        return "child"
    if value < 20:
        return "teenage patient"
    decade = min((value // 10) * 10, 90)
    return f"in their {decade}s"


def _join(parts: list[str]) -> str:
    clean = [p for p in (clean_text(part) for part in parts) if p]
    return ", ".join(clean)


def translate_diag(text: str) -> str:
    if not text:
        return ""
    key = text.strip().lower()
    return DIAG_MAP.get(key, text.strip())


def safe_name(value: Any) -> str:
    return re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "na"))[:80]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
    parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
    parser.add_argument("--per-group", type=int, default=5)
    parser.add_argument("--seed", type=int, default=20260701)
    parser.add_argument("--thumb", type=int, default=320)
    return parser.parse_args()


if __name__ == "__main__":
    main()