Datasets:
File size: 7,438 Bytes
f053b90 | 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 | #!/usr/bin/env python3
"""Score predictions on VeriSpoof-Bench (numpy, pandas, pyarrow; no model code).
python scripts/score.py --pred <pred_dir> [--bench <local dataset dir | AustinXiao/VeriSpoof-Bench>]
[--subsets ...] [--out metrics.json]
<pred_dir> holds one file per subset, <subset>.parquet | .jsonl | .csv, with an `item_id` column and:
authenticity, same_*, generator_id, acoustic_model, recording_condition
scores list of candidate scores aligned with the item's `options` (e.g. log-likelihoods), or
score one number per item: authenticity -> higher = spoof; same_* -> higher = same
(closed questions need `scores`)
ad_reasoning (grounded detection reasoning)
output the model's reasoning text (OBSERVATIONS / CHANNEL_STATUS / LOCALIZATION / SOURCE_PROFILE /
DECISION lines; see the dataset card)
loc_score optional: log p(" No synthesized segment is found.") after the model's own "LOCALIZATION:"
flip_scores optional: [logp bona fide, logp spoof] decision candidates after the opposite localization
token_scores optional: per-token synthesized scores on the 0.16 s grid (> 0 = synthesized), as
`ref_token_labels`
plus, optionally, <subset>.faith.(parquet|jsonl|csv) with item_id, form, decision ("bonafide" / "spoof"), the
model's decision after each faithfulness intervention (scripts/faithfulness.py makes the prompts)
sv_reasoning (source-verification reasoning)
output the model's reasoning text
decision_score optional: higher = same generation system (verdict EER; without it the parsed verdict is used)
Writes {subset: metrics} as JSON and prints a summary line per subset.
"""
import argparse
import json
import os
import sys
import numpy as np
import pandas as pd
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vsbench_metrics as VM # noqa: E402
HERE = os.path.dirname(os.path.abspath(__file__))
DIRECT = {"authenticity", "same_generator", "same_acoustic_model", "same_vocoder", "generator_id", "acoustic_model",
"recording_condition"}
HEADLINE = {"authenticity": "eer", "same_generator": "eer", "same_acoustic_model": "eer", "same_vocoder": "eer",
"generator_id": "acc", "acoustic_model": "acc", "recording_condition": "acc",
"ad_reasoning": "decision_acc", "sv_reasoning": "eer_decision"}
def bench_dir(b):
if b and os.path.isdir(b):
return b
from huggingface_hub import snapshot_download
return snapshot_download(b or "AustinXiao/VeriSpoof-Bench", repo_type="dataset", allow_patterns=["data/*"])
def read_table(path_noext):
for ext, f in ((".parquet", pd.read_parquet), (".jsonl", lambda p: pd.read_json(p, lines=True)),
(".csv", pd.read_csv)):
if os.path.exists(path_noext + ext):
d = f(path_noext + ext)
for c in ("scores", "flip_scores", "token_scores"):
if c in d.columns and d[c].dtype == object and len(d) and isinstance(d[c].iloc[0], str):
d[c] = d[c].map(json.loads)
return d
return None
def load_items(bench, subset):
import pyarrow.parquet as pq
items = []
for r in pq.read_table(f"{bench}/data/{subset}.parquet").to_pylist():
items.append({"item_id": r["item_id"], "task": r["task"], "options": r["options"],
"label_index": r["label_index"], "label": r["label"],
"meta": json.loads(r["meta"]) if r["meta"] else {},
"labels": json.loads(r["labels"]) if r["labels"] else {},
"reference": r["reference"], "ref_label": r["label"], "ref_kind": r["ref_kind"],
"ref_spans": r["ref_spans"] or [], "ref_token_labels": r["ref_token_labels"],
"has_proc": r["audio"][0]["post_processing"] is not None})
return items
def align(items, pred, subset):
p = pred.set_index("item_id")
missing = [it["item_id"] for it in items if it["item_id"] not in p.index]
if missing:
raise SystemExit(f"{subset}: {len(missing)} items without a prediction, e.g. {missing[:3]}")
return p.loc[[it["item_id"] for it in items]]
def score_subset(items, pred, faith=None, subset=""):
task = items[0]["task"]
p = align(items, pred, subset)
if task in DIRECT:
if "scores" in p.columns and p["scores"].notna().all():
K = max(len(it["options"]) for it in items)
S = np.full((len(items), K), -np.inf)
for i, s in enumerate(p["scores"]):
S[i, :len(s)] = s
elif "score" in p.columns:
S = p["score"].to_numpy(float)
else:
raise SystemExit(f"{subset}: needs `scores` or `score`")
return VM.direct_metrics(items, S)
if task == "ad_reasoning":
opt = lambda c: list(p[c]) if c in p.columns and p[c].notna().all() else None # noqa: E731
m = VM.ad_metrics(items, list(p["output"].fillna("")), opt("loc_score"), opt("flip_scores"),
opt("token_scores"))
for form in ("paraphrase", "span", "channel", "observe"): # items each held-out intervention applies to
m[f"faith_{form}_n"] = sum(VM.intervene(t, form) is not None for t in p["output"].fillna(""))
if faith is not None:
texts = dict(zip(p.index, p["output"].fillna("")))
for form, g in faith.groupby("form"):
exp, dec = [], []
for iid, d in zip(g["item_id"], g["decision"]):
r = VM.intervene(texts[iid], form)
if r is not None:
exp.append(r[1])
dec.append(d)
m[f"faith_{form}"] = round(VM.faith_rate(exp, dec), 4) if exp else None
m[f"faith_{form}_n"] = len(exp)
return m
if task == "sv_reasoning":
ds = list(p["decision_score"]) if "decision_score" in p.columns and p["decision_score"].notna().all() else None
m = VM.sv_metrics(items, list(p["output"].fillna("")), ds)
if "branch_score" in p.columns and p["branch_score"].notna().all(): # VeriSpoof's decision at the connector
m["eer_branch"] = round(VM.eer(p["branch_score"].to_numpy(float),
[it["labels"]["same_generator"] for it in items]), 4)
return m
raise SystemExit(f"unknown task {task}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--pred", required=True)
ap.add_argument("--bench", default=os.path.join(HERE, ".."))
ap.add_argument("--subsets", nargs="*")
ap.add_argument("--out")
a = ap.parse_args()
bench = bench_dir(a.bench)
subsets = a.subsets or sorted(f[:-8] for f in os.listdir(f"{bench}/data") if f.endswith(".parquet"))
res = {}
for s in subsets:
pred = read_table(f"{a.pred}/{s}")
if pred is None:
continue
items = load_items(bench, s)
res[s] = score_subset(items, pred, read_table(f"{a.pred}/{s}.faith"), s)
h = HEADLINE[items[0]["task"]]
print(f"{s:<55} {h} {res[s].get(h)}", flush=True)
if a.out:
json.dump(res, open(a.out, "w"), indent=1)
if not res:
print("no prediction files found in", a.pred)
if __name__ == "__main__":
main()
|