"""Build an embedded HTML review page for high-risk training rows. This is a targeted human-QC sampler for prompt-adapter manifests. It does not modify source images or training manifests. """ from __future__ import annotations import argparse import base64 import csv import html import io import json import math import random import tarfile from pathlib import Path from typing import Any import pandas as pd from PIL import Image DEFAULT_MANIFEST = Path( "/data/team/lisicheng/new_data_manifest/" "prompt_adapter_mixed_v6_exclude_octbuckets_octa/adapter_manifest_mixed_v6.parquet" ) DEFAULT_CAPTIONS = Path( "/data/team/lisicheng/new_data_manifest/" "prompt_adapter_mixed_v6_exclude_octbuckets_octa/captions_v2.parquet" ) DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/v6_quality_risk_review_20260709") HIGH_RISK_COHORTS = [ "data0410_master_fundus", "chengdu_shiyi_ubm", "eryuan_ubm", "yinhai_ubm", "yinhai_bscan", "xiangya_bscan", "chengdu_bscan", "yinhai_uwf", "eryuan_ffa", "eryuan_t17_fundus", "hcw_fundus", ] DEID_SANITY_COHORTS = [ "fundus90wer", "tongren_fundus", "tongren_95disease_fundus", "tongren_external_fundus", "fq_rawfundus", "fq_testfundus", ] RARE_OR_CONFUSABLE_SUBTYPES = [ "octa_enface", "oct_enface", "slit_lamp_anterior_segment", "reflectance_slo_gray", "fundus_fluorescein_angiography", "uwf_color_fundus", "external_anterior_segment_photo", "ocular_bscan_ultrasound", "ubm_anterior_segment", ] class ImageOpener: def __init__(self) -> None: self._tar_cache: dict[str, tarfile.TarFile] = {} def close(self) -> None: for tf in self._tar_cache.values(): tf.close() self._tar_cache.clear() def open(self, path: str) -> Image.Image: if "::" not in path: return Image.open(path).convert("RGB") tar_path, member = path.split("::", 1) tf = self._tar_cache.get(tar_path) if tf is None: tf = tarfile.open(tar_path, "r:*") self._tar_cache[tar_path] = tf fh = tf.extractfile(member) if fh is None: raise FileNotFoundError(member) return Image.open(io.BytesIO(fh.read())).convert("RGB") def clean(value: Any) -> Any: if value is None: return None if isinstance(value, float) and math.isnan(value): return None return value def json_safe(value: Any) -> Any: if isinstance(value, dict): return {str(k): json_safe(v) for k, v in value.items()} if isinstance(value, list | tuple): return [json_safe(v) for v in value] if value is None: return None if isinstance(value, float): return value if math.isfinite(value) else None try: if pd.isna(value): return None except (TypeError, ValueError): pass return value def sample_group(group: pd.DataFrame, n: int, seed: int) -> pd.DataFrame: if len(group) <= n: return group return group.sample(n=n, random_state=seed) def add_samples( selected: dict[str, dict[str, Any]], frame: pd.DataFrame, reason: str, n: int, seed: int, group_col: str | None = None, ) -> None: if len(frame) == 0: return if group_col: pieces = [sample_group(g, n, seed) for _, g in frame.groupby(group_col, sort=True)] rows = pd.concat(pieces, ignore_index=True) if pieces else frame.head(0) else: rows = sample_group(frame, n, seed) for row in rows.to_dict("records"): image_id = str(row["image_id"]) if image_id in selected: selected[image_id]["risk_reason"] += f"; {reason}" else: row["risk_reason"] = reason selected[image_id] = row def build_review_rows(args: argparse.Namespace) -> tuple[list[dict[str, Any]], dict[str, Any]]: cols = [ "image_id", "cohort", "hospital_domain", "modality", "modality_family", "modality_subtype", "view_or_projection", "field_of_view", "image_quality_band", "image_quality_score", "image_height_px", "image_width_px", "file_path", "prompt_modality_phrase", "diagnosis_group_clean", ] df = pd.read_parquet(args.manifest, columns=cols) rng_seed = args.seed selected: dict[str, dict[str, Any]] = {} add_samples( selected, df[df["image_quality_band"].fillna("").astype(str).eq("poor")], "显式 poor quality", args.poor_per_modality, rng_seed, "modality_subtype", ) add_samples( selected, df[df["cohort"].astype(str).isin(HIGH_RISK_COHORTS)], "私有原始路径或水印/PII 高风险 cohort", args.high_risk_per_cohort, rng_seed + 1, "cohort", ) add_samples( selected, df[df["cohort"].astype(str).isin(DEID_SANITY_COHORTS)], "已脱敏大 cohort 抽查", args.deid_sanity_per_cohort, rng_seed + 2, "cohort", ) add_samples( selected, df[df["modality_subtype"].astype(str).isin(RARE_OR_CONFUSABLE_SUBTYPES)], "稀有或易混淆 subtype 抽查", args.rare_per_subtype, rng_seed + 3, "modality_subtype", ) top_cohorts = df["cohort"].value_counts().head(args.top_cohorts).index add_samples( selected, df[df["cohort"].astype(str).isin(top_cohorts.astype(str))], "大 cohort 随机兜底抽查", args.top_per_cohort, rng_seed + 4, "cohort", ) rows = list(selected.values()) random.Random(args.seed).shuffle(rows) if args.max_rows and len(rows) > args.max_rows: rows = rows[: args.max_rows] ids = [str(r["image_id"]) for r in rows] captions = pd.read_parquet(args.captions, columns=["image_id", "level", "prompt_text"]) captions["image_id"] = captions["image_id"].astype(str) wide = captions[captions["image_id"].isin(ids)].pivot(index="image_id", columns="level", values="prompt_text") opener = ImageOpener() records: list[dict[str, Any]] = [] try: for idx, row in enumerate(rows, start=1): image_id = str(row["image_id"]) thumb, open_error = thumbnail(opener, str(row["file_path"]), args.thumb_size) record = { "review_seq": idx, **{k: clean(v) for k, v in row.items()}, "short_prompt": clean(wide["short"].get(image_id)) if "short" in wide else None, "medium_prompt": clean(wide["medium"].get(image_id)) if "medium" in wide else None, "dense_prompt": clean(wide["dense"].get(image_id)) if "dense" in wide else None, "thumb_data": thumb, "open_error": open_error, } records.append(record) finally: opener.close() summary = { "manifest": str(args.manifest), "captions": str(args.captions), "rows_in_manifest": int(len(df)), "review_rows": int(len(records)), "risk_reason_counts": pd.Series([r["risk_reason"] for r in records]).value_counts().astype(int).to_dict(), "review_by_cohort": pd.Series([r["cohort"] for r in records]).value_counts().astype(int).to_dict(), "review_by_modality_subtype": pd.Series([r["modality_subtype"] for r in records]).value_counts().astype(int).to_dict(), "poor_quality_rows": int(df["image_quality_band"].fillna("").astype(str).eq("poor").sum()), "high_risk_cohort_rows": int(df["cohort"].astype(str).isin(HIGH_RISK_COHORTS).sum()), } return records, summary def thumbnail(opener: ImageOpener, path: str, size: int) -> tuple[str, str]: try: im = opener.open(path) 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)) err = "" except Exception as exc: canvas = Image.new("RGB", (size, size), (100, 15, 15)) err = repr(exc) buf = io.BytesIO() canvas.save(buf, format="JPEG", quality=88) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode("ascii"), err def write_csv(records: list[dict[str, Any]], out: Path) -> None: cols = [ "review_seq", "risk_reason", "image_id", "cohort", "hospital_domain", "modality", "modality_family", "modality_subtype", "view_or_projection", "field_of_view", "image_quality_band", "image_quality_score", "image_height_px", "image_width_px", "prompt_modality_phrase", "diagnosis_group_clean", "short_prompt", "medium_prompt", "dense_prompt", "file_path", "open_error", ] with out.open("w", newline="", encoding="utf-8-sig") as handle: writer = csv.DictWriter(handle, fieldnames=cols) writer.writeheader() for row in records: writer.writerow({col: row.get(col) for col in cols}) def write_html(records: list[dict[str, Any]], out: Path) -> None: rows_json = json.dumps(json_safe(records), ensure_ascii=False, allow_nan=False).replace(""']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); } function edit(id) { return edits[id] || {status:'unreviewed', issue:'', note:''}; } function save() { try { localStorage.setItem(storageKey, JSON.stringify(edits)); localStorage.setItem(storageKey + ':idx', String(idx)); } catch (_) {} } 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; } function go(delta) { idx=Math.max(0, Math.min(rows.length-1, idx+delta)); save(); render(); } function gotoIndex(v) { const n=Number(v); if (Number.isFinite(n)) { idx=Math.max(0, Math.min(rows.length-1, n-1)); save(); render(); } } 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(); } function updateNote(v) { const r=rows[idx]; edits[r.image_id]={...edit(r.image_id),note:v}; save(); } function mergedRows() { return rows.map(r=>{ const x={...r, ...edit(r.image_id)}; delete x.thumb_data; return x; }); } 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); } 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'); } function exportJSON() { download('octflow_v6_quality_risk_review_edits.json', JSON.stringify(mergedRows(), null, 2), 'application/json'); } function render() { if (!rows.length) { document.getElementById('root').innerHTML='
没有审核样本。
'; return; } const r=rows[idx], e=edit(r.image_id), c=counts(); 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}`; document.getElementById('jump').value=idx+1; document.getElementById('root').innerHTML=`
${esc(r.risk_reason)}${esc(r.modality_subtype)}${esc(r.cohort)}${r.open_error ? '读取错误' : ''}
图像 ID:${esc(r.image_id)}
cohort:${esc(r.cohort)};center:${esc(r.hospital_domain)}
modality:${esc(r.modality)};family:${esc(r.modality_family)};subtype:${esc(r.modality_subtype)}
view/fov:${esc(r.view_or_projection)} / ${esc(r.field_of_view)}
quality:${esc(r.image_quality_band)} / ${esc(r.image_quality_score)};size:${esc(r.image_width_px)} x ${esc(r.image_height_px)}
diagnosis:${esc(r.diagnosis_group_clean)}
路径:${esc(r.file_path)}${r.open_error ? '
读取错误:'+esc(r.open_error) : ''}
短 prompt:${esc(r.short_prompt)}
中 prompt:${esc(r.medium_prompt)}
快捷键:1 保留,2 水印,3 PII,4 错模态,5 低质,6 丢弃,←/→ 翻页,C 导出 CSV,J 导出 JSON。备注框内不会触发快捷键。
`; } document.addEventListener('keydown', ev => { const tag=(ev.target && ev.target.tagName || '').toLowerCase(); if (tag === 'input' || tag === 'textarea' || tag === 'select') return; if (ev.key === 'ArrowRight') go(1); else if (ev.key === 'ArrowLeft') go(-1); else if (ev.key === '1') setStatus('keep'); else if (ev.key === '2') setStatus('watermark'); else if (ev.key === '3') setStatus('pii'); else if (ev.key === '4') setStatus('wrong_modality', false); else if (ev.key === '5') setStatus('low_quality'); else if (ev.key === '6') setStatus('drop'); else if (ev.key.toLowerCase() === 'c') exportCSV(); else if (ev.key.toLowerCase() === 'j') exportJSON(); }); render(); """ doc = f"""OCTFlow v6 风险样本审核

OCTFlow v6 风险样本审核

风险导向抽样:poor quality、私有原始路径/水印高风险 cohort、已脱敏大 cohort 抽查、稀有或易混淆 subtype、大 cohort 兜底抽查。这里只用于人工 QC,不修改训练数据。
""" out.write_text(doc, encoding="utf-8") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) parser.add_argument("--captions", type=Path, default=DEFAULT_CAPTIONS) parser.add_argument("--out", type=Path, default=DEFAULT_OUT) parser.add_argument("--seed", type=int, default=20260709) parser.add_argument("--thumb-size", type=int, default=512) parser.add_argument("--poor-per-modality", type=int, default=20) parser.add_argument("--high-risk-per-cohort", type=int, default=6) parser.add_argument("--deid-sanity-per-cohort", type=int, default=4) parser.add_argument("--rare-per-subtype", type=int, default=8) parser.add_argument("--top-cohorts", type=int, default=20) parser.add_argument("--top-per-cohort", type=int, default=2) parser.add_argument("--max-rows", type=int, default=180) return parser.parse_args() def main() -> None: args = parse_args() args.out.mkdir(parents=True, exist_ok=True) records, summary = build_review_rows(args) write_csv(records, args.out / "risk_review_rows.csv") (args.out / "risk_review_rows.json").write_text( json.dumps(json_safe(records), ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8", ) (args.out / "summary.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8", ) write_html(records, args.out / "OPEN_THIS_V6_QUALITY_RISK_REVIEW.html") print(json.dumps({"out": str(args.out), **summary}, ensure_ascii=False), flush=True) if __name__ == "__main__": main()