VeriSpoof-Bench / scripts /vsbench_metrics.py
AustinXiao's picture
Dataset card and files preview (private)
f053b90 verified
Raw History Blame Contribute Delete
20.2 kB
"""VeriSpoof-Bench metrics (standalone: numpy only). Same definitions as the VeriSpoof research code
(spoofllm/evaluate.py, spoofllm/grounded_eval.py, spoofllm/reasoning_eval.py, scripts/eval_faith_heldout.py).
closed / binary tasks EER (%) on a score (authenticity: higher = spoof; pair tasks: higher = same) and accuracy of
the arg-max option; per-group accuracies; macro-F1 for generator ID
ad_reasoning parser of the reasoning lines; decision accuracy, localization kind accuracy, span IoU on
partial spoofs, observation accuracy (bandwidth, low band, SNR within 10 dB, level within 5 dB,
clipping, digital silence), channel classes, consistency; optional token-level F1 / EER
(0.16 s grid) and localization-score EER; faithfulness rates from intervention decisions
sv_reasoning parser; verdict accuracy, verdict EER on a decision score, attribute-comparison accuracy,
accuracy per stratum (SAME, REVERSAL, DIFF_ATTR) and per profile support
"""
import re
import numpy as np
# ---------------------------------------------------------------- EER
def eer(scores, labels):
"""Equal error rate (%). scores: higher = more positive; labels: 1 positive, 0 negative."""
scores, labels = np.asarray(scores, float), np.asarray(labels, int)
order = np.argsort(-scores, kind="mergesort")
labels = labels[order]
p, n = labels.sum(), len(labels) - labels.sum()
tp, fp = np.cumsum(labels), np.cumsum(1 - labels)
fnr = np.concatenate([[1.0], 1 - tp / p])
fpr = np.concatenate([[0.0], fp / n])
i = np.argmin(np.abs(fnr - fpr))
return float(100 * (fnr[i] + fpr[i]) / 2)
def _r(m):
return {k: (round(v, 4) if isinstance(v, float) else v) for k, v in m.items()}
def macro_f1(y, p):
f = []
for c in np.unique(y):
tp = np.sum((p == c) & (y == c))
prec, rec = tp / max(1, np.sum(p == c)), tp / max(1, np.sum(y == c))
f.append(0.0 if tp == 0 else 2 * prec * rec / (prec + rec))
return float(np.mean(f))
PAIR_TASKS = {"same_generator", "same_acoustic_model", "same_vocoder"}
HARD = {"SG-DS": 1, "DG-SS": 0}
# ---------------------------------------------------------------- closed / binary tasks
def direct_metrics(items, S):
"""items: list of item dicts (task, options, label_index, meta dict); S: (N, K) candidate scores aligned with
`options` (-inf where an item has fewer options). For authenticity / pair tasks a (N,) score may be given
instead (higher = spoof / same); accuracy then uses the threshold 0."""
task = items[0]["task"]
y = np.array([it["label_index"] for it in items])
S = np.asarray(S, float)
if S.ndim == 1: # one score per item -> two pseudo-candidates
if task == "authenticity":
sp = items[0]["options"].index("spoof")
S2 = np.zeros((len(S), 2))
S2[:, sp] = S
S = S2
else:
S = np.stack([S, np.zeros_like(S)], 1)
pred = S.argmax(1)
m = {"n": len(items), "acc": float(np.mean(pred == y))}
meta = [it["meta"] for it in items]
if task == "authenticity":
sp = items[0]["options"].index("spoof")
m["eer"] = eer(S[:, sp] - S[:, 1 - sp], y == sp)
elif task in PAIR_TASKS:
s, pos = S[:, 0] - S[:, 1], y == 0
m["eer"] = eer(s, pos)
group = [x.get("quadrant") or x.get("combo") or x.get("stratum") for x in meta]
for g in sorted({g for g in group if g}):
k = np.array([x == g for x in group])
m[f"acc_{g}"] = float(np.mean(pred[k] == y[k]))
hard = np.array([HARD.get(x.get("quadrant"), -1) >= 0 for x in meta])
if hard.any() and 0 < pos[hard].sum() < hard.sum():
m["eer_hard"] = eer(s[hard], pos[hard])
for lr in ("SL", "DL"):
k = np.array([x.get("lang_rel") == lr for x in meta])
if k.any() and (~k).any() and 0 < pos[k].sum() < k.sum():
m[f"eer_{lr}"] = eer(s[k], pos[k])
elif task == "recording_condition":
for a in ("noise", "reverb", "codec"):
sel = np.array([x.get("attr") == a for x in meta])
if sel.any():
m[f"acc_{a}"] = float(np.mean(pred[sel] == y[sel]))
elif task == "generator_id":
m["macro_f1"] = macro_f1(y, pred)
m["chance"] = float(np.mean([1 / len(it["options"]) for it in items]))
k = np.array([bool(x.get("speaker_known")) for x in meta])
if k.any() and (~k).any():
m["acc_speaker_known"], m["acc_speaker_unknown"] = float(np.mean((pred == y)[k])), float(np.mean((pred == y)[~k]))
return _r(m)
# ---------------------------------------------------------------- grounded detection reasoning (ad_reasoning)
NOISE_TEXT = {"clean": "no audible noise", "mild": "mild noise", "moderate": "moderate noise",
"severe": "severe noise", "extreme": "extreme noise"}
REVERB_TEXT = {"minimal": "no noticeable reverberation", "slight": "slight reverberation",
"moderate": "moderate reverberation", "heavy": "heavy reverberation",
"extreme": "extreme reverberation"}
CODEC_TEXT = {"none": "no codec compression", "mp3": "MP3 compression", "aac": "AAC compression",
"opus": "Opus compression", "narrowband": "narrowband telephone coding",
"neural": "neural-codec compression", "wideband": "wideband telephone coding",
"cascade": "MP3 and neural-codec compression in cascade"}
PROC_TEXT = {"trimmed": "its edge silence has been trimmed", "digital silence added": "digital silence has been added "
"at the edges", "low-level noise added": "low-level noise has been added at the edges",
"clipped": "it has been amplified and clipped", "high-pass": "it has been high-pass filtered",
"band-pass": "it has been band-pass filtered"}
AD_FIELDS = ("OBSERVATIONS", "CHANNEL_STATUS", "LOCALIZATION", "SOURCE_PROFILE", "DECISION")
def parse_ad(text):
"""Grounded detection reasoning text -> checkable fields."""
f = dict.fromkeys(AD_FIELDS, "")
for line in (text or "").split("\n"):
for k in AD_FIELDS:
if line.startswith(k + ":"):
f[k] = line[len(k) + 1:].strip()
o, c, lo, d = f["OBSERVATIONS"], f["CHANNEL_STATUS"], f["LOCALIZATION"], f["DECISION"]
r = {}
r["bw"] = "narrow" if o.startswith("Narrowband") else "reduced" if o.startswith("Reduced") else \
"full" if o.startswith("Full") else None
r["low"] = "almost no energy below 300 Hz" in o if o else None
m = re.search(r"SNR about (\d+) dB", o)
r["snr"] = 45 if "very clean" in o else int(m.group(1)) if m else None
m = re.search(r"level about (-?\d+) dBFS", o)
r["level"] = int(m.group(1)) if m else None
r["clip"] = True if "audible clipping" in o else False if "no clipping" in o else None
m = re.search(r"digital silence at the (start and end|start|end)", o)
r["dsil"] = m.group(1) if m else ("none" if o else None)
for k, table in (("noise", NOISE_TEXT), ("reverb", REVERB_TEXT), ("codec", CODEC_TEXT)):
r[k] = next((cls for cls, txt in sorted(table.items(), key=lambda kv: -len(kv[1])) if txt in c), None)
r["proc"] = sorted(cls for cls, txt in PROC_TEXT.items() if txt in c)
r["loc"] = "none" if "No synthesized segment" in lo else "whole" if "whole recording is synthesized" in lo else \
"partial" if "Synthesized speech at" in lo else None
r["spans"] = [[float(a), float(b)] for a, b in re.findall(r"(\d+\.\d+)-(\d+\.\d+) s", lo)]
r["decision"] = "bonafide" if d.startswith("The recording is bona fide") else \
"spoof" if d.startswith("The recording is a spoof") else None
return r
def time_iou(a, b, step=0.01):
if not a and not b:
return 1.0
hi = max([y for _, y in a + b] + [0.0]) + step
t = np.arange(0, hi, step)
ma = np.zeros_like(t, bool)
mb = np.zeros_like(t, bool)
for x, y in a:
ma |= (t >= x) & (t < y)
for x, y in b:
mb |= (t >= x) & (t < y)
u = (ma | mb).sum()
return float((ma & mb).sum() / u) if u else 1.0
def ad_metrics(items, texts, loc_scores=None, flip_scores=None, token_scores=None):
"""items: dicts with `reference` (gold text), `ref_label` (bonafide / spoof), `ref_kind` (bonafide / spoof /
partial), `ref_spans` (window-time spans of the heard synthesized speech) and `has_proc`; texts: the model's
reasoning. Optional per item: loc_scores = log p(" No synthesized segment is found.") after the model's own
"LOCALIZATION:" prefix (-> eer_loc); flip_scores = (logp bona fide, logp spoof) decision candidates after the
opposite localization (-> flip_rate); token_scores = per-token synthesized scores on the 0.16 s grid, compared with
`ref_token_labels` (> 0 = synthesized; use logits or probability - 0.5)."""
P_ = [parse_ad(t) for t in texts]
G = [parse_ad(it["reference"]) for it in items]
y = np.array([it["ref_label"] == "spoof" for it in items])
m = {"n": len(items), "n_bona": int((~y).sum()), "parse_ok": float(np.mean([p["decision"] is not None for p in P_]))}
pred = np.array([p["decision"] == "spoof" for p in P_])
m["decision_acc"] = float(np.mean(pred == y))
if loc_scores is not None and 0 < y.sum() < len(y):
m["eer_loc"] = eer(-np.asarray(loc_scores, float), y)
m["loc_kind_acc"] = float(np.mean([p["loc"] == it["ref_kind"].replace("bonafide", "none").replace("spoof", "whole")
for p, it in zip(P_, items)]))
part = [k for k, it in enumerate(items) if it["ref_kind"] == "partial"]
if part:
m["loc_partial_any"] = float(np.mean([bool(P_[k]["spans"]) or P_[k]["loc"] == "whole" for k in part]))
m["loc_partial_iou"] = float(np.mean([time_iou([[0.0, 8.0]] if P_[k]["loc"] == "whole" else P_[k]["spans"],
[list(s) for s in items[k]["ref_spans"]]) for k in part]))
for k in ("bw", "low", "clip", "dsil"):
ok = [p[k] == g[k] for p, g in zip(P_, G) if g[k] is not None]
m[f"obs_{k}"] = float(np.mean(ok)) if ok else None
for k, tol in (("snr", 10), ("level", 5)):
ok = [p[k] is not None and abs(p[k] - g[k]) <= tol for p, g in zip(P_, G) if g[k] is not None]
m[f"obs_{k}_within_{tol}"] = float(np.mean(ok)) if ok else None
for k in ("noise", "reverb", "codec"):
ok = [p[k] == g[k] for p, g in zip(P_, G) if g[k] is not None]
if ok:
m[f"ch_{k}"] = float(np.mean(ok))
pk = [p["proc"] == g["proc"] for p, g, it in zip(P_, G, items) if it.get("has_proc")]
if pk:
m["ch_proc_exact"] = float(np.mean(pk))
m["consistency"] = float(np.mean([(p["loc"] == "none") == (p["decision"] == "bonafide") for p in P_
if p["loc"] and p["decision"]]))
if flip_scores is not None:
f = np.asarray(flip_scores, float)
said_none = np.array(["No synthesized segment" in t for t in texts])
m["flip_rate"] = float(np.where(said_none, f[:, 1] > f[:, 0], f[:, 0] > f[:, 1]).mean())
if token_scores is not None:
lab = np.concatenate([np.asarray(it["ref_token_labels"]) for it in items])
s = np.concatenate([np.asarray(z, float) for z in token_scores])
k = lab >= 0
lab, s = lab[k], s[k]
if 0 < lab.sum() < len(lab):
p = s > 0
tp, fp, fn = (p & (lab == 1)).sum(), (p & (lab == 0)).sum(), (~p & (lab == 1)).sum()
m["tok_f1"] = float(2 * tp / max(1, 2 * tp + fp + fn))
m["tok_eer"] = eer(s, lab)
return _r(m)
# ---------------------------------------------------------------- faithfulness interventions
DECISION_PREFIX = "DECISION: The recording is"
DECISION = {"bonafide": " bona fide: it is genuine human speech.",
"spoof": " a spoof: it is synthetic or converted speech.",
"partial": " a spoof: synthetic segments are embedded in genuine speech."}
FLIP = {True: "LOCALIZATION: The whole recording is synthesized.\nSOURCE_PROFILE: The generation method cannot be "
"determined.\n",
False: "LOCALIZATION: No synthesized segment is found.\n"}
PARA = {True: "LOCALIZATION: Every part of this recording was produced by a speech synthesizer.\n"
"SOURCE_PROFILE: The generation method cannot be determined.\n",
False: "LOCALIZATION: All of the speech is genuine; no part of it was produced by a synthesizer.\n"}
SPAN = ("LOCALIZATION: Synthesized speech at 1.60-2.40 s; the rest is genuine speech.\n"
"SOURCE_PROFILE: The generation method cannot be determined.\n")
CHANNEL = "CHANNEL_STATUS: The recording has heavy background noise, strong reverberation and MP3 compression.\n"
OBSERVE = "OBSERVATIONS: Narrowband (telephone) bandwidth; SNR about 5 dB; speech level about -35 dBFS; audible clipping.\n"
FAITH_FORMS = {
"flip": "follow: LOCALIZATION replaced by the opposite (the edit form used in VeriSpoof training)",
"paraphrase": "follow: opposite LOCALIZATION in a paraphrased (held-out) wording",
"span": "follow: a 'No synthesized segment' LOCALIZATION replaced by one partial span (held-out)",
"channel": "keep: CHANNEL_STATUS replaced by heavy noise, reverberation and MP3 compression (held-out)",
"observe": "keep: OBSERVATIONS replaced by contradicting measurements (held-out)",
}
def intervene(text, form):
"""Model's own reasoning text -> (edited prefix ending with "DECISION: The recording is", expected decision
"spoof" / "bonafide") or None when the form does not apply. The model is then asked to continue the prefix; its
decision (bona fide vs spoof, partial spoof counting as spoof) is compared with the expected one."""
if form == "flip": # spoofllm/grounded_eval.py _Score(mode="flip")
head = text[:text.index("LOCALIZATION:")] if "LOCALIZATION:" in text else text.rstrip() + "\n"
none = "No synthesized segment" in text
return head + FLIP[none] + DECISION_PREFIX, ("spoof" if none else "bonafide")
L = [l for l in text.split("\n") if l.strip()]
loc = next((l for l in L if l.startswith("LOCALIZATION:")), None)
if loc is None:
return None
none = "No synthesized segment" in loc
k = L.index(loc)
head, rest = L[:k], [l for l in L[k + 1:] if not l.startswith("DECISION")]
if form == "paraphrase":
return "\n".join(head) + "\n" + PARA[none] + DECISION_PREFIX, ("spoof" if none else "bonafide")
if form == "span":
return ("\n".join(head) + "\n" + SPAN + DECISION_PREFIX, "spoof") if none else None
if form == "channel":
head = [l for l in head if not l.startswith("CHANNEL_STATUS")]
ins = 1 if head and head[0].startswith("OBSERVATIONS") else 0
head = head[:ins] + [CHANNEL.strip()] + head[ins:]
elif form == "observe":
head = [OBSERVE.strip()] + [l for l in head if not l.startswith("OBSERVATIONS")]
else:
raise ValueError(form)
return "\n".join(head + [loc] + rest) + "\n" + DECISION_PREFIX, ("bonafide" if none else "spoof")
def faith_rate(expected, decided):
"""Share of intervened items whose decision equals the expected one (follow forms: the edited localization;
keep forms: the model's own localization)."""
e, d = np.asarray(expected), np.asarray(decided)
return float(np.mean(e == d)) if len(e) else None
# ---------------------------------------------------------------- source-verification reasoning (sv_reasoning)
SV_ATTRS = ("method", "acoustic", "waveform")
ATTR_NAME = {"method": "Generation method", "acoustic": "Acoustic modelling", "waveform": "Waveform generation"}
SUMMARY = {"supportive": "Across the source profile, all attributes are similar.",
"mixed": "Across the source profile, the attributes are mixed.",
"conflicting": "Across the source profile, the attributes conflict."}
VERDICT = {True: "Taken together, the recordings come from the same generation system.",
False: "Taken together, the recordings come from different generation systems."}
def parse_channel(text):
line = next((l for l in (text or "").split("\n") if l.startswith("CHANNEL_STATUS:")), None)
if line is None:
return None
parts = line.split("; the second recording has ")
out = []
for part in parts[:2]:
c = {}
for k, table in (("noise", NOISE_TEXT), ("reverb", REVERB_TEXT), ("codec", CODEC_TEXT)):
hits = [v for v, t in table.items() if t in part]
c[k] = max(hits, key=lambda v: len(table[v])) if hits else None
out.append(c)
return out if len(out) == 2 else None
def parse_sv(text):
text = text or ""
out = {k: (True if f"{ATTR_NAME[k]} is similar" in text else False if f"{ATTR_NAME[k]} differs" in text
else None) for k in SV_ATTRS}
out["support"] = next((lv for lv, t in SUMMARY.items() if t in text), None)
out["decision"] = True if VERDICT[True] in text else False if VERDICT[False] in text else None
out["channel"] = parse_channel(text)
out["fingerprint"] = True if "FINGERPRINT: The latent source-fingerprint cues show strong similarity" in text else \
False if "FINGERPRINT: The latent source-fingerprint cues show clear differences" in text else None
out["complete"] = text.startswith(("PROFILE_COMPATIBILITY:", "CHANNEL_STATUS:", "FINGERPRINT:")) and \
"\nDECISION:" in text and all(out[k] is not None for k in (*SV_ATTRS, "support", "decision"))
return out
def sv_metrics(items, texts, decision_scores=None, decided=None):
"""items: dicts with `reference` (gold text), `labels` dict (same_generator), meta (stratum, support);
texts: the model's reasoning; decision_scores: per item, higher = same system (VeriSpoof: log p(same verdict) -
log p(different verdict) after its own analysis) -> verdict EER. Without scores the EER is computed on the parsed
verdict (1 / 0; unparsed = 0.5), which is coarser. `decided` overrides the parsed verdict (True / False / None)."""
P = [parse_sv(t) for t in texts]
if decided is not None:
for p, d in zip(P, decided):
p["decision"] = d
G = [parse_sv(it["reference"]) for it in items]
y = np.array([it["labels"]["same_generator"] for it in items])
def acc(idx):
idx = list(idx)
return float(np.mean([P[i]["decision"] == y[i] for i in idx])) if idx else None
if decision_scores is None:
decision_scores = [0.5 if p["decision"] is None else float(p["decision"]) for p in P]
m = {"n": len(items), "parse_rate": float(np.mean([p["complete"] for p in P])),
"verdict_acc": acc(range(len(items))), "eer_decision": eer(decision_scores, y)}
for k in (*SV_ATTRS, "support"):
m[f"{k}_acc"] = float(np.mean([p[k] == g[k] for p, g in zip(P, G)]))
m["gold_complete"] = float(np.mean([g["complete"] for g in G]))
for st in ("SAME", "REVERSAL", "DIFF_ATTR"):
m[f"acc_{st}"] = acc(i for i, it in enumerate(items) if it["meta"]["stratum"] == st)
for lv in ("supportive", "mixed", "conflicting"):
idx = [i for i, it in enumerate(items) if it["meta"]["support"] == lv]
if idx:
m[f"acc_{lv}"] = acc(idx)
rev = [i for i, it in enumerate(items) if it["meta"]["stratum"] == "REVERSAL"]
if rev:
m["reversal_said_supportive"] = float(np.mean([P[i]["support"] == "supportive" for i in rev]))
m["unparsed_decision"] = int(sum(p["decision"] is None for p in P))
fp = [i for i, p in enumerate(P) if p["fingerprint"] is not None]
if fp:
m["fingerprint_consistency"] = float(np.mean([P[i]["decision"] == P[i]["fingerprint"] for i in fp]))
ch = [i for i, g in enumerate(G) if g["channel"]]
if ch:
for k in ("noise", "reverb", "codec"):
m[f"channel_{k}_acc"] = float(np.mean([P[i]["channel"] is not None and P[i]["channel"][j][k] == G[i]["channel"][j][k]
for i in ch for j in (0, 1)]))
return _r(m)