File size: 9,365 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
#!/usr/bin/env python3
"""How well does SoundAQNet match in-situ human ratings? (International Soundscape Database)

ISD (Zenodo 10672568) pairs ~30-s calibrated binaural recordings (WAV values in pascals, file name
= GroupID) with the 8 attribute ratings of the people present. Each recording is scored by
SoundAQNet in three level conditions (as in the project pipeline):
  per_clip_-30LUFS   the old project pipeline
  calibrated         true level: pascals converted with SoundAQNet's own calibration
  fixed_gain         one gain for all recordings (median at -30 LUFS)
for the full recording and a 10-s centre crop (the project's clip length).
Agreement is Spearman between SoundAQNet and human ratings at the recording level (mean of the
group's raters), the individual-rating level, and the location level. Two references:
  human split-half   agreement between two halves of each group's raters (how consistent people are)
  LAeq only          ranking recordings by measured loudness alone (a physical baseline)
"""
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
from pathlib import Path

import numpy as np
import pandas as pd
import soundfile as sf
from scipy.stats import spearmanr

AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
LOUDNESS_SIGN = {"pleasant": -1, "eventful": 1, "chaotic": 1, "vibrant": 1, "uneventful": -1,
                 "calm": -1, "annoying": 1, "monotonous": -1}


def parse_args():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--isd-root", type=Path, required=True)
    p.add_argument("--output-dir", type=Path, default=Path("runs_main_all_datasets/soundaq_vs_isd"))
    p.add_argument("--model", default="SoundAQnet_ASC96_AEC94_PAQ1027")
    p.add_argument("--device", default="cuda")
    p.add_argument("--exclude-location", action="append", default=[])
    p.add_argument("--split-half-repeats", type=int, default=200)
    return p.parse_args()


def mean_rho(a, b, columns):
    values = [spearmanr(a[c], b[c], nan_policy="omit").statistic for c in columns]
    return float(np.nanmean(values)), dict(zip(columns, map(float, values)))


