| """Compare robustness curves across three models: |
| CTA (this project), X-AVDT, AVH-Align. |
| |
| For each perturbation type, draw one figure with three lines (one per model) |
| showing AUROC (and AP / Accuracy / Acc@EER) as a function of severity level. |
| |
| The three input CSVs use different schemas; this script normalizes them to |
| a common long-table: (model, perturbation, level, AUROC, AP, Accuracy, Acc@EER). |
| |
| Output: |
| <out_dir>/ |
| auroc_<perturbation>.{png,pdf} one per perturbation, single metric |
| ap_<perturbation>.{png,pdf} |
| acc_<perturbation>.{png,pdf} |
| acc_at_eer_<perturbation>.{png,pdf} |
| grid_auroc.{png,pdf} 7 perturbations on one A4-ish grid |
| merged_long_table.csv normalized long-table for downstream |
| |
| Usage: |
| python3 scripts/analysis/plot_robustness_compare.py \\ |
| --cta /apdcephfs_gy4/.../figs_with_jpeg/robustness_table.csv \\ |
| --xavdt /apdcephfs_gy4/.../X-AVDT/results/robustness/robustness_summary.csv \\ |
| --avhalign /apdcephfs_gy5/.../AVH-Align/results/robustness_v2/merged_long_table.csv \\ |
| --out_dir /apdcephfs_gy4/.../X-AVDT/results/robustness/compare |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import os |
| from collections import defaultdict |
| from pathlib import Path |
| from typing import Dict, List, Optional |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
|
|
| |
| PERTS_CANONICAL = [ |
| "gaussian_noise", |
| "block_wise", |
| "jpeg_quality", |
| |
| "pixelate", |
| "gaussian_blur", |
| "color_saturation", |
| "color_contrast", |
| ] |
|
|
| |
| PERT_ALIASES: Dict[str, str] = { |
| "jpeg_compression": "jpeg_quality", |
| } |
|
|
| PRETTY = { |
| "gaussian_noise": "Gaussian noise", |
| "block_wise": "Block occlusion", |
| "jpeg_quality": "JPEG compression", |
| "pixelate": "Pixelation", |
| "gaussian_blur": "Gaussian blur", |
| "color_saturation": "Color saturation", |
| "color_contrast": "Color contrast", |
| } |
|
|
| MODEL_COLORS = { |
| "CTA": "#C0392B", |
| "X-AVDT": "#2980B9", |
| "AVH-Align": "#16A085", |
| } |
| MODEL_MARKERS = { |
| "CTA": "o", |
| "X-AVDT": "s", |
| "AVH-Align": "^", |
| } |
|
|
|
|
| def _canon(p: str) -> str: |
| return PERT_ALIASES.get(p, p) |
|
|
|
|
| def _to_float(s: str) -> Optional[float]: |
| try: |
| v = float(s) |
| if v != v: |
| return None |
| return v |
| except (ValueError, TypeError): |
| return None |
|
|
|
|
| |
| |
| |
| def load_cta(path: str) -> List[dict]: |
| """CTA schema (long, narrow): |
| perturbation,level,param,AUROC,AP,Accuracy,Acc@EER,delta_AUROC_vs_L1 |
| Already long-format: one row per (perturbation, level). |
| """ |
| rows = [] |
| with open(path) as f: |
| reader = csv.DictReader(f) |
| for r in reader: |
| p = _canon(r["perturbation"].strip()) |
| L = int(r["level"]) |
| rows.append({ |
| "model": "CTA", |
| "perturbation": p, |
| "level": L, |
| "param": r.get("param", ""), |
| "AUROC": _to_float(r.get("AUROC")), |
| "AP": _to_float(r.get("AP")), |
| "Accuracy": _to_float(r.get("Accuracy")), |
| "Acc@EER": _to_float(r.get("Acc@EER")), |
| }) |
| print(f"[load] CTA: {len(rows)} rows from {path}") |
| return rows |
|
|
|
|
| def load_xavdt(path: str) -> List[dict]: |
| """X-AVDT schema: |
| perturbation,level,param,n_clips, |
| overall_AUROC, overall_AP, overall_Accuracy@0.50, overall_Acc@EER, |
| overall_TPR@FPR=1%, overall_TPR@FPR=0.1%, ... (per-fake too) |
| Special row: perturbation='baseline', level=1 (the no-op). |
| Each non-baseline perturbation only has level 2..5; we fan the baseline |
| out as L1 of every perturbation so curves start at the same anchor. |
| """ |
| rows = [] |
| baseline = None |
| perts_seen = set() |
| with open(path) as f: |
| reader = csv.DictReader(f) |
| for r in reader: |
| p_raw = r["perturbation"].strip() |
| L = int(r["level"]) |
| block = { |
| "AUROC": _to_float(r.get("overall_AUROC")), |
| "AP": _to_float(r.get("overall_AP")), |
| "Accuracy": _to_float(r.get("overall_Accuracy@0.50")), |
| "Acc@EER": _to_float(r.get("overall_Acc@EER")), |
| } |
| if p_raw == "baseline": |
| baseline = block |
| continue |
| p = _canon(p_raw) |
| perts_seen.add(p) |
| rows.append({ |
| "model": "X-AVDT", |
| "perturbation": p, |
| "level": L, |
| "param": r.get("param", ""), |
| **block, |
| }) |
|
|
| |
| if baseline is not None: |
| for p in perts_seen: |
| rows.append({ |
| "model": "X-AVDT", |
| "perturbation": p, |
| "level": 1, |
| "param": "baseline", |
| **baseline, |
| }) |
| print(f"[load] X-AVDT: {len(rows)} rows (incl. {len(perts_seen)} fanned baseline rows)") |
| return rows |
|
|
|
|
| def load_avhalign(path: str, subset: str = "non_diffusion") -> List[dict]: |
| """AVH-Align schema: |
| perturbation,level,param,subset,samples,accuracy,auc,average_precision,acc_at_eer |
| `subset` is one of {overall, non_diffusion, SadTalk, EDTalk, Float}; |
| we keep only the requested subset. |
| """ |
| rows = [] |
| n_skipped = 0 |
| with open(path) as f: |
| reader = csv.DictReader(f) |
| for r in reader: |
| if r["subset"].strip() != subset: |
| continue |
| p = _canon(r["perturbation"].strip()) |
| L = int(r["level"]) |
| rows.append({ |
| "model": "AVH-Align", |
| "perturbation": p, |
| "level": L, |
| "param": r.get("param", ""), |
| "AUROC": _to_float(r.get("auc")), |
| "AP": _to_float(r.get("average_precision")), |
| "Accuracy": _to_float(r.get("accuracy")), |
| "Acc@EER": _to_float(r.get("acc_at_eer")), |
| }) |
| print(f"[load] AVH-Align: {len(rows)} rows (subset={subset})") |
| return rows |
|
|
|
|
| |
| |
| |
| def _gather(rows: List[dict]): |
| """Group by perturbation -> model -> {level: row}.""" |
| out = defaultdict(lambda: defaultdict(dict)) |
| for r in rows: |
| out[r["perturbation"]][r["model"]][r["level"]] = r |
| return out |
|
|
|
|
| def _plot_metric_one_pert(ax, by_model, metric, title, ylabel, |
| ylim=None, show_legend=True): |
| """`by_model`: {model: {level: row}}.""" |
| for model in ("CTA", "X-AVDT", "AVH-Align"): |
| if model not in by_model: |
| continue |
| levels = sorted(by_model[model].keys()) |
| ys = [by_model[model][L].get(metric) for L in levels] |
| if all(y is None for y in ys): |
| continue |
| ax.plot( |
| levels, ys, |
| marker=MODEL_MARKERS[model], linewidth=2.0, markersize=7, |
| color=MODEL_COLORS[model], label=model, |
| ) |
| ax.set_xticks([1, 2, 3, 4, 5]) |
| ax.set_xlabel("Perturbation level (1 = clean, 5 = strongest)") |
| ax.set_ylabel(ylabel) |
| ax.set_title(title) |
| if ylim is not None: |
| ax.set_ylim(ylim) |
| ax.grid(True, alpha=0.3, linestyle=":") |
| ax.spines["top"].set_visible(False) |
| ax.spines["right"].set_visible(False) |
| if show_legend: |
| ax.legend(frameon=False, loc="best", fontsize=10) |
|
|
|
|
| def plot_per_perturbation(rows: List[dict], out_dir: Path): |
| by_pert = _gather(rows) |
|
|
| for metric_key, prefix, ylabel in [ |
| ("AUROC", "auroc", "AUROC"), |
| ("AP", "ap", "Average Precision"), |
| ("Accuracy","acc", "Accuracy @ 0.5"), |
| ("Acc@EER", "acc_at_eer", "Acc @ EER threshold"), |
| ]: |
| for p in PERTS_CANONICAL: |
| if p not in by_pert: |
| continue |
| fig, ax = plt.subplots(figsize=(6.5, 4.5)) |
| _plot_metric_one_pert( |
| ax, by_pert[p], metric_key, |
| f"{PRETTY[p]} — {ylabel}", |
| ylabel, |
| ) |
| fig.tight_layout() |
| png = out_dir / f"{prefix}_{p}.png" |
| pdf = out_dir / f"{prefix}_{p}.pdf" |
| fig.savefig(png, dpi=200, bbox_inches="tight") |
| fig.savefig(pdf, bbox_inches="tight") |
| plt.close(fig) |
| print(f"[plot] wrote {png}") |
|
|
|
|
| def plot_grid_auroc(rows: List[dict], out_path: Path): |
| """One A4-ish grid: 7 perturbations, AUROC only, 3 lines each.""" |
| by_pert = _gather(rows) |
| perts = [p for p in PERTS_CANONICAL if p in by_pert] |
| n = len(perts) |
| cols = 4 |
| rows_n = (n + cols - 1) // cols |
| fig, axes = plt.subplots(rows_n, cols, figsize=(cols * 4.0, rows_n * 3.6)) |
| axes = axes.flatten() if hasattr(axes, "flatten") else [axes] |
|
|
| for ax, p in zip(axes, perts): |
| _plot_metric_one_pert( |
| ax, by_pert[p], "AUROC", |
| PRETTY[p], "AUROC", |
| show_legend=False, |
| ) |
| |
| for ax in axes[len(perts):]: |
| ax.axis("off") |
|
|
| |
| handles, labels = axes[0].get_legend_handles_labels() |
| fig.legend(handles, labels, loc="upper center", ncol=3, |
| bbox_to_anchor=(0.5, 1.005), frameon=False, fontsize=11) |
| fig.tight_layout(rect=(0, 0, 1, 0.97)) |
| fig.savefig(out_path, dpi=200, bbox_inches="tight") |
| fig.savefig(str(out_path).replace(".png", ".pdf"), bbox_inches="tight") |
| plt.close(fig) |
| print(f"[plot] wrote {out_path}") |
|
|
|
|
| def save_long_table(rows: List[dict], out_csv: Path): |
| fields = ["model", "perturbation", "level", "param", |
| "AUROC", "AP", "Accuracy", "Acc@EER"] |
| with open(out_csv, "w", newline="") as f: |
| w = csv.DictWriter(f, fieldnames=fields) |
| w.writeheader() |
| for r in sorted(rows, key=lambda x: (x["model"], x["perturbation"], x["level"])): |
| w.writerow({k: r.get(k, "") for k in fields}) |
| print(f"[plot] wrote {out_csv}") |
|
|
|
|
| |
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--cta", required=True, help="CTA robustness_table.csv") |
| ap.add_argument("--xavdt", required=True, help="X-AVDT robustness_summary.csv") |
| ap.add_argument("--avhalign", required=True, help="AVH-Align merged_long_table.csv") |
| ap.add_argument("--avhalign_subset", default="non_diffusion", |
| choices=["overall", "non_diffusion", "SadTalk", "EDTalk", "Float"], |
| help="Which subset row to read from AVH-Align (default: " |
| "non_diffusion, matching CTA's three-family merged set)") |
| ap.add_argument("--out_dir", required=True) |
| args = ap.parse_args() |
|
|
| out_dir = Path(args.out_dir) |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| rows = [] |
| rows += load_cta(args.cta) |
| rows += load_xavdt(args.xavdt) |
| rows += load_avhalign(args.avhalign, subset=args.avhalign_subset) |
|
|
| |
| cov = defaultdict(set) |
| for r in rows: |
| cov[r["model"]].add((r["perturbation"], r["level"])) |
| print() |
| print("[plot] coverage:") |
| for m in ("CTA", "X-AVDT", "AVH-Align"): |
| print(f" {m}: {len(cov[m])} (perturbation, level) cells") |
| common_perts = sorted(set.intersection( |
| *[{p for p, _ in cov[m]} for m in cov] |
| )) if cov else [] |
| print(f"[plot] perturbations covered by all three: {common_perts}") |
| print() |
|
|
| save_long_table(rows, out_dir / "merged_long_table.csv") |
| plot_per_perturbation(rows, out_dir) |
| plot_grid_auroc(rows, out_dir / "grid_auroc.png") |
| print(f"[plot] DONE. outputs in: {out_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|