File size: 2,541 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared constants and tiny I/O helpers. Every other module imports these, so the
frame grid, label ids and file layout are defined exactly once."""
import json
import wave
from pathlib import Path

import numpy as np

SR = 16000                # input sample rate (caller audio, and self audio as the controller sees it)
FRAME_MS = 80
FRAME = SR * FRAME_MS // 1000          # 1280 samples per 80 ms frame
HOP = 160                 # 10 ms mel hop (same as the baseline encoder's front end)
N_FFT = 400
N_MELS = 128
PATCH = 4                 # mel frames per encoder token: 40 ms, 25 Hz (the baseline encoder's output rate)
TOK_PER_FRAME = FRAME // (HOP * PATCH)  # 2 encoder tokens per 80 ms frame
TEACHER_DIM = 1280        # baseline AudioEncoder n_audio_state (config.json of Step-Audio-R1.1)

OUT_SR = 24000            # reply audio sample rate (Step-Audio 2 token2wav and Kokoro both emit 24 kHz)
OUT_FRAME = OUT_SR * FRAME_MS // 1000  # 1920 samples

LABELS = ["WAIT", "START", "STOP", "BACKCHANNEL"]
WAIT, START, STOP, BACKCHANNEL = range(4)

CALLER, AGENT = 0, 1      # channel order in every dataset wav


def read_wav(path, start=0, frames=None):
    """PCM16 wav -> float32 [T, C] in [-1, 1], sample rate. Reads only the requested slice."""
    with wave.open(str(path), "rb") as w:
        assert w.getsampwidth() == 2, f"{path}: expected 16-bit PCM"
        n = w.getnframes()
        start = min(start, n)
        frames = n - start if frames is None else min(frames, n - start)
        w.setpos(start)
        x = np.frombuffer(w.readframes(frames), dtype="<i2").reshape(-1, w.getnchannels())
        return x.astype(np.float32) / 32768.0, w.getframerate()


def wav_len(path):
    with wave.open(str(path), "rb") as w:
        return w.getnframes()


def write_wav(path, x, sr):
    """float [T] or [T, C] in [-1, 1] -> PCM16 wav."""
    x = np.asarray(x, dtype=np.float32)
    if x.ndim == 1:
        x = x[:, None]
    pcm = (np.clip(x, -1.0, 1.0) * 32767.0).astype("<i2")
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    with wave.open(str(path), "wb") as w:
        w.setnchannels(pcm.shape[1])
        w.setsampwidth(2)
        w.setframerate(sr)
        w.writeframes(pcm.tobytes())


def read_jsonl(path):
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def write_json(path, obj):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        json.dump(obj, f, indent=2, ensure_ascii=False)