def split_half(ratings, repeats, rng):
    """Spearman between the means of two random halves of each group's raters (groups with >= 2 raters)."""
    groups = [g for _, g in ratings.groupby("GroupID") if len(g) >= 2]
    out = []
    for _ in range(repeats):
        a, b = [], []
        for g in groups:
            order = rng.permutation(len(g))
            half = len(g) // 2
            a.append(g.iloc[order[:half]][AQ].mean())
            b.append(g.iloc[order[half:]][AQ].mean())
        a, b = pd.DataFrame(a), pd.DataFrame(b)
        out.append([spearmanr(a[c], b[c], nan_policy="omit").statistic for c in AQ])
    rho = np.nanmean(np.asarray(out), axis=0)
    return float(np.mean(rho)), dict(zip(AQ, map(float, rho))), len(groups)


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

    data = pd.read_csv(args.isd_root / "ISD v1.0 Data.csv", low_memory=False)
    wavs = {p.stem: p for p in args.isd_root.rglob("*.wav") if "__MACOSX" not in p.parts}
    ratings = data[data.GroupID.isin(wavs) & ~data.LocationID.isin(args.exclude_location)].copy()
    ratings = ratings.dropna(subset=AQ, how="all")
    groups = ratings.groupby("GroupID").agg(LocationID=("LocationID", "first"), laeq=("LAeq_L(A)", "first"),
                                            raters=("RecordID", "size"))
    human = ratings.groupby("GroupID")[AQ].mean()
    print(f"{len(ratings)} ratings, {len(groups)} recordings, {groups.LocationID.nunique()} locations")

    cal, _ = sf.read(str(_calibration_wav()))
    cal = cal if cal.ndim == 1 else cal.mean(axis=1)
    offset = 60.0 - 20 * np.log10(np.sqrt(np.mean(cal ** 2)))   # dB SPL = dBFS + offset
    pa_per_unit = 2e-5 * 10 ** (offset / 20)                     # pascals of a digital value of 1.0

    prepared, skipped = [], set()
    for gid in groups.index:
        x, fs = sf.read(str(wavs[gid]), always_2d=True)
        bad = ~np.isfinite(x)
        if bad.any():
            print(f"[warn] {gid}: {int(bad.sum())} non-finite samples set to 0")
            x = np.where(bad, 0.0, x)
        mono_pa = x[:, :2].mean(axis=1)
        for crop in ("full", "10s"):
            y = mono_pa
            if crop == "10s":
                n = int(10 * fs)
                start = max(0, (len(y) - n) // 2)
                y = y[start:start + n]
            digital = y / pa_per_unit                             # calibrated digital signal
            lufs = pyloudnorm.Meter(fs).integrated_loudness(digital)
            if not np.isfinite(lufs) or np.max(np.abs(digital)) == 0:
                print(f"[warn] {gid} ({crop}): loudness not measurable (silent?); recording skipped")
                skipped.add(gid)
                continue
            prepared.append(dict(gid=gid, crop=crop, fs=fs, digital=digital, lufs=lufs))
    if skipped:
        prepared = [q for q in prepared if q["gid"] not in skipped]
        groups = groups.drop(index=list(skipped))
        human = human.drop(index=list(skipped))
        ratings = ratings[~ratings.GroupID.isin(skipped)]
        print(f"Skipped {len(skipped)} recordings: {sorted(skipped)}")
    teacher = SoundAQnet(args.model, device=args.device)
    rows, predictions = [], {}
    for crop in ("full", "10s"):
        items = [q for q in prepared if q["crop"] == crop]
        shift = -30.0 - float(np.median([q["lufs"] for q in items]))
        conditions = {"per_clip_-30LUFS": lambda q: -30.0 - q["lufs"], "calibrated": lambda q: 0.0,
                      "fixed_gain": lambda q: shift}
        for condition, gain in conditions.items():
            folder = args.output_dir / "audio" / f"{crop}_{condition}"
            folder.mkdir(parents=True, exist_ok=True)
            paths = []
            for q in items:
                out = folder / f"{q['gid']}.wav"
                audio = np.nan_to_num(q["digital"] * 10 ** (gain(q) / 20), nan=0.0, posinf=0.0, neginf=0.0)
                sf.write(str(out), audio.astype(np.float32), q["fs"], subtype="FLOAT")
                paths.append(out)
            mels = extract_mel_from_file(paths, num_workers=4)
            louds = extract_loudness_from_file(paths, num_workers=4)
            pred = pd.DataFrame({o.stem: [teacher.predict_sample(np.asarray(mels[o.stem], np.float32),
                                                                 np.asarray(louds[o.stem], np.float32))[c] for c in PAQ_COLUMNS]
                                 for o in paths}, index=AQ).T
            predictions[(crop, condition)] = pred
            pred.to_csv(args.output_dir / f"predictions_{crop}_{condition}.csv")
            g_rho, g_by = mean_rho(pred.loc[human.index], human, AQ)
            ind = ratings.set_index("GroupID")[AQ]
            i_rho, _ = mean_rho(pred.loc[ind.index].reset_index(drop=True), ind.reset_index(drop=True), AQ)
            loc_pred = pred.loc[human.index].groupby(groups.LocationID).mean()
            loc_human = human.groupby(groups.LocationID).mean()
            l_rho, _ = mean_rho(loc_pred, loc_human, AQ)
            rows.append({"crop": crop, "condition": condition, "recording_rho": g_rho, "individual_rho": i_rho,
                         "location_rho": l_rho, **{f"rec_{a}": g_by[a] for a in AQ}})
    rng = np.random.default_rng(0)
    sh_mean, sh_by, sh_groups = split_half(ratings, args.split_half_repeats, rng)
    laeq = pd.DataFrame({a: groups.laeq * LOUDNESS_SIGN[a] for a in AQ})
    laeq_rho, laeq_by = mean_rho(laeq.loc[human.index], human, AQ)
    table = pd.DataFrame(rows)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    table.to_csv(args.output_dir / "summary.csv", index=False)
    (args.output_dir / "summary.json").write_text(json.dumps({
        "ratings": int(len(ratings)), "recordings": int(len(groups)), "locations": int(groups.LocationID.nunique()),
        "calibration_offset_db": offset, "human_split_half": {"mean": sh_mean, "by_attribute": sh_by, "groups": sh_groups},
        "laeq_only_recording_rho": {"mean": laeq_rho, "by_attribute": laeq_by}, "conditions": rows}, indent=2))
    pd.set_option("display.width", 220)
    print(table[["crop", "condition", "recording_rho", "individual_rho", "location_rho"] + [f"rec_{a}" for a in AQ]].round(3).to_string(index=False))
    print(f"\nHuman split-half agreement (recordings with >=2 raters, n={sh_groups}): {sh_mean:.3f}  "
          + ", ".join(f"{a} {v:.2f}" for a, v in sh_by.items()))
    print(f"LAeq only (louder = less pleasant/calm, more eventful/annoying): {laeq_rho:.3f}  "
          + ", ".join(f"{a} {v:.2f}" for a, v in laeq_by.items()))


if __name__ == "__main__":
    main()