""" ================================================================================ 脚本名称 (Script Name): split_octbuckets_octa_review.py 原本用途 (Original Purpose): 启发式多特征混杂 OCT 模态拆分与人工复审流水线。提取纵横比、边缘密度、层状结构评分(Layer score)与血管流信号评分(Vessel score),将打包混杂的 OCT 数据精准解耦分离为 B-scan、OCTA en-face 与 SLO 样图像。 适用数据集 (Target Dataset): archives/data0410/ 中的 octBuckets.zip(34,519 张多模态混合 OCT 图像)。 作者与归属 (Author/Provenance): 李思成 (Lisicheng), 浙江大学多模态眼科团队 输入要求 (Input): 包含混杂扫描模式的 octBuckets 图像集 输出结果 (Output): 按真实模态分类的 CSV 清单(oct_bscan, octa_enface, oct_enface_or_slo_like)及单张复审 HTML 依赖环境 (Dependencies): numpy, pandas, pillow, tarfile ================================================================================ """ """Split the mixed octbuckets_octa cohort into reviewable OCT subtypes. This script is read-only with respect to source images and training manifests. It produces: - auto_labels.csv: one row per image with heuristic subtype and features - review_candidates.csv: non-B-scan, uncertain, and sampled B-scan rows - OPEN_THIS_OCTBUCKETS_OCTA_REVIEW.html: single-image manual review page - thumbs/: local thumbnails referenced by the HTML """ from __future__ import annotations import argparse import html import io import json import random import re import tarfile from dataclasses import asdict, dataclass from pathlib import Path from typing import Any import numpy as np import pandas as pd from PIL import Image DEFAULT_MANIFEST = Path("/data/team/lisicheng/new_data_manifest/prompt_adapter_mixed_v6/adapter_manifest_mixed_v6.parquet") DEFAULT_OUT = Path("/data/team/lisicheng/Code/OCTFlow/pilot/path1/audit/octbuckets_octa_split_20260708") LABELS = ["oct_bscan", "octa_enface", "oct_enface_or_slo_like", "unknown"] @dataclass(frozen=True) class Classification: label: str confidence: float reason: str aspect_ratio: float edge_density: float horizontal_edge_ratio: float vertical_edge_ratio: float dark_fraction: float bright_fraction: float layer_score: float vessel_score: float enface_score: float 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 _to_gray_resized(arr: np.ndarray, size: int = 192) -> tuple[np.ndarray, float]: if arr.ndim == 3: gray = np.dot(arr[..., :3], [0.299, 0.587, 0.114]) else: gray = arr.astype(np.float32) h, w = gray.shape[:2] aspect = max(w / max(h, 1), h / max(w, 1)) im = Image.fromarray(np.clip(gray, 0, 255).astype(np.uint8)).resize((size, size), Image.Resampling.BILINEAR) out = np.asarray(im, dtype=np.float32) / 255.0 p1, p99 = np.percentile(out, [1, 99]) if p99 > p1 + 0.05: out = np.clip((out - p1) / (p99 - p1), 0, 1) return out, float(aspect) def classify_array(arr: np.ndarray) -> Classification: gray, aspect = _to_gray_resized(arr) gy, gx = np.gradient(gray) agx = np.abs(gx) agy = np.abs(gy) mag = agx + agy edge_threshold = max(float(np.quantile(mag, 0.86)), 0.035) edges = mag > edge_threshold edge_count = int(edges.sum()) total = int(edges.size) edge_density = edge_count / max(total, 1) if edge_count: horizontal = ((agy > agx * 1.20) & edges).sum() / edge_count vertical = ((agx > agy * 1.20) & edges).sum() / edge_count else: horizontal = 0.0 vertical = 0.0 dark_fraction = float((gray < 0.12).mean()) bright_fraction = float((gray > 0.78).mean()) row_profile = gray.mean(axis=1) col_profile = gray.mean(axis=0) row_variation = float(row_profile.std()) col_variation = float(col_profile.std()) anisotropy = abs(horizontal - vertical) layer_score = ( 0.52 * horizontal + 0.23 * min(row_variation / 0.18, 1.0) + 0.15 * min(dark_fraction / 0.45, 1.0) + 0.10 * min(aspect / 2.0, 1.0) ) vessel_score = ( 0.42 * min(edge_density / 0.18, 1.0) + 0.30 * min(bright_fraction / 0.14, 1.0) + 0.18 * max(0.0, 1.0 - anisotropy / 0.55) + 0.10 * min((row_variation + col_variation) / 0.28, 1.0) ) enface_score = ( 0.40 * max(0.0, 1.0 - min(aspect - 1.0, 1.0)) + 0.25 * max(0.0, 1.0 - min(layer_score / 0.72, 1.0)) + 0.20 * min(edge_density / 0.12, 1.0) + 0.15 * min(float(gray.std()) / 0.24, 1.0) ) if layer_score >= 0.54 and horizontal >= 0.42 and (dark_fraction >= 0.18 or aspect >= 1.35): label = "oct_bscan" confidence = min(0.98, 0.62 + (layer_score - 0.54) * 1.25 + max(0.0, horizontal - 0.42)) reason = "layer-dominant horizontal OCT cross-section" elif vessel_score >= 0.56 and layer_score < 0.58 and edge_density >= 0.08: label = "octa_enface" confidence = min(0.95, 0.55 + (vessel_score - 0.56) * 1.20 + max(0.0, edge_density - 0.08)) reason = "dense vessel-like en-face network" elif enface_score >= 0.56 and layer_score < 0.62 and aspect <= 1.45: label = "oct_enface_or_slo_like" confidence = min(0.90, 0.52 + (enface_score - 0.56) * 1.10) reason = "fundus-like gray en-face projection without dominant layers" else: label = "unknown" confidence = max(0.30, min(0.58, max(layer_score, vessel_score, enface_score))) reason = "ambiguous OCT/OCTA appearance" return Classification( label=label, confidence=round(float(confidence), 4), reason=reason, aspect_ratio=round(float(aspect), 4), edge_density=round(float(edge_density), 4), horizontal_edge_ratio=round(float(horizontal), 4), vertical_edge_ratio=round(float(vertical), 4), dark_fraction=round(float(dark_fraction), 4), bright_fraction=round(float(bright_fraction), 4), layer_score=round(float(layer_score), 4), vessel_score=round(float(vessel_score), 4), enface_score=round(float(enface_score), 4), ) def choose_review_rows( rows: list[dict[str, Any]], bscan_sample: int, uncertain_threshold: float, seed: int, ) -> list[dict[str, Any]]: selected: list[dict[str, Any]] = [] bscan_pool: list[dict[str, Any]] = [] seen: set[str] = set() for row in rows: label = str(row["auto_subtype"]) conf = float(row["confidence"]) image_id = str(row["image_id"]) needs_review = label != "oct_bscan" or conf < uncertain_threshold if needs_review: selected.append(row) seen.add(image_id) elif bscan_sample > 0: bscan_pool.append(row) rng = random.Random(seed) rng.shuffle(bscan_pool) for row in bscan_pool[:bscan_sample]: image_id = str(row["image_id"]) if image_id not in seen: selected.append(row) seen.add(image_id) return selected def save_thumb(im: Image.Image, out: Path, size: int) -> None: thumb = im.copy() thumb.thumbnail((size, size), Image.Resampling.LANCZOS) canvas = Image.new("RGB", (size, size), (245, 245, 245)) canvas.paste(thumb, ((size - thumb.width) // 2, (size - thumb.height) // 2)) canvas.save(out, quality=90) def safe_name(value: str) -> str: return re.sub(r"[^A-Za-z0-9_.-]+", "_", value)[:160] def build_html(records: list[dict[str, Any]], out: Path, title: str) -> None: rows_json = json.dumps(records, ensure_ascii=False).replace(""']/g, c => ({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[c])); }} function edit(id) {{ return edits[id] || {{status:'unreviewed', final_subtype:'', note:''}}; }} function save() {{ localStorage.setItem(storageKey, JSON.stringify(edits)); localStorage.setItem(storageKey + ':idx', String(idx)); }} function counts() {{ const c={{unreviewed:0,reviewed:0,drop:0}}; rows.forEach(r=>{{ const s=edit(r.image_id).status || 'unreviewed'; c[s]=(c[s]||0)+1; }}); return c; }} 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.isNaN(n)) {{ idx=Math.max(0,Math.min(rows.length-1,n-1)); save(); render(); }} }} function setLabel(label, advance=true) {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,status:'reviewed',final_subtype:label}}; save(); if (advance) go(1); else render(); }} function dropRow() {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,status:'drop',final_subtype:'exclude'}}; save(); go(1); }} function updateNote(v) {{ const r=rows[idx]; const e=edit(r.image_id); edits[r.image_id]={{...e,note:v}}; save(); }} function mergedRows() {{ return rows.map(r=>{{ const e=edit(r.image_id); return {{...r,status:e.status||'unreviewed',final_subtype:e.final_subtype||r.auto_subtype,note:e.note||''}}; }}); }} 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=['image_id','cohort','current_subtype','auto_subtype','confidence','status','final_subtype','note','reason','file_path']; const csv=[cols.join(',')].concat(out.map(o=>cols.map(c=>'"'+String(o[c]??'').replaceAll('"','""')+'"').join(','))).join('\\n'); download('octbuckets_octa_split_review_edits.csv', csv, 'text/csv'); }} function exportJSON() {{ download('octbuckets_octa_split_review_edits.json', JSON.stringify(mergedRows(), null, 2), 'application/json'); }} function labelSelect(current) {{ return ''; }} function badgeClass(r) {{ if (r.auto_subtype === 'oct_bscan' && Number(r.confidence) >= 0.65) return 'ok'; if (r.auto_subtype === 'unknown' || Number(r.confidence) < 0.60) return 'warn'; return 'bad'; }} function render() {{ if (!rows.length) {{ document.getElementById('root').innerHTML='
没有审核样本。
'; return; }} const r=rows[idx]; const e=edit(r.image_id); const final=e.final_subtype || r.auto_subtype; const c=counts(); document.getElementById('progress').textContent=`第 ${{idx+1}} / ${{rows.length}} 张;已看 ${{c.reviewed||0}},排除 ${{c.drop||0}},未看 ${{c.unreviewed||0}}`; document.getElementById('jump').value=idx+1; document.getElementById('root').innerHTML=`
自动:${{esc(r.auto_subtype)}} (${{Number(r.confidence).toFixed(2)}})当前:${{esc(r.current_subtype)}}最终:${{esc(final)}}
图像 ID:${{esc(r.image_id)}}
cohort:${{esc(r.cohort)}}
理由:${{esc(r.reason)}}
路径:${{esc(r.file_path)}}
aspect: ${{esc(r.aspect_ratio)}}
edge_density: ${{esc(r.edge_density)}}
horizontal: ${{esc(r.horizontal_edge_ratio)}}
vertical: ${{esc(r.vertical_edge_ratio)}}
dark: ${{esc(r.dark_fraction)}}
bright: ${{esc(r.bright_fraction)}}
layer_score: ${{esc(r.layer_score)}}
vessel_score: ${{esc(r.vessel_score)}}
enface_score: ${{esc(r.enface_score)}}
快捷键:1/2/3/4 标注并下一张,←/→ 上一张/下一张,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') setLabel('oct_bscan'); else if (ev.key === '2') setLabel('octa_enface'); else if (ev.key === '3') setLabel('oct_enface_or_slo_like'); else if (ev.key === '4') dropRow(); else if (ev.key.toLowerCase() === 'c') exportCSV(); else if (ev.key.toLowerCase() === 'j') exportJSON(); }}); render(); """ doc = f""" {html.escape(title)}

{html.escape(title)}

只审核自动非 B-scan、低置信度样本,以及抽样 B-scan。源图和 manifest 不会被修改。
""" out.write_text(doc, encoding="utf-8") def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) p.add_argument("--out", type=Path, default=DEFAULT_OUT) p.add_argument("--cohort", default="octbuckets_octa") p.add_argument("--limit", type=int, default=0, help="Debug limit; 0 means all rows.") p.add_argument("--seed", type=int, default=20260708) p.add_argument("--thumb-size", type=int, default=512) p.add_argument("--review-bscan-sample", type=int, default=300) p.add_argument("--uncertain-threshold", type=float, default=0.65) return p.parse_args() def main() -> None: args = parse_args() args.out.mkdir(parents=True, exist_ok=True) thumb_dir = args.out / "thumbs" thumb_dir.mkdir(parents=True, exist_ok=True) cols = ["image_id", "cohort", "modality", "modality_subtype", "file_path"] rows = pd.read_parquet(args.manifest, columns=cols) rows = rows[rows["cohort"].astype(str).eq(args.cohort)].copy() rows = rows.sort_values(["file_path", "image_id"]).reset_index(drop=True) if args.limit: rows = rows.head(args.limit).copy() print(f"[load] {len(rows)} rows from {args.manifest} cohort={args.cohort}", flush=True) opener = ImageOpener() records: list[dict[str, Any]] = [] try: for i, row in enumerate(rows.itertuples(index=False), start=1): try: im = opener.open(str(row.file_path)) arr = np.asarray(im) result = classify_array(arr) rec = { "image_id": str(row.image_id), "cohort": str(row.cohort), "modality": str(row.modality), "current_subtype": str(row.modality_subtype), "file_path": str(row.file_path), "auto_subtype": result.label, **asdict(result), "open_error": "", } except Exception as exc: rec = { "image_id": str(row.image_id), "cohort": str(row.cohort), "modality": str(row.modality), "current_subtype": str(row.modality_subtype), "file_path": str(row.file_path), "auto_subtype": "unknown", "label": "unknown", "confidence": 0.0, "reason": "open/classify error", "open_error": repr(exc), } records.append(rec) if i % 1000 == 0 or i == len(rows): print(f"[classify] {i}/{len(rows)}", flush=True) finally: opener.close() auto = pd.DataFrame(records) auto_path = args.out / "auto_labels.csv" auto.to_csv(auto_path, index=False) summary = { "rows": len(auto), "auto_subtype_counts": auto["auto_subtype"].value_counts(dropna=False).to_dict(), "open_errors": int((auto.get("open_error", "") != "").sum()) if "open_error" in auto else 0, "uncertain_threshold": args.uncertain_threshold, "review_bscan_sample": args.review_bscan_sample, } (args.out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") print("[summary]", json.dumps(summary, ensure_ascii=False), flush=True) review = choose_review_rows(records, args.review_bscan_sample, args.uncertain_threshold, args.seed) opener = ImageOpener() try: for i, rec in enumerate(review, start=1): thumb_name = f"{i:05d}_{safe_name(rec['image_id'])}.jpg" thumb_path = thumb_dir / thumb_name rec["thumb_rel"] = f"thumbs/{thumb_name}" if not thumb_path.exists(): try: save_thumb(opener.open(str(rec["file_path"])), thumb_path, args.thumb_size) except Exception as exc: rec["thumb_rel"] = "" rec["open_error"] = repr(exc) if i % 500 == 0 or i == len(review): print(f"[thumbs] {i}/{len(review)}", flush=True) finally: opener.close() review_path = args.out / "review_candidates.csv" pd.DataFrame(review).to_csv(review_path, index=False) html_path = args.out / "OPEN_THIS_OCTBUCKETS_OCTA_REVIEW.html" build_html(review, html_path, "octbuckets_octa 自动拆分人工审核") print(json.dumps({"out": str(args.out), "auto_labels": str(auto_path), "review_rows": len(review), "html": str(html_path)}, ensure_ascii=False), flush=True) if __name__ == "__main__": main()