File size: 4,516 Bytes
adabee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pulse locking per band: how identically each band's energy repeats from one pitch period to
the next (tiny-voca-it docs/analysis/quality-journey.md §2: autocorrelation at the pitch lag).
Real speech varies a little every cycle; a pulse-train source repeats too exactly, and the ear
hears that as buzz, most of all on long vowels. Higher = more regular. Compare with real
recordings of the same voice (tiny-voca-it: real 0.31-0.55 / 0.32-0.48 / 0.21-0.48 at
1-2 / 2-4 / 4-6 kHz; buzzy vocoders 0.6-0.7).

Per voiced frame (pYIN pitch, librosa), the band-passed signal's Hilbert envelope over two
periods is correlated with the next two periods (Pearson). Reported: the mean over all voiced
frames, and over frames inside voiced runs of at least --long-ms (a long-vowel proxy).

Usage (inside the `quality` service, data root mounted at /work):
  python scripts/pulse_locking.py --out checks/locking/<name>.json \
      --group "real=out/copy-voc50k/real/*.wav" --group "v3trim=out/val-v3trim-s30000-voc50k/vocoded/*.wav"
"""
import argparse
import glob
import json
from pathlib import Path

import librosa
import numpy as np
from scipy.signal import butter, hilbert, sosfiltfilt

SR = 24000
HOP = 256
BANDS = ((1000, 2000), (2000, 4000), (4000, 6000))


def runs_mask(flags, minimum):
    """True for frames inside runs of True at least `minimum` long."""
    out, start = np.zeros_like(flags), None
    for i, f in enumerate(np.append(flags, False)):
        if f and start is None:
            start = i
        elif not f and start is not None:
            if i - start >= minimum:
                out[start:i] = True
            start = None
    return out


def clip_locking(path, long_frames):
    y, _ = librosa.load(path, sr=SR, mono=True)
    f0, voiced, _ = librosa.pyin(y, fmin=60, fmax=400, sr=SR, frame_length=2048, hop_length=HOP)
    voiced = voiced & np.isfinite(f0)
    long = runs_mask(voiced, long_frames)
    result = {}
    for lo, hi in BANDS:
        envelope = np.abs(hilbert(sosfiltfilt(butter(4, [lo, hi], btype='band', fs=SR, output='sos'), y)))
        values, long_values = [], []
        for i in np.flatnonzero(voiced):
            lag = int(round(SR / f0[i]))
            start = i * HOP - lag
            if start < 0 or start + 3 * lag > len(envelope):
                continue
            a = envelope[start:start + 2 * lag] - envelope[start:start + 2 * lag].mean()
            b = envelope[start + lag:start + 3 * lag] - envelope[start + lag:start + 3 * lag].mean()
            denominator = np.sqrt((a * a).sum() * (b * b).sum())
            if denominator > 0:
                values.append(float((a * b).sum() / denominator))
                if long[i]:
                    long_values.append(values[-1])
        result[f'{lo // 1000}-{hi // 1000}k'] = (values, long_values)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--group', action='append', required=True, help='"name=glob"')
    parser.add_argument('--long-ms', type=float, default=150)
    parser.add_argument('--out', type=Path, required=True)
    args = parser.parse_args()
    long_frames = int(round(args.long_ms / 1000 * SR / HOP))
    report = {'method': 'Pearson correlation of the band Hilbert envelope, 2 periods vs the next 2, pYIN voiced frames',
              'long_ms': args.long_ms, 'groups': {}}
    for spec in args.group:
        name, pattern = spec.split('=', 1)
        files = sorted(glob.glob(pattern))
        if not files:
            raise SystemExit(f'no files for {name}: {pattern}')
        pooled = {}
        for path in files:
            for band, (values, long_values) in clip_locking(path, long_frames).items():
                pooled.setdefault(band, ([], []))
                pooled[band][0].extend(values)
                pooled[band][1].extend(long_values)
        summary = {band: {'all': float(np.mean(v)), 'long': float(np.mean(lv)) if lv else None,
                          'frames': len(v), 'long_frames': len(lv)} for band, (v, lv) in pooled.items()}
        report['groups'][name] = {'files': len(files), 'bands': summary}
        cells = '  '.join(f"{band} {s['all']:.2f} (long {s['long']:.2f})" for band, s in summary.items())
        print(f'{name:28s} n={len(files):3d}  {cells}', flush=True)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(report, indent=2))


if __name__ == '__main__':
    main()