File size: 8,116 Bytes
41e802a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Localise sound sources in a multichannel recording with the array tracker.

    python localise.py recording.wav mics.json --out directions.csv

recording.wav   one channel per microphone; any sample rate (it is resampled to 16 kHz)
mics.json       [[x, y, z], ...] in metres, one row per channel in the order of the file; any origin, any axes.
                A .npy file or a text file with three columns is read too.

The output has one row per 8 ms frame and declared source:

    time_s          centre of the frame's 32 ms window, in seconds from the start of the recording
    slot            which of the model's four outputs this is (0 to 3); a slot is not an identity over time
    length          length of the output vector: near 1 when the model is sure a source is there, near 0 when not
    azimuth_deg     atan2(y, x), counter-clockwise from the x axis of your microphone coordinates, -180 to 180
    elevation_deg   angle above the x-y plane of your microphone coordinates, -90 to 90
    x, y, z         the same direction as a unit vector from the centre of the array towards the source

Options:
    --threshold 0.5     a source is declared when its vector is longer than this (0.5 is what the model was trained with)
    --sources N         you know how many sources there are: write the N longest vectors of every frame instead,
                        whatever their length
    --all               write all four outputs of every frame
    --device cuda       run on a GPU

From Python:

    import localise
    net = localise.load()                                    # the folder of this file
    vector, time = localise.localise(net, audio, positions)  # audio [M, samples] at 16 kHz, positions [M, 3] in metres
    declared, direction, azimuth, elevation = localise.decode(vector)
