File size: 7,509 Bytes
29439fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""WebSocket bidirectional-streaming TTS server for TTS-V4.

    python stream_server.py --model-dir /path/to/TTS-V4 --port 8765

Protocol (ws://host:port/v1/tts/stream):
  client -> {"type":"start","voice":"bank_collection_female","sample_rate":8000|16000|24000,
             "mode":"icl"|"xvec","segment":"sentence"|"token","speed":1.0,"temperature":0.8,"seed":0}
            (or "ref_audio_b64" + "ref_text" instead of "voice" for a custom real reference)
  client -> {"type":"text","text":"..."}   (any number, any granularity, e.g. LLM tokens)
  client -> {"type":"end"}                 (no more text)   | {"type":"cancel"} (barge-in)
  server -> {"type":"started","sample_rate":..,"format":"pcm_s16le","channels":1}
  server -> binary audio chunks (PCM 16-bit little endian mono)
  server -> {"type":"done","stats":{...}}  | {"type":"error","message":...}
"""
import argparse
import asyncio
import base64
import json
import os
import tempfile
import threading
import time

import numpy as np
import soxr
import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

from stream_engine import StreamingTTS

app = FastAPI()
ENGINE = None
ARGS = None


@app.get('/health')
def health():
    return dict(status='ok' if ENGINE else 'loading', voices=sorted(ENGINE.voice_info) if ENGINE else [],
                sample_rate=ENGINE.sample_rate if ENGINE else None)


def pcm16(x):
    return (np.clip(x, -1, 1) * 32767).astype('<i2').tobytes()


@app.websocket('/v1/tts/stream')
async def stream(ws: WebSocket):
    await ws.accept()
    loop = asyncio.get_running_loop()
    session, temp = None, None
    try:
        start = json.loads(await ws.receive_text())
        if start.get('type') != 'start':
            raise ValueError('first message must be {"type":"start",...}')
        sr = int(start.get('sample_rate', ENGINE.sample_rate))
        if sr not in (8000, 16000, 24000):
            raise ValueError('sample_rate must be 8000, 16000 or 24000')
        mode = start.get('mode', 'icl')
        if mode not in ('icl', 'xvec'):
            raise ValueError('mode must be icl or xvec')
        t = float(start.get('temperature', ARGS.temperature))
        segment = start.get('segment', 'sentence' if mode == 'icl' else 'token')
        speed = float(start.get('speed', 1.0))
        if not 0.5 <= speed <= 2.0:
            raise ValueError('speed must be within [0.5, 2.0]')
        kwargs = dict(seed=start.get('seed'), mode=mode, segment=segment, speed=speed,
                      sampling=dict(temperature=t, subtalker_temperature=t))
        if 'ref_audio_b64' in start:
            temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
            temp.write(base64.b64decode(start['ref_audio_b64']))
            temp.close()
            session = ENGINE.session(ref_audio=temp.name, ref_text=start['ref_text'], **kwargs)
        else:
            voice = start.get('voice')
            if voice not in ENGINE.voice_info:
                raise ValueError(f'unknown voice {voice!r}; available {sorted(ENGINE.voice_info)}')
            session = ENGINE.session(voice, **kwargs)
        resampler = soxr.ResampleStream(ENGINE.sample_rate, sr, 1, dtype='float32') if sr != ENGINE.sample_rate else None
        await ws.send_text(json.dumps(dict(type='started', sample_rate=sr, format='pcm_s16le', channels=1)))
        audio_q = asyncio.Queue()

        def pump():
            try:
                for chunk in session.audio():
                    if resampler is not None:
                        chunk = resampler.resample_chunk(chunk)
                    if len(chunk):
                        loop.call_soon_threadsafe(audio_q.put_nowait, pcm16(chunk))
                if resampler is not None:
                    tail = resampler.resample_chunk(np.zeros(0, np.float32), last=True)
                    if len(tail):
                        loop.call_soon_threadsafe(audio_q.put_nowait, pcm16(tail))
                loop.call_soon_threadsafe(audio_q.put_nowait, None)
            except Exception as error:
                loop.call_soon_threadsafe(audio_q.put_nowait, error)

        threading.Thread(target=pump, daemon=True).start()

        async def sender():
            while True:
                item = await audio_q.get()
                if item is None:
                    return
                if isinstance(item, Exception):
                    raise item
                await ws.send_bytes(item)

        send_task = asyncio.create_task(sender())

        async def receiver():
            while True:
                msg = json.loads(await ws.receive_text())
                kind = msg.get('type')
                if kind == 'text':
                    await asyncio.to_thread(session.push_text, msg.get('text', ''))
                elif kind == 'end':
                    await asyncio.to_thread(session.end)
                    return
                elif kind == 'cancel':
                    session.cancel()
                    return
        recv_task = asyncio.create_task(receiver())
        done, _ = await asyncio.wait({send_task, recv_task}, return_when=asyncio.FIRST_EXCEPTION)
        for task in done:
            if task.exception():
                raise task.exception()
        await send_task
        st = session.stats
        t0 = st.t_first_text
        await ws.send_text(json.dumps(dict(type='done', stats=dict(
            mode=mode, segment=segment, speed=speed, start_tokens=st.extra.get('start_tokens'), sentences=st.extra.get('sentences'),
            first_audio_ms=None if st.t_first_audio is None or t0 is None else round(1000 * (st.t_first_audio - t0), 1),
            prefill_ms=None if st.t_prefill is None or t0 is None else round(1000 * (st.t_prefill - t0), 1),
            frames=st.frames, audio_s=round(st.audio_s, 3), eos=st.eos, cancelled=st.cancelled,
            waits_for_text=st.waits_for_text,
            rtf=None if not st.audio_s or st.t_done is None or st.t_prefill is None else round((st.t_done - st.t_prefill) / st.audio_s, 3)))))
    except WebSocketDisconnect:
        if session:
            session.cancel()
    except Exception as error:
        if session:
            session.cancel()
        try:
            await ws.send_text(json.dumps(dict(type='error', message=repr(error))))
        except Exception:
            pass
    finally:
        if temp is not None:
            os.unlink(temp.name)
        try:
            await ws.close()
        except Exception:
            pass


def main():
    global ENGINE, ARGS
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--model-dir', default=os.path.dirname(os.path.abspath(__file__)))
    ap.add_argument('--adapter', help='development only: V4 adapter on a base checkpoint')
    ap.add_argument('--voices-json')
    ap.add_argument('--host', default='0.0.0.0')
    ap.add_argument('--port', type=int, default=8765)
    ap.add_argument('--device', default='cuda:0')
    ap.add_argument('--temperature', type=float, default=0.8)
    ARGS = ap.parse_args()
    ENGINE = StreamingTTS(ARGS.model_dir, adapter=ARGS.adapter, device=ARGS.device, voices_json=ARGS.voices_json)
    for name in ENGINE.voice_info:  # warm reference prompts
        ENGINE.voice(name)
    s = ENGINE.session(next(iter(ENGINE.voice_info)), seed=0)
    s.push_text('您好。'); s.end(); list(s.audio())
    uvicorn.run(app, host=ARGS.host, port=ARGS.port, log_level='warning')


if __name__ == '__main__':
    main()