Dataset / data_processing /04_modality_split /split_octbuckets_octa_review.py
Kaphathy's picture
Add standalone data_processing directory with per-script dataset mapping and detailed purpose comments
fe5b36e verified
Raw History Blame Contribute Delete
22.1 kB
"""
================================================================================
脚本名称 (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 => ({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[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 '<select onchange="setLabel(this.value,false)">' + labels.concat(['exclude']).map(x=>`<option value="${{esc(x)}}" ${{x===current?'selected':''}}>${{esc(x)}}</option>`).join('') + '</select>'; }}
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='<div class=viewer><div class=panel>没有审核样本。</div></div>'; 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=`<section class="viewer"><div class="panel"><div class="imgbox"><img src="${{esc(r.thumb_rel)}}" loading="eager"></div></div><div class="panel"><div><span class="badge ${{badgeClass(r)}}">自动:${{esc(r.auto_subtype)}} (${{Number(r.confidence).toFixed(2)}})</span><span class="badge">当前:${{esc(r.current_subtype)}}</span><span class="badge">最终:${{esc(final)}}</span></div><div class="meta"><b>图像 ID</b>:${{esc(r.image_id)}}<br><b>cohort</b>:${{esc(r.cohort)}}<br><b>理由</b>:${{esc(r.reason)}}<br><b>路径</b>:<span class="path">${{esc(r.file_path)}}</span></div><div class="features"><div>aspect: ${{esc(r.aspect_ratio)}}</div><div>edge_density: ${{esc(r.edge_density)}}</div><div>horizontal: ${{esc(r.horizontal_edge_ratio)}}</div><div>vertical: ${{esc(r.vertical_edge_ratio)}}</div><div>dark: ${{esc(r.dark_fraction)}}</div><div>bright: ${{esc(r.bright_fraction)}}</div><div>layer_score: ${{esc(r.layer_score)}}</div><div>vessel_score: ${{esc(r.vessel_score)}}</div><div>enface_score: ${{esc(r.enface_score)}}</div></div><div class="review"><div class="row"><button class="good" onclick="setLabel('oct_bscan')">1 B-scan</button><button class="good" onclick="setLabel('octa_enface')">2 OCTA en face</button><button class="good" onclick="setLabel('oct_enface_or_slo_like')">3 en face/SLO-like</button><button class="drop" onclick="dropRow()">4 unknown/exclude</button><button onclick="setLabel('${{esc(final)}}', false)">只保存</button></div><div class="row"><label>最终标签:${{labelSelect(final)}}</label></div><textarea placeholder="备注" oninput="updateNote(this.value)">${{esc(e.note || '')}}</textarea></div><div class="hint">快捷键:1/2/3/4 标注并下一张,←/→ 上一张/下一张,C 导出 CSV,J 导出 JSON。备注框内不会触发快捷键。</div></div></section>`;
}}
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"""<!doctype html>
<html><head><meta charset="utf-8"><title>{html.escape(title)}</title><style>{css}</style></head>
<body><header><h1>{html.escape(title)}</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">只审核自动非 B-scan、低置信度样本,以及抽样 B-scan。源图和 manifest 不会被修改。</div></header><main id="root"></main><script type="application/json" id="rows-data">{rows_json}</script><script>{js}</script></body></html>"""
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()