"""
from __future__ import annotations

import argparse
import csv
import json
import math
from pathlib import Path

import numpy as np
import torch

from model import Tracker, TrackerConfig

LONG_FRAMES = 1000      # a recording longer than this (8 s) is run in pieces that carry the model's state: same outputs
CHUNK_FRAMES = 500


def load(folder=None, device="cpu") -> Tracker:
    """The model with its trained weights. `folder` holds config.json and model.safetensors (default: next to this file)."""
    from safetensors.torch import load_file
    folder = Path(folder) if folder is not None else Path(__file__).resolve().parent
    net = Tracker(TrackerConfig(**json.loads((folder / "config.json").read_text())))
    net.load_state_dict(load_file(str(folder / "model.safetensors")))
    return net.to(device).eval()


@torch.no_grad()
def localise(net: Tracker, audio, positions):
    """audio [M, samples] at net.cfg.fs (16 kHz), positions [M, 3] in metres, one row per channel.
    Returns vector [T, 4, 3], one row of four output vectors per 8 ms frame, and time [T], the centre of each frame's
    window in seconds. Frame t covers samples t * 128 to t * 128 + 511."""
    cfg = net.cfg
    device = next(net.parameters()).device
    audio = torch.as_tensor(audio, dtype=torch.float32, device=device)
    positions = torch.as_tensor(positions, dtype=torch.float32, device=device)
    assert audio.ndim == 2 and positions.shape == (audio.shape[0], 3), \
        f"audio must be [microphones, samples] and positions [microphones, 3]; got {tuple(audio.shape)} and {tuple(positions.shape)}"
    assert audio.shape[1] >= cfg.n_fft, f"the recording is shorter than one analysis window ({cfg.n_fft} samples)"
    positions = positions - positions.mean(0, keepdim=True)          # origin at the centre of the array, as in training
    frames = (audio.shape[1] - cfg.n_fft) // cfg.hop + 1
    if frames > LONG_FRAMES:
        out = net.chunked(audio[None], positions[None], CHUNK_FRAMES)
    else:
        out = net(audio[None], positions[None])
    time = (torch.arange(frames, dtype=torch.float64) * cfg.hop + cfg.n_fft / 2) / cfg.fs
    return out["vector"][0].cpu(), time


def decode(vector: torch.Tensor, threshold: float = 0.5):
    """vector [T, K, 3] -> declared [T, K] (longer than `threshold`), direction [T, K, 3] (unit vectors from the array
    towards the source), azimuth [T, K] and elevation [T, K] in degrees."""
    length = vector.norm(dim=-1)
    direction = vector / length.clamp(min=1e-9)[..., None]
    azimuth = torch.rad2deg(torch.atan2(direction[..., 1], direction[..., 0]))
    elevation = torch.rad2deg(torch.asin(direction[..., 2].clamp(-1, 1)))
    return length > threshold, direction, azimuth, elevation


def read_positions(path) -> np.ndarray:
    path = Path(path)
    if path.suffix == ".json":
        positions = np.array(json.loads(path.read_text()), dtype=np.float64)
    elif path.suffix == ".npy":
        positions = np.load(path).astype(np.float64)
    else:
        positions = np.loadtxt(path, delimiter="," if "," in path.read_text() else None, dtype=np.float64)
    assert positions.ndim == 2 and positions.shape[1] == 3, f"{path}: expected one row of x, y, z per microphone, got shape {positions.shape}"
    return positions


def read_audio(path, fs: int) -> np.ndarray:
    """A recording as [channels, samples] at `fs`, with the scale the file has (16-bit full scale is 1.0)."""
    import soundfile as sf
    audio, rate = sf.read(str(path), dtype="float32", always_2d=True)
    if rate != fs:
        from scipy.signal import resample_poly
        divisor = math.gcd(int(rate), fs)
        audio = resample_poly(audio, fs // divisor, int(rate) // divisor, axis=0).astype(np.float32)
    return np.ascontiguousarray(audio.T)


def main():
    parser = argparse.ArgumentParser(description="Directions of sound sources in a multichannel recording, one row per 8 ms frame.")
    parser.add_argument("recording", help="audio file with one channel per microphone")
    parser.add_argument("mics", help="microphone positions in metres, one row of x, y, z per channel (.json, .npy or text)")
    parser.add_argument("--out", default=None, help="CSV file to write (default: the recording's name with .directions.csv)")
    parser.add_argument("--threshold", type=float, default=0.5, help="a source is declared when its vector is longer than this")
    parser.add_argument("--sources", type=int, default=None, help="known number of sources: write that many longest vectors per frame")
    parser.add_argument("--all", action="store_true", help="write all four outputs of every frame")
    parser.add_argument("--device", default="cpu")
    args = parser.parse_args()

    net = load(device=args.device)
    positions = read_positions(args.mics)
    audio = read_audio(args.recording, net.cfg.fs)
    assert audio.shape[0] == len(positions), f"the recording has {audio.shape[0]} channels and {args.mics} has {len(positions)} microphones"
    vector, time = localise(net, audio, positions)
    declared, direction, azimuth, elevation = decode(vector, args.threshold)
    length = vector.norm(dim=-1)
    if args.all:
        keep = torch.ones_like(declared)
    elif args.sources is not None:
        assert 1 <= args.sources <= vector.shape[1], f"--sources must be 1 to {vector.shape[1]}"
        keep = torch.zeros_like(declared).scatter_(1, length.argsort(dim=1, descending=True)[:, :args.sources], True)
    else:
        keep = declared
    out = Path(args.out) if args.out else Path(args.recording).with_suffix(".directions.csv")
    with open(out, "w", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow(["time_s", "slot", "length", "azimuth_deg", "elevation_deg", "x", "y", "z"])
        for t, k in keep.nonzero().tolist():
            writer.writerow([f"{time[t]:.3f}", k, f"{length[t, k]:.3f}", f"{azimuth[t, k]:.2f}", f"{elevation[t, k]:.2f}",
                             *(f"{value:.4f}" for value in direction[t, k].tolist())])
    print(f"{len(time)} frames ({time[-1] + net.cfg.n_fft / 2 / net.cfg.fs:.1f} s), {audio.shape[0]} microphones; "
          f"a source is declared in {100 * declared.any(1).float().mean():.0f}% of the frames; {int(keep.sum())} rows in {out}")


if __name__ == "__main__":
    main()