File size: 7,087 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
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python3
"""Resolve VeriSpoof-Bench audio from your local corpus copies and regenerate the derived items.

    python scripts/prepare_audio.py --roots LA19=/corpora/ASVspoof2019 InTheWild=/corpora/itw ... \
        [--musan /corpora/musan --rirs /corpora/RIRS_NOISES] [--subsets ...] [--out bench_audio] [--check] [--md5]

--roots      one ROOT=DIR per corpus root used by the items (`audio[].root`: LA19, ASVspoof2021, ASVspoof5, InTheWild,
             SpoofCeleb, MLAAD, STOPA, DFADD, LibriSeVoc, CodecFakePlus, PartialSpoof, HAD, PartialEdit,
             LlamaPartialSpoof). DIR/<audio[].path> should exist; if your layout differs, files are found by the longest
             matching path suffix under DIR.
--musan/--rirs  MUSAN (OpenSLR 17) and RIRS_NOISES (OpenSLR 28) roots, needed for augmented / recorded-condition items
--check      only report missing files (and with --md5, files whose MD5 differs from `audio[].md5`)

Writes <out>/manifest.csv (item_id, subset, role, path): for clean items the path of your original file (the model
reads it and uses the first 8 s, tiling shorter files); for derived items (augmented / recorded-condition /
post-processed) a 16 kHz float32 WAV of the exact 8 s window the evaluation used, regenerated by
scripts/vsbench_audio.py (the replayed random draws are checked against the stored `realization`). EnCodec items
need torch + transformers; ffmpeg 7.0.2 (static build, e.g. johnvansickle.com) via $VSBENCH_FFMPEG reproduces the
classical codecs bit-exactly.
"""
import argparse
import csv
import glob
import hashlib
import json
import os
import sys
from multiprocessing import Pool

import pyarrow.parquet as pq

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vsbench_audio as VA  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))


class Resolver:
    def __init__(self, roots):
        self.roots, self.index = roots, {}

    def _index(self, root):
        if root not in self.index:
            idx = {}
            for dp, _, fs in os.walk(self.roots[root]):
                for f in fs:
                    idx.setdefault(f, []).append(os.path.join(dp, f))
            self.index[root] = idx
        return self.index[root]

    def __call__(self, root, rel):
        if root not in self.roots:
            return None
        p = os.path.join(self.roots[root], rel)
        if os.path.exists(p):
            return p
        cands = self._index(root).get(os.path.basename(rel), [])
        best, score = None, -1
        parts = rel.split("/")
        for c in cands:
            cp = c.split(os.sep)
            n = 0
            while n < min(len(parts), len(cp)) and parts[-1 - n] == cp[-1 - n]:
                n += 1
            if n > score:
                best, score = c, n
            elif n == score:
                best = None  # ambiguous
        return best


def md5(p):
    h = hashlib.md5()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


_W = {}


def _realize(job):
    key, src_path, seed_key, cond, proc, real, out, musan, rirs = job
    if "src" not in _W:
        _W["src"] = VA.Sources(musan, rirs) if musan else None
        _W["enc"] = None
    if cond and cond["codec_kind"] in ("neural", "cascade") and _W["enc"] is None:
        _W["enc"] = VA.EnCodec()
    if os.path.exists(out):
        return key, out, None
    try:
        x, tr = VA.realize(src_path, seed_key, cond, proc, _W["src"], _W["enc"], check=real)
    except AssertionError as e:
        return key, None, str(e)
    import soundfile as sf
    os.makedirs(os.path.dirname(out), exist_ok=True)
    sf.write(out + ".part.wav", x, VA.SR, subtype="FLOAT")
    os.replace(out + ".part.wav", out)
    return key, out, None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--roots", nargs="+", default=[], help="ROOT=DIR")
    ap.add_argument("--musan")
    ap.add_argument("--rirs")
    ap.add_argument("--bench", default=os.path.join(HERE, ".."))
    ap.add_argument("--subsets", nargs="*")
    ap.add_argument("--out", default="bench_audio")
    ap.add_argument("--check", action="store_true")
    ap.add_argument("--md5", action="store_true")
    ap.add_argument("--workers", type=int, default=8)
    a = ap.parse_args()
    roots = dict(r.split("=", 1) for r in a.roots)
    res = Resolver(roots)
    files = sorted(glob.glob(f"{a.bench}/data/*.parquet"))
    subsets = a.subsets or [os.path.basename(f)[:-8] for f in files]
    rows, missing, bad, jobs, derived = [], {}, [], {}, {}
    for s in subsets:
        for it in pq.read_table(f"{a.bench}/data/{s}.parquet", columns=["item_id", "audio"]).to_pylist():
            for au in it["audio"]:
                p = res(au["root"], au["path"])
                if p is None:
                    missing.setdefault(au["root"], set()).add(au["path"])
                    continue
                if a.md5 and md5(p) != au["md5"]:
                    bad.append(p)
                if au["derived"] or au["post_processing"]:
                    proc = au["post_processing"]
                    key = au["seed_key"] + ("" if proc is None else "__proc_" + hashlib.md5(
                        json.dumps(proc, sort_keys=True).encode()).hexdigest()[:10])
                    out = os.path.join(a.out, "derived", key.replace("/", "__").replace("#", "_") + ".wav")
                    jobs[key] = (key, p, au["seed_key"], au["condition"] if au["derived"] else None, proc,
                                 au["realization"] if au["derived"] else None, out, a.musan, a.rirs)
                    derived[(it["item_id"], au["role"])] = key
                    rows.append([it["item_id"], s, au["role"], out])
                else:
                    rows.append([it["item_id"], s, au["role"], p])
    for r, ps in sorted(missing.items()):
        print(f"missing {len(ps)} files under root {r}" + ("" if r in roots else " (no --roots entry)"), flush=True)
    if a.md5:
        print(f"{len(bad)} files with a different MD5", flush=True)
    if a.check:
        return
    if any(j[3] for j in jobs.values()) and not (a.musan and a.rirs):
        raise SystemExit("augmented / recorded-condition items need --musan and --rirs")
    errors = []
    with Pool(a.workers) as pool:
        for k, (key, out, err) in enumerate(pool.imap_unordered(_realize, list(jobs.values()), chunksize=8)):
            if err:
                errors.append(err)
            if k % 1000 == 0:
                print(f"derived {k}/{len(jobs)}", flush=True)
    for e in errors[:10]:
        print("REALIZATION MISMATCH", e)
    os.makedirs(a.out, exist_ok=True)
    with open(f"{a.out}/manifest.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["item_id", "subset", "role", "path"])
        w.writerows(rows)
    print(f"{len(rows)} audio entries ({len(jobs)} derived files) -> {a.out}/manifest.csv; "
          f"{sum(map(len, missing.values()))} missing; {len(errors)} realization mismatches")


if __name__ == "__main__":
    main()