File size: 7,938 Bytes
b58079c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""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


# Same order as evaluate_robustness.py SEVERITY dict
PERTURBATIONS = ["color_saturation", "color_contrast", "block_wise",
                 "gaussian_noise", "gaussian_blur", "pixelate", "jpeg_quality"]

# Visual styling — distinct color per perturbation, consistent across plots
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)

    # one shared legend on top-right axis
    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()