File size: 9,584 Bytes
c74e524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Voice worker: Aiden TTS + ASR with per-word causal prosody (codec_bench/env).

JSONL protocol on stdin/stdout.

  TTS  in : {"op":"tts","id":3,"text":"Sure, let me check."}
       out: {"id":3,"sr":24000,"ms":412,"dur":1.8,"audio_b64":"<wav>"}

  ASR  in : {"op":"asr","id":4,"wav_b64":"<16k mono wav>"}
       out: {"id":4,"text":"check the weather in berlin",
             "words":[{"w":"check","t0":0.12,"t1":0.41,"vec_b64":"<512 f16>"}], "ms":310}

The words carry the pooled causal Mimi vector over exactly the span the trainer uses
(word_start-0.08 .. word_end+0.16). That is what lets a live voice turn use the same
PROSODY-marker prompt shape as training instead of a clean-text fallback.
"""
from __future__ import annotations

import argparse
import os
import base64
import io
import json
import sys
import time
from pathlib import Path

import numpy as np
import soundfile as sf
import torch

TTS_MODEL = os.environ.get('AIDEN_TTS_MODEL',
                           '/workspace/chroma_duplex_demo/models/qwen3_tts_1.7b_customvoice')
ASR_PATH = os.environ.get('AIDEN_ASR_MODEL',
                          '/workspace/speech_comparison/models/asr_evaluation/'
                          'models--mobiuslabsgmbh--faster-whisper-large-v3-turbo/'
                          'snapshots/0a363e9161cbc7ed1431c9597a8ceaf0c4f78fcf')
MIMI_CKPT = os.environ.get('AIDEN_MIMI',
                          '/workspace/speech_comparison/models/personaplex/'
                          'tokenizer-e351c8d8-checkpoint125.safetensors')
MOSHI_SRC = os.environ.get('AIDEN_MOSHI_SRC',
                          '/workspace/speech_comparison/src/personaplex')
SR = 24000
FRAME_RATE = 12.5
MIMI_CHUNK = 1920 * 10
INSTRUCT = ('Lively, warm, conversational American English. Natural pacing, '
            'a slight smile in the voice, clear articulation.')


def wav_bytes(w, sr):
    buf = io.BytesIO()
    sf.write(buf, np.asarray(w, dtype=np.float32).reshape(-1), sr,
             format='WAV', subtype='PCM_16')
    return buf.getvalue()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('lane', choices=('tts', 'input'))
    args = parser.parse_args()
    t0 = time.time()
    if args.lane == 'tts':
        from qwen_tts import Qwen3TTSModel
        tts = Qwen3TTSModel.from_pretrained(TTS_MODEL, device_map='cuda:0',
                                            dtype=torch.bfloat16,
                                            attn_implementation='sdpa', local_files_only=True)
    else:
        from faster_whisper import WhisperModel
        asr = WhisperModel(ASR_PATH, device='cuda', compute_type='float16')
        sys.path.insert(0, MOSHI_SRC)
        from moshi.models.loaders import get_mimi
        mimi = get_mimi(Path(MIMI_CKPT), device='cuda')
        mimi.set_num_codebooks(8)
        mimi.eval()

    def synthesize(text):
        return tts.generate_custom_voice(text=text, language='English', speaker='Aiden',
                                         instruct=INSTRUCT, max_new_tokens=256,
                                         do_sample=False)

    def synth_batch(texts):
        n = len(texts)
        return tts.generate_custom_voice(text=list(texts), language='English',
                                         speaker=['Aiden'] * n,
                                         instruct=[INSTRUCT] * n,
                                         max_new_tokens=256, do_sample=False)

    @torch.no_grad()
    def prosody(x16):
        """Causal Mimi latents for a finished utterance -> (frames, n)."""
        import librosa
        x24 = librosa.resample(x16, orig_sr=16000, target_sr=SR, res_type='soxr_hq')
        x24 = np.ascontiguousarray(x24, dtype=np.float32)
        try:
            mimi.reset_streaming()
        except ValueError:
            pass
        mimi.streaming_forever(1)
        outs = []
        for i in range(0, len(x24), MIMI_CHUNK):
            c = x24[i:i + MIMI_CHUNK]
            if len(c) < MIMI_CHUNK:
                c = np.pad(c, (0, MIMI_CHUNK - len(c)))
            outs.append(mimi.encode_to_latent(
                torch.from_numpy(np.ascontiguousarray(c))[None, None].cuda(),
                quantize=False)[0].float().cpu())
        try:
            mimi.reset_streaming()
        except ValueError:
            pass
        lat = torch.cat(outs, dim=-1)
        keep = int(len(x16) // 1280)  # only complete 80 ms frames
        return lat[:, :keep].numpy()

    if args.lane == 'tts':
        synthesize('Hello.')
    else:
        silence = np.zeros(8000, dtype=np.float32)
        list(asr.transcribe(silence, beam_size=1, language='en', word_timestamps=True)[0])
        prosody(silence)
    print(json.dumps({'ready': True, 'lane': args.lane,
                      'warm_s': round(time.time() - t0, 2)}), flush=True)

    def vector(lat):
        return base64.b64encode(lat.mean(axis=1).astype(np.float16).tobytes()).decode()

    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
        except ValueError:
            continue
        op, rid = req.get('op'), req.get('id')
        t0 = time.time()
        try:
            if args.lane == 'tts' and op == 'tts':
                texts = req.get('texts')
                if texts is None:
                    texts = [req.get('text') or '']
                texts = [t.strip() for t in texts if t and t.strip()]
                if not texts:
                    print(json.dumps({'id': rid, 'error': 'empty'}), flush=True)
                    continue
                # One batched call: the model is slow per sentence (~1x real time),
                # so batching is what lets audio arrive ahead of playback.
                try:
                    if len(texts) == 1:
                        # single-clause path is ~2x faster than the list API
                        wavs, sr = synthesize(texts[0])
                    else:
                        wavs, sr = synth_batch(texts)
                except Exception:
                    wavs, sr = [synthesize(t)[0][0] for t in texts], SR
                audios = []
                for w in wavs:
                    w = np.asarray(w, dtype=np.float32).reshape(-1)
                    if sr != SR:
                        import torchaudio
                        w = torchaudio.functional.resample(
                            torch.from_numpy(w), sr, SR).numpy()
                    audios.append({'dur': round(len(w) / SR, 3),
                                   'audio_b64': base64.b64encode(wav_bytes(w, SR)).decode()})
                out = {'id': rid, 'sr': SR, 'audios': audios,
                       'ms': round((time.time() - t0) * 1000, 1)}
                if len(audios) == 1:
                    out.update(audio_b64=audios[0]['audio_b64'], dur=audios[0]['dur'])
                print(json.dumps(out), flush=True)
            elif args.lane == 'input' and op in ('asr', 'onset', 'partial'):
                raw = base64.b64decode(req.get('wav_b64') or '')
                w, sr = sf.read(io.BytesIO(raw), dtype='float32', always_2d=True)
                mono = w.mean(axis=1) if w.shape[1] > 1 else w[:, 0]
                if sr != 16000:
                    import librosa
                    mono = librosa.resample(mono, orig_sr=sr, target_sr=16000)
                mono = np.ascontiguousarray(mono, dtype=np.float32)
                if op == 'onset':
                    lat = prosody(mono)
                    print(json.dumps({'id': rid, 'vec': vector(lat) if lat.shape[1] else None}),
                          flush=True)
                    continue
                segs, _ = asr.transcribe(mono, beam_size=1, language='en',
                                          vad_filter=False,
                                          condition_on_previous_text=False,
                                          word_timestamps=op == 'asr')
                if op == 'partial':
                    text = ' '.join(s.text.strip() for s in segs if s.no_speech_prob < .6)
                    print(json.dumps({'id': rid, 'text': text,
                                      'ms': round((time.time() - t0) * 1000, 1)}), flush=True)
                    continue
                words, pieces = [], []
                for s in segs:
                    for wd in s.words or []:
                        txt = (wd.word or '').strip()
                        if txt:
                            pieces.append(txt)
                            words.append({'w': txt, 't0': float(wd.start),
                                          't1': float(wd.end)})
                text = ' '.join(pieces)
                if words:
                    lat = prosody(mono)
                    nf = lat.shape[1]
                    for wd in words:
                        f0 = max(0, int((wd['t0'] - 0.08) * FRAME_RATE))
                        f1 = min(nf, int((wd['t1'] + 0.16) * FRAME_RATE))
                        if f1 > f0:
                            wd['vec_b64'] = vector(lat[:, f0:f1])
                print(json.dumps({'id': rid, 'text': text, 'words': words,
                                  'ms': round((time.time() - t0) * 1000, 1)}), flush=True)
            elif op == 'ping':
                print(json.dumps({'pong': True}), flush=True)
            else:
                print(json.dumps({'id': rid, 'error': f'unknown op {op}'}), flush=True)
        except Exception as exc:
            print(json.dumps({'id': rid, 'error': repr(exc)[:400]}), flush=True)


if __name__ == '__main__':
    main()