""" ================================================================================ 脚本名称 (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("", "<\\/") labels_json = json.dumps(LABELS, ensure_ascii=False) css = """:root{--bg:#f4f6f8;--panel:#fff;--line:#d8dee8;--text:#1f2937;--muted:#64748b;--blue:#0f62fe;--green:#177245;--red:#b42318;--amber:#9a5b00}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:Arial,"Noto Sans CJK SC","Microsoft YaHei",sans-serif}header{position:sticky;top:0;z-index:10;background:var(--panel);border-bottom:1px solid var(--line);padding:12px 16px;box-shadow:0 1px 8px rgba(15,23,42,.07)}h1{font-size:18px;margin:0 0 8px}.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.muted{color:var(--muted);font-size:13px}.progress{font-size:13px;min-width:260px}.viewer{display:grid;grid-template-columns:minmax(420px,52vw) 1fr;gap:14px;padding:14px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:12px}.imgbox{height:min(70vh,720px);min-height:420px;background:#080808;display:flex;align-items:center;justify-content:center;overflow:hidden;border:1px solid #111}.imgbox img{max-width:100%;max-height:100%;object-fit:contain}.badge{display:inline-block;border-radius:999px;padding:3px 8px;margin:0 5px 6px 0;font-size:12px;background:#edf2ff;color:#173b8f}.ok{background:#e8f5e9;color:#1b5e20}.warn{background:#fff7e6;color:#8a4b00}.bad{background:#ffecec;color:#9b1c1c}.meta{font-size:13px;line-height:1.5;word-break:break-word}.features{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px 12px;margin-top:8px;font-size:12px;color:#334155}.review{border-top:1px solid var(--line);margin-top:10px;padding-top:10px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0}button,select,input,textarea{font-size:13px;border:1px solid #b8c0cc;border-radius:4px;background:#fff;padding:7px 9px}button{cursor:pointer}button.primary{background:var(--blue);border-color:var(--blue);color:#fff}button.good{background:#e9f7ef;color:var(--green);border-color:#a8ddb9}button.drop{background:#fff1f0;color:var(--red);border-color:#ffccc7}textarea{width:100%;height:78px;resize:vertical}.path{font-family:monospace;font-size:12px;color:#334155}.hint{margin-top:6px;font-size:12px;color:var(--muted)}@media(max-width:1000px){.viewer{grid-template-columns:1fr}.imgbox{height:520px}}""" js = f""" const rows = JSON.parse(document.getElementById('rows-data').textContent); const labels = {labels_json}; const storageKey = 'octbuckets_octa_split_review_20260708'; let idx = Number(localStorage.getItem(storageKey + ':idx') || 0); let edits = JSON.parse(localStorage.getItem(storageKey) || '{{}}'); function esc(v) {{ return String(v ?? '').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='