File size: 13,576 Bytes
16231ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
"""Rebuild SoundAQNet targets with a different fixed-gain reference (default -30 -> -40 LUFS).

Every dataset already has ONE gain that puts its median training clip at -30 LUFS (Ann Arbor/Detroit:
one gain per city). Moving the reference to -40 LUFS is therefore the same -10 dB on every
re-levelled clip, keeping all level differences between and within datasets. Nothing is learned.

Why: SoundAQNet agrees better with human ratings at a quieter reference
(check_soundaq_vs_humans.py: SATP 0.58 -> 0.72, Mumbai 0.46 -> 0.49 for -30 -> -40).

Steps
  1. For every scored pair in the target cache, find the waveform SoundAQNet scored for the current
     targets (the -30 re-levelled waveform from the rescaled_manifest.csv files; Ann Arbor/Detroit:
     its per-city waveform).
  2. Check: SoundAQNet on a few of these waveforms at 0 dB must reproduce the stored targets.
  3. In chunks: write the waveforms shifted by --delta-db to a temporary folder, run SoundAQNet
     (mel + ISO 532-1 loudness), save SoundAQ and Direct-AQ targets, delete the temporary audio.
     Resumable: finished targets are skipped.
  4. Write a new revision: manifest with the new target paths, the same folds and training
     exclusions, and a target cache with the new targets.
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]

import argparse
import json
import shutil
from pathlib import Path

import numpy as np
import pandas as pd
import soundfile as sf
from tqdm import tqdm

BASE = "urbansas_whole_yfcc_binaural_v1_yfcc_nogeo_b0_21105_allnew"
RESCALED = [   # rescaled_manifest.csv of every revision that the combined revision draws on (pass your own list)
    "runs_main_all_datasets/direct_aq_dataset_gain/urbansas_whole_yfcc_binaural_v1/rescaled_manifest.csv",
    "runs_main_all_datasets/yfcc_nogeo/urbansas_whole_yfcc_binaural_v1_b0_21105/dataset_gain/rescaled_manifest.csv",
    "runs_main_all_datasets/sonicurban/urbansas_whole_yfcc_binaural_v1_yfcc_nogeo_b0_21105_s3/dataset_gain/rescaled_manifest.csv",
]


def parse_args():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--revision-dir", type=Path, default=Path(f"runs_main_all_datasets/direct_aq_dataset_gain/{BASE}"))
    p.add_argument("--cache", type=Path, default=Path(f"runs_main_all_datasets/photo_aqnet/{BASE}/feature_cache.npz"))
    p.add_argument("--rescaled-manifests", type=Path, nargs="+", default=[Path(x) for x in RESCALED])
    p.add_argument("--delta-db", type=float, default=-10.0, help="-10 moves the reference from -30 to -40 LUFS")
    p.add_argument("--work-dir", type=Path, default=Path("runs_main_all_datasets/ref40"),
                   help="targets, temporary audio and the new target cache")
    p.add_argument("--new-revision-dir", type=Path, default=Path(f"runs_main_all_datasets/direct_aq_dataset_gain/{BASE}_ref40"))
    p.add_argument("--model", default="SoundAQnet_ASC96_AEC94_PAQ1027")
    p.add_argument("--device", default="cuda")
    p.add_argument("--num-workers", type=int, default=8)
    p.add_argument("--chunk-size", type=int, default=256)
    p.add_argument("--check-per-dataset", type=int, default=3)
    p.add_argument("--check-tolerance", type=float, default=0.02)
    p.add_argument("--limit", type=int, help="process only this many pairs (testing)")
    return p.parse_args()


def norm(p) -> str:
    return str(p).replace("/", "\\").casefold()


def scored_waveforms(manifest, cache_keys, rescaled_paths):
    """One row per scored pair with the waveform SoundAQNet scored for the current targets."""
    keys = set(cache_keys)
    m = manifest.copy()
    m["cache_key"] = m.view_id.astype(str) + "|" + m.direct_aq_target_path.astype(str)
    m = m[m.cache_key.isin(keys)].copy()
    parts = []
    for path in rescaled_paths:
        r = pd.read_csv(path, low_memory=False, usecols=lambda c: c in {
            "view_id", "standardized_waveform_path", "original_standardized_waveform_path", "level_rescaled"})
        r = r[r.level_rescaled.astype(str).str.lower().eq("true")]
        parts.append(r)
    r = pd.concat(parts, ignore_index=True)
    r["key"] = r.view_id.astype(str) + "|" + r.original_standardized_waveform_path.map(norm)
    r = r.drop_duplicates("key").set_index("key").standardized_waveform_path
    m["key"] = m.view_id.astype(str) + "|" + m.standardized_waveform_path.map(norm)
    m["scored_waveform"] = m.key.map(r)
    # Clips that were never per-clip re-levelled (Ann Arbor/Detroit per-city waveforms) were scored as they are.
    kept = m.scored_waveform.isna()
    m.loc[kept, "scored_waveform"] = m.loc[kept, "standardized_waveform_path"]
    m["scored_waveform_source"] = np.where(kept, "standardized (per-city / kept)", "dataset-gain waveform")
    return m.drop(columns="key")


def soundaq_batch(teacher, paths, workers, extract_mel_from_file, extract_loudness_from_file):
    mels = extract_mel_from_file(paths, num_workers=workers)
    louds = extract_loudness_from_file(paths, num_workers=workers)
    out = {}
    for path in paths:
        mel = np.asarray(mels[path.stem], np.float32)
        loud = np.asarray(louds[path.stem], np.float32)
        out[path.stem] = (mel, loud, teacher.predict_sample(mel, loud))
    return out


def main():
    args = parse_args()
    from soundaqnet import SoundAQnet
    from soundaqnet.feature_extraction.loudness import extract_loudness_from_file
    from soundaqnet.feature_extraction.mel_spectrogram import extract_mel_from_file
    from soundaqnet.framework import config
    from soundaqnet.inference import EVENT_LABELS, PAQ_COLUMNS

    def vectors(pred):
        ev = np.asarray([pred["event_probs"][lab] for lab in EVENT_LABELS], np.float32)
        aff = np.asarray([pred["isop"], pred["isoe"]] + [pred[c] for c in PAQ_COLUMNS], np.float32)
        sc = list(config.scene_labels).index(pred["scene"])
        return aff, ev, sc

    manifest = pd.read_csv(args.revision_dir / "metadata_manifest.csv", low_memory=False)
    with np.load(args.cache, allow_pickle=True) as z:
        cache = {k: z[k] for k in z.files}
    m = scored_waveforms(manifest, cache["keys"], args.rescaled_manifests)
    missing = ~m.scored_waveform.map(lambda p: Path(str(p)).is_file())
    print(f"{len(m)} scored pairs; waveform source: {m.scored_waveform_source.value_counts().to_dict()}; "
          f"missing audio: {int(missing.sum())}")
    if missing.any():
        print(m.loc[missing, ["training_dataset", "scored_waveform"]].head())
        raise SystemExit("Some scored waveforms are missing; stopping.")
    if args.limit:
        m = m.groupby("training_dataset", group_keys=False).head(max(1, args.limit // m.training_dataset.nunique()))

    teacher = SoundAQnet(args.model, device=args.device)
    tmp = args.work_dir / "tmp_audio"
    tmp.mkdir(parents=True, exist_ok=True)

    # 2. Check that the waveform mapping reproduces the current targets at 0 dB.
    sample = m.groupby("training_dataset", group_keys=False).head(args.check_per_dataset)
    paths = []
    for _, row in sample.iterrows():
        audio, rate = sf.read(str(row.scored_waveform), dtype="float32")
        out = tmp / f"check_{row.view_id}.wav"
        sf.write(str(out), audio, rate, subtype="FLOAT")
        paths.append(out)
    res = soundaq_batch(teacher, paths, args.num_workers, extract_mel_from_file, extract_loudness_from_file)
    worst = {}
    for (_, row), path in zip(sample.iterrows(), paths):
        with np.load(str(row.direct_aq_target_path), allow_pickle=False) as z:
            stored = z["affective_mean"]
        diff = float(np.abs(vectors(res[path.stem][2])[0] - stored).max())
        worst[row.training_dataset] = max(worst.get(row.training_dataset, 0.0), diff)
        path.unlink()
    print("Check at 0 dB, max |new - stored| per dataset:", {k: round(v, 4) for k, v in worst.items()})
    bad = {k: v for k, v in worst.items() if v > args.check_tolerance}
    if bad:
        raise SystemExit(f"Stored targets not reproduced for {bad}; the waveform mapping is wrong, stopping.")

    # 3. Shifted targets, in chunks.
    gain = np.float32(10 ** (args.delta_db / 20))
    sa_dir, dt_dir = args.work_dir / "soundaq" / "targets", args.work_dir / "direct_targets" / "targets"
    sa_dir.mkdir(parents=True, exist_ok=True)
    dt_dir.mkdir(parents=True, exist_ok=True)
    m["new_soundaq_target_path"] = [str((sa_dir / f"{v}.npz").resolve()) for v in m.view_id]
    m["new_direct_aq_target_path"] = [str((dt_dir / f"{v}.npz").resolve()) for v in m.view_id]
    todo = m[~m.new_direct_aq_target_path.map(lambda p: Path(p).is_file())]
    print(f"{len(m) - len(todo)} targets already done, {len(todo)} to compute (delta {args.delta_db:+g} dB)")
    peaks = 0
    for start in tqdm(range(0, len(todo), args.chunk_size), desc="Re-levelled SoundAQNet chunks"):
        chunk = todo.iloc[start:start + args.chunk_size]
        paths = []
        for _, row in chunk.iterrows():
            audio, rate = sf.read(str(row.scored_waveform), dtype="float32")
            audio = audio * gain
            peaks += int(np.max(np.abs(audio)) > 1.0)
            out = tmp / f"{row.view_id}.wav"
            sf.write(str(out), audio, rate, subtype="FLOAT")
            paths.append(out)
        res = soundaq_batch(teacher, paths, args.num_workers, extract_mel_from_file, extract_loudness_from_file)
        for (_, row), path in zip(chunk.iterrows(), paths):
            mel, loud, pred = res[path.stem]
            aff, ev, sc = vectors(pred)
            scene = np.zeros(3, np.float32)
            scene[sc] = 1.0
            sa, dt = Path(row.new_soundaq_target_path), Path(row.new_direct_aq_target_path)
            np.savez_compressed(sa.with_suffix(".tmp.npz"), mel=mel, loudness=loud, event_probabilities=ev,
                                scene_index=np.asarray(sc, np.int64), affective=aff)
            sa.with_suffix(".tmp.npz").replace(sa)
            np.savez_compressed(dt.with_suffix(".tmp.npz"), affective_mean=aff, affective_std=np.zeros_like(aff),
                                event_mean=ev, event_std=np.zeros_like(ev), scene_probabilities=scene,
                                clip_count=np.asarray(1, np.int64), source_soundaq_target_path=np.asarray(str(sa)),
                                reference_delta_db=np.asarray(args.delta_db, np.float32))
            dt.with_suffix(".tmp.npz").replace(dt)
            path.unlink()
    shutil.rmtree(tmp, ignore_errors=True)
    if args.limit:
        print("--limit run: stopping before writing the revision.")
        return

    # 4. New revision: manifest, folds, exclusions, target cache.
    new = manifest.copy()
    new["previous_direct_aq_target_path"] = new.direct_aq_target_path
    sa_map = dict(zip(m.view_id.astype(str), m.new_soundaq_target_path))
    dt_map = dict(zip(m.view_id.astype(str), m.new_direct_aq_target_path))
    hit = new.view_id.astype(str).isin(dt_map)
    new.loc[hit, "soundaq_target_path"] = new.loc[hit, "view_id"].astype(str).map(sa_map)
    new.loc[hit, "direct_aq_target_path"] = new.loc[hit, "view_id"].astype(str).map(dt_map)
    new.loc[~hit, "direct_aq_target_status"] = "not_scored_in_base"
    new["target_level"] = f"dataset_gain_ref{-30 + args.delta_db:g}"
    args.new_revision_dir.mkdir(parents=True, exist_ok=True)
    new.to_csv(args.new_revision_dir / "metadata_manifest.csv", index=False)
    for name in ("cv_folds_combined.csv", "train_exclude_combined.csv"):
        if (args.revision_dir / name).exists():
            shutil.copy2(args.revision_dir / name, args.new_revision_dir / name)

    old_index = {k: i for i, k in enumerate(cache["keys"])}
    rows = m.cache_key.map(old_index).to_numpy()
    aff, ev, sc = [], [], []
    for p in tqdm(m.new_direct_aq_target_path, desc="New targets into the target cache"):
        with np.load(p, allow_pickle=False) as z:
            aff.append(z["affective_mean"]); ev.append(z["event_mean"]); sc.append(z["scene_probabilities"])
    new_keys = (m.view_id.astype(str) + "|" + m.new_direct_aq_target_path.astype(str)).to_numpy(dtype=object)
    out_cache = args.work_dir / "feature_cache.npz"
    np.savez(out_cache, version=2, keys=new_keys,
             aff=np.stack(aff).astype(np.float32), ev=np.stack(ev).astype(np.float32), sc=np.stack(sc).astype(np.float32))

    old_aff = cache["aff"][rows]
    new_aff = np.stack(aff)
    names = ["isop", "isoe", *PAQ_COLUMNS]
    summary = {
        "delta_db": args.delta_db, "reference_lufs": -30 + args.delta_db, "pairs": int(len(m)),
        "waveforms_with_peaks_above_full_scale": peaks, "check_max_abs_diff": worst,
        "mean_change": dict(zip(names, map(float, (new_aff - old_aff).mean(0)))),
        "spread_old_std": dict(zip(names, map(float, old_aff.std(0)))),
        "spread_new_std": dict(zip(names, map(float, new_aff.std(0)))),
        "rank_corr_old_new": {n: float(pd.Series(old_aff[:, i]).corr(pd.Series(new_aff[:, i]), method="spearman"))
                              for i, n in enumerate(names)},
    }
    (args.new_revision_dir / "relevel_summary.json").write_text(json.dumps(summary, indent=2))
    print(json.dumps(summary, indent=2))
    print(f"Wrote {args.new_revision_dir / 'metadata_manifest.csv'} and {out_cache}")


if __name__ == "__main__":
    main()