| """plot_robustness.py — visualize robustness sweep results. |
| |
| Reads robustnessv3/runs.json and produces: |
| - robustness_overall.png : 4 metrics x 7 perturbations, line plot per metric |
| - robustness_per_fake.png: AUROC per (fake-model x perturbation), 1 row per fake |
| - robustness_table.csv : flat CSV (perturbation, level, param, metrics) |
| |
| Run: |
| /opt/conda/envs/LipFD/bin/python plot_robustness.py \ |
| --runs robustnessv3/runs.json --out_dir robustnessv3 |
| """ |
| import argparse |
| import csv as _csv |
| import json |
| import os |
|
|
| import matplotlib.pyplot as plt |
| import numpy as np |
|
|
|
|
| |
| PERTURBATIONS = ["color_saturation", "color_contrast", "block_wise", |
| "gaussian_noise", "gaussian_blur", "pixelate", "jpeg_quality"] |
|
|
| |
| COLORS = { |
| "color_saturation": "#1f77b4", |
| "color_contrast": "#ff7f0e", |
| "block_wise": "#2ca02c", |
| "gaussian_noise": "#d62728", |
| "gaussian_blur": "#9467bd", |
| "pixelate": "#8c564b", |
| "jpeg_quality": "#e377c2", |
| } |
| MARKERS = { |
| "color_saturation": "o", |
| "color_contrast": "s", |
| "block_wise": "^", |
| "gaussian_noise": "D", |
| "gaussian_blur": "v", |
| "pixelate": "P", |
| "jpeg_quality": "X", |
| } |
|
|
|
|
| def load_runs(path): |
| with open(path) as f: |
| return json.load(f)["runs"] |
|
|
|
|
| def organize(runs): |
| """{perturbation: {level: run_dict}} — level 1 baseline copied to every perturbation.""" |
| out = {p: {} for p in PERTURBATIONS} |
| baseline = None |
| for r in runs: |
| if r["level"] == 1: |
| baseline = r |
| break |
| for r in runs: |
| out[r["perturbation"]][r["level"]] = r |
| if baseline is not None: |
| for p in PERTURBATIONS: |
| out[p][1] = baseline |
| return out, baseline |
|
|
|
|
| def write_csv(runs, csv_path): |
| rows = [] |
| for r in runs: |
| o = r["overall_clip"] |
| rows.append({ |
| "perturbation": r["perturbation"], |
| "level": r["level"], |
| "param": r["param"], |
| "n_clips": r["n_clips"], |
| "AUROC": o["AUROC"], |
| "AP": o["AP"], |
| "Accuracy": o["Accuracy"], |
| "Acc@EER": o["Acc@EER"], |
| "TPR@FPR=1%": o["TPR@FPR=1%"], |
| "TPR@FPR=0.1%": o["TPR@FPR=0.1%"], |
| }) |
| rows.sort(key=lambda x: (x["perturbation"], x["level"])) |
| with open(csv_path, "w", newline="") as f: |
| w = _csv.DictWriter(f, fieldnames=list(rows[0].keys())) |
| w.writeheader() |
| w.writerows(rows) |
| print(f" wrote {csv_path} ({len(rows)} rows)") |
|
|
|
|
| def plot_overall(by_pert, out_path, baseline): |
| """4 panels: AUROC / Accuracy / Acc@EER / TPR@FPR=1%, level on X axis.""" |
| metrics = [ |
| ("AUROC", "AUROC"), |
| ("Accuracy", "Accuracy"), |
| ("Acc@EER", "Acc@EER"), |
| ("TPR@FPR=1%", "TPR@FPR=1%"), |
| ] |
| fig, axes = plt.subplots(2, 2, figsize=(13, 9)) |
| axes = axes.flatten() |
| levels = [1, 2, 3, 4, 5] |
|
|
| for ax, (key, title) in zip(axes, metrics): |
| for p in PERTURBATIONS: |
| ys = [] |
| for L in levels: |
| r = by_pert[p].get(L) |
| if r is None: |
| ys.append(np.nan) |
| else: |
| ys.append(r["overall_clip"][key]) |
| ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p], |
| label=p, linewidth=1.8, markersize=7) |
| if baseline is not None: |
| bl = baseline["overall_clip"][key] |
| ax.axhline(bl, color="grey", linestyle="--", alpha=0.5, linewidth=1, |
| label=f"clean baseline = {bl:.4f}") |
| ax.set_title(title, fontsize=12) |
| ax.set_xlabel("perturbation level (1=clean, 5=heaviest)") |
| ax.set_ylabel(title) |
| ax.set_xticks(levels) |
| ax.grid(alpha=0.3) |
|
|
| |
| handles, labels = axes[0].get_legend_handles_labels() |
| fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9, |
| frameon=False, bbox_to_anchor=(0.5, -0.02)) |
| fig.suptitle("LipFD robustness — overall (clip-level), epoch_44 ckpt", fontsize=14) |
| plt.tight_layout(rect=[0, 0.04, 1, 0.97]) |
| plt.savefig(out_path, dpi=140, bbox_inches="tight") |
| plt.close() |
| print(f" wrote {out_path}") |
|
|
|
|
| def plot_per_fake(by_pert, out_path, baseline): |
| """1 row per fake model (EDTalk / Float / SadTalk), |
| each row = AUROC vs level for every perturbation.""" |
| fakes = sorted(set(baseline["per_fake_vs_real"].keys())) |
| fig, axes = plt.subplots(1, len(fakes), figsize=(5 * len(fakes), 4.5), |
| sharey=True) |
| if len(fakes) == 1: |
| axes = [axes] |
| levels = [1, 2, 3, 4, 5] |
|
|
| for ax, fm in zip(axes, fakes): |
| for p in PERTURBATIONS: |
| ys = [] |
| for L in levels: |
| r = by_pert[p].get(L) |
| ys.append(r["per_fake_vs_real"][fm]["AUROC"] if r else np.nan) |
| ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p], |
| label=p, linewidth=1.6, markersize=6) |
| if baseline is not None: |
| bl = baseline["per_fake_vs_real"][fm]["AUROC"] |
| ax.axhline(bl, color="grey", linestyle="--", alpha=0.5, linewidth=1) |
| ax.set_title(f"{fm} + Real (AUROC)") |
| ax.set_xlabel("level") |
| ax.set_xticks(levels) |
| ax.grid(alpha=0.3) |
| axes[0].set_ylabel("AUROC") |
| handles, labels = axes[0].get_legend_handles_labels() |
| fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9, |
| frameon=False, bbox_to_anchor=(0.5, -0.04)) |
| fig.suptitle("LipFD robustness — per-fake AUROC, epoch_44 ckpt", fontsize=14) |
| plt.tight_layout(rect=[0, 0.06, 1, 0.95]) |
| plt.savefig(out_path, dpi=140, bbox_inches="tight") |
| plt.close() |
| print(f" wrote {out_path}") |
|
|
|
|
| def plot_fairness(by_pert, out_path): |
| """3 panels (gender/race4/age_group), each shows F_MEO trend per perturbation.""" |
| dims = ["gender", "race4", "age_group"] |
| fig, axes = plt.subplots(1, 3, figsize=(15, 4.5)) |
| levels = [1, 2, 3, 4, 5] |
| for ax, d in zip(axes, dims): |
| for p in PERTURBATIONS: |
| ys = [] |
| for L in levels: |
| r = by_pert[p].get(L) |
| fb = r["fairness_overall"].get(d) if r else None |
| ys.append(fb["F_MEO"] if fb else np.nan) |
| ax.plot(levels, ys, marker=MARKERS[p], color=COLORS[p], |
| label=p, linewidth=1.6, markersize=6) |
| ax.set_title(f"F_MEO ({d}) — lower is fairer") |
| ax.set_xlabel("level") |
| ax.set_xticks(levels) |
| ax.grid(alpha=0.3) |
| axes[0].set_ylabel("F_MEO (%)") |
| handles, labels = axes[0].get_legend_handles_labels() |
| fig.legend(handles, labels, loc="lower center", ncol=4, fontsize=9, |
| frameon=False, bbox_to_anchor=(0.5, -0.04)) |
| fig.suptitle("LipFD robustness — fairness F_MEO across perturbations", fontsize=14) |
| plt.tight_layout(rect=[0, 0.06, 1, 0.95]) |
| plt.savefig(out_path, dpi=140, bbox_inches="tight") |
| plt.close() |
| print(f" wrote {out_path}") |
|
|
|
|
| def parse_args(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--runs", required=True) |
| p.add_argument("--out_dir", required=True) |
| return p.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| runs = load_runs(args.runs) |
| by_pert, baseline = organize(runs) |
| os.makedirs(args.out_dir, exist_ok=True) |
| write_csv(runs, os.path.join(args.out_dir, "robustness_table.csv")) |
| plot_overall(by_pert, os.path.join(args.out_dir, "robustness_overall.png"), baseline) |
| plot_per_fake(by_pert, os.path.join(args.out_dir, "robustness_per_fake.png"), baseline) |
| plot_fairness(by_pert, os.path.join(args.out_dir, "robustness_fairness.png")) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|