#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Build a single self-contained HTML report of the benchmark. 4 modules (Myopia / AMD / Glaucoma / DR). Each dataset card shows: - 采集背景 (acquisition background: FOV / device / source / resolution) - 类别分布 (class distribution by split: table + grouped bar chart) - 模型性能 (metrics table + grouped bar chart, 3 models) - 可展开的混淆矩阵 / ROC 图 All images are embedded as base64 -> works offline, one file. """ import os, json, base64, io, csv from collections import defaultdict import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt PROJ = "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/GPT-Image" RESULTS = f"{PROJ}/results" DSROOT = f"{PROJ}/Dataset" OUT = f"{RESULTS}/report.html" MODELS = ["retfound", "resnet", "vit"] MLABEL = {"retfound": "RetFound (ViT-L, CFP)", "resnet": "ResNet-50", "vit": "ViT-B/16"} MCOLOR = {"retfound": "#4C72B0", "resnet": "#55A868", "vit": "#C44E52"} SPLIT_COLOR = {"train": "#4C72B0", "val": "#DD8452", "test": "#55A868"} CATS = [ ("近视 · Myopic Maculopathy", "#2563eb", [("mmac", "MMAC 2023", "5-class grade 0–4")]), ("AMD · Age-related Macular Degeneration", "#16a34a", [("adam", "ADAM", "binary AMD / Non-AMD")]), ("青光眼 · Glaucoma", "#d97706", [("airogs", "AIROGS (EyePACS-AIROGS-light)", "binary RG / NRG"), ("papila", "PAPILA", "binary glaucoma / healthy")]), ("DR · Diabetic Retinopathy", "#dc2626", [("idrid", "IDRiD", "5-class grade 0–4"), ("aptos", "APTOS-2019", "5-class grade 0–4"), ("deepdrid", "DeepDRiD", "5-class grade 0–4")]), ] SPLITS = {"mmac": "973/139/279", "adam": "280/40/80", "airogs": "5000/540/1000", "papila": "294/42/84", "idrid": "318/45/92", "aptos": "2930/366/366", "deepdrid": "1200/400/400"} DSPATH = {"mmac": "Myopia/Classification_of_Myopic_Maculopathy", "adam": "AMD/adamdataset", "airogs": "Glaucoma/eyepacs-airogs-light", "papila": "Glaucoma/papila-retinal-fundus-images", "idrid": "DR/idrid-dataset", "aptos": "DR/aptos2019", "deepdrid": "DR/deepdrid"} # 采集背景(已核实来源;不确定处据实标注) BG = { "mmac": "彩色眼底照(非散瞳)|FOV:45°(设备标称,论文正文未印)|设备:Topcon TRC-NW400(单一设备)|来源:上海健康医学中心 + 上海市第六人民医院(中国,均为中国人群)|分辨率:未公开|标注:META-PM 5 级,双医师分级(κ=0.91),单设备单人群为其局限。", "adam": "彩色眼底照|FOV:未标注(仅说明取景中心为视盘 / 黄斑 / 两者中点)|设备:Zeiss Visucam 500(2124×2056,824 张)+ Canon CR-2(1444×1444,376 张)|来源:中山眼科中心(中国·广州)|Training400:89 AMD / 311 非 AMD(AMD 被刻意过采样,非真实患病率)。", "airogs": "彩色眼底照,源自 EyePACS 远程筛查平台(美国约 500 个点、60071 人、多种族)|设备:多相机混用(Optovue iCam100≈26%、Topcon NW200/400≈20%、Canon CR1/CR2/DGI、Centervue、Nidek、Crystalvue,约 21% 未知)|FOV / 分辨率:因多设备未统一|原为糖网筛查图后重标青光眼;全集 RG 仅约 3%(极不平衡),本「light」子集已平衡为 3270/3270。", "papila": "彩色眼底照,以视盘为中心|FOV:30°|设备:Topcon TRC-NW400(非散瞳)|分辨率:2576×1934 JPEG|来源:Reina Sofía 大学医院(西班牙·Murcia,2018–2020)|244 人双眼共 488 张(healthy/glaucoma/suspect,本项目已剔除 suspect → 420)|附临床数据与视盘/视杯分割。", "idrid": "彩色眼底照|FOV:50°|设备:Kowa VX-10α(散瞳,托吡卡胺 0.5%)|分辨率:4288×2848 JPG|来源:印度 Nanded(Maharashtra)眼科诊所,2009–2017|全集 516 张(本项目有标签 455 张)|DR 0–4(ICDR)+ 黄斑水肿风险分级。", "aptos": "彩色眼底照|设备 / FOV / 分辨率:均未公开(多诊所、多相机、跨时间采集,异质性大)|来源:Aravind 眼科医院(印度),乡村远程筛查|训练集 3662 张,DR 0–4(ICDR)|真实世界噪声明显(伪影 / 失焦 / 过曝欠曝 / 标签噪声)。", "deepdrid": "彩色眼底照(常规,非超广角)|设备:Topcon 非散瞳(具体型号未公开)|FOV≈45–60°、分辨率≈1956×1934(来自补充材料,中等可信)|来源:上海市第六人民医院(中国)糖尿病筛查队列|2000 张 / 500 人,每眼双视野(视盘中心 + 黄斑中心)|DR 0–4 + 图像质量标注。", } BIN_COLS = [("accuracy", "Accuracy"), ("auroc", "AUROC"), ("auprc", "AUPRC"), ("f1_macro", "F1"), ("sensitivity", "Sensitivity"), ("specificity", "Specificity"), ("cohen_kappa", "Kappa"), ("mcc", "MCC")] MUL_COLS = [("accuracy", "Accuracy"), ("balanced_accuracy", "Bal-Acc"), ("auroc_macro_ovr", "macro-AUROC"), ("quadratic_weighted_kappa", "QWK"), ("f1_macro", "F1-macro"), ("precision_macro", "Prec-macro"), ("recall_macro", "Rec-macro"), ("cohen_kappa", "Kappa")] BIN_BAR = [("accuracy", "Acc"), ("auroc", "AUROC"), ("auprc", "AUPRC"), ("f1_macro", "F1"), ("sensitivity", "Sens"), ("specificity", "Spec")] MUL_BAR = [("accuracy", "Acc"), ("auroc_macro_ovr", "AUROC"), ("quadratic_weighted_kappa", "QWK"), ("f1_macro", "F1"), ("balanced_accuracy", "Bal-Acc")] def load(dsk, model): try: return json.load(open(os.path.join(RESULTS, dsk, model, "metrics.json"))) except Exception: return None def read_dist(dsk): """Return ordered [(label,class_name)], counts[split][label], total.""" rows = list(csv.DictReader(open(os.path.join(DSROOT, DSPATH[dsk], "labels.csv")))) classes = sorted(set((r["label"], r.get("class_name", "")) for r in rows), key=lambda x: int(x[0])) cnt = defaultdict(lambda: defaultdict(int)) for r in rows: cnt[r["split"]][r["label"]] += 1 return classes, cnt, len(rows) def b64_img(path): try: return "data:image/png;base64," + base64.b64encode(open(path, "rb").read()).decode() except Exception: return "" def fig_b64(fig): buf = io.BytesIO() fig.savefig(buf, format="png", dpi=110, bbox_inches="tight") plt.close(fig) return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() def grouped_bar(labels, series, colors, ylabel, intlabels=False): """series: list of (name, [values]) aligned to labels.""" x = np.arange(len(labels)) w = 0.8 / max(1, len(series)) fig, ax = plt.subplots(figsize=(7.2, 3.6)) for i, (name, vals) in enumerate(series): bars = ax.bar(x + (i - (len(series) - 1) / 2) * w, vals, w, label=name, color=colors[name]) for b, v in zip(bars, vals): if v: ax.text(b.get_x() + b.get_width() / 2, v, (f"{int(v)}" if intlabels else f"{v:.2f}"), ha="center", va="bottom", fontsize=6.3) ax.set_xticks(x); ax.set_xticklabels(labels, fontsize=8.5) ax.set_ylabel(ylabel) ax.legend(fontsize=7.5, ncol=len(series), loc="lower center", bbox_to_anchor=(0.5, 1.0), frameon=False) ax.grid(axis="y", ls=":", alpha=0.4); ax.set_axisbelow(True) if not intlabels: ax.set_ylim(0, 1.08) for s in ("top", "right"): ax.spines[s].set_visible(False) return fig_b64(fig) def perf_bar(metrics, bar_keys): keys = [k for k, _ in bar_keys] series = [(MLABEL[m], [(metrics.get(m) or {}).get(k) if isinstance((metrics.get(m) or {}).get(k), (int, float)) else 0 for k in keys]) for m in MODELS] colors = {MLABEL[m]: MCOLOR[m] for m in MODELS} return grouped_bar([l for _, l in bar_keys], series, colors, "score", intlabels=False) def dist_bar(classes, cnt): labels = [f"{l}·{cn}" for l, cn in classes] series = [(sp, [cnt[sp].get(l, 0) for l, _ in classes]) for sp in ("train", "val", "test")] return grouped_bar(labels, series, SPLIT_COLOR, "images", intlabels=True) def perf_table(metrics, cols): keys = [k for k, _ in cols] best = {} for k in keys: vals = [(metrics[m].get(k) if metrics.get(m) and isinstance(metrics[m].get(k), (int, float)) else None) for m in MODELS] vals = [v for v in vals if v is not None] best[k] = max(vals) if vals else None h = ['
| Model | '] + [f"{lab} | " for _, lab in cols] + ["|
|---|---|---|
| {MLABEL[m]} | ') for k, _ in cols: v = mm.get(k) if isinstance(v, (int, float)): cls = "best" if (best[k] is not None and abs(v - best[k]) < 1e-9) else "" h.append(f'{v:.4f} | ') else: h.append("— | ") h.append("
| Split | '] + [f"{l}·{cn} | " for l, cn in classes] + ["合计 |
|---|---|---|
| {sp} | ') s = 0 for l, _ in classes: v = cnt[sp].get(l, 0); s += v; coltot[l] += v h.append(f"{v} | ") h.append(f"{s} |
| 合计 | ') for l, _ in classes: h.append(f"{coltot[l]} | ") h.append(f'{sum(coltot.values())} |
| Class | Support | '] for m in MODELS: h.append(f'{MLABEL[m]} | ') h.append("||
|---|---|---|---|---|
| Recall | F1 | AUROC | ') h.append("||
| {l}·{cn} | {sup if sup is not None else "—"} | ') for m in MODELS: mm = metrics.get(m) or {} pc = mm.get("per_class", {}).get(str(l), {}) au = (mm.get("auroc_per_class") or {}).get(str(l)) f1 = pc.get("f1-score") f1cls = "best" if (isinstance(f1, (int, float)) and bf is not None and abs(f1 - bf) < 1e-9) else "" h.append(f'{fmt(pc.get("recall"))} | {fmt(f1)} | {fmt(au)} | ') h.append("
| Model | '] for _, kn in metrics_keys: th.append(f'{kn} | ') th.append("
|---|---|
| {m} | ') for k, _ in metrics_keys: v = mm.get(k) if mm else None cls = "best" if (isinstance(v, (int, float)) and best_map[k] is not None and abs(v - best_map[k]) < 1e-9) else "" vs = f"{v:.4f}" if isinstance(v, (int, float)) else "—" th.append(f'{vs} | ') th.append("
7 个数据集 · 4 个疾病方向 · 三模型(RetFound ViT-L / ResNet-50 / ViT-B/16,均预训练后全参数微调)
每个数据集含:采集背景(FOV/设备/来源/分辨率)· 类别分布(按 split)· 模型性能(指标表 + 柱状图)· 混淆矩阵/ROC
评估协议:输入 224 · 官方划分优先(否则 7:1:2 分层)· val 选最优→测 test · 指标由统一脚本计算