LoveLogicAI commited on
Commit
3d12bc4
·
verified ·
1 Parent(s): 5168344

MVP: bot session process (LiveKit, VAD-whisper, Piper, avatar)

Browse files
Files changed (1) hide show
  1. freestream/bot.py +253 -0
freestream/bot.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FREESTREAM bot — the MVP LiveKit session process (run with -m freestream.bot).
2
+
3
+ One bot = one LiveKit session:
4
+ join room -> publish mic (Piper audio) + camera (animated face) tracks
5
+ -> subscribe remote audio -> energy-VAD -> faster-whisper -> agent reply
6
+ -> Piper synthesis -> audio push with 150ms avatar pre-roll.
7
+
8
+ Status protocol: JSON lines on stdout ("status"/"timing" events) plus
9
+ state.json in the session dir (what the CLI polls). SIGTERM closes the
10
+ session gracefully.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import os
19
+ import signal
20
+ import sys
21
+ import time
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
27
+
28
+ from freestream import avatar as avatar_mod
29
+ from freestream.agent import load_agent
30
+ from freestream.asr import Segmenter, Transcriber
31
+ from freestream.events import EventLog
32
+ from freestream.persona import VoiceBackend
33
+
34
+ AVATAR_FPS = avatar_mod.FPS
35
+ PRE_ROLL_S = 0.15
36
+ IDLE_FPS = 2 # static face refresh when not speaking
37
+
38
+
39
+ def emit(obj: dict):
40
+ print(json.dumps(obj), flush=True)
41
+
42
+
43
+ class BotSession:
44
+ def __init__(self, url: str, token: str, room_name: str, bot_name: str,
45
+ image: Path, voice: str, session_dir: Path, session_id: str,
46
+ system_prompt: str | None):
47
+ self.url, self.token, self.room_name = url, token, room_name
48
+ self.bot_name = bot_name
49
+ self.image = image
50
+ self.voice_backend = VoiceBackend(voice)
51
+ self.session_dir = Path(session_dir)
52
+ self.session_dir.mkdir(parents=True, exist_ok=True)
53
+ self.session_id = session_id
54
+ self.state = "connecting"
55
+ self.log = EventLog(self.session_dir / "bot-events.jsonl") # separate chain from the CLI log
56
+ self.agent = load_agent(system_prompt, bot_name)
57
+ self.renderer = avatar_mod.AvatarRenderer(image if image.exists() else None)
58
+ self.mouth = 0.0 # current openness, driven by the speak loop
59
+ self.speaking_until = 0.0
60
+ self.transcriber = Transcriber()
61
+ self.segmenter = Segmenter()
62
+ self.first_utterance_done = False
63
+
64
+ # -- state ---------------------------------------------------------------
65
+ def set_state(self, s: str, **extra):
66
+ self.state = s
67
+ payload = {"session_id": self.session_id, "status": s, **extra}
68
+ (self.session_dir / "state.json").write_text(json.dumps(payload))
69
+ self.log.append("session.status", status=s)
70
+ emit({"event": "status", **payload})
71
+
72
+ # -- tracks ---------------------------------------------------------------
73
+ async def publish_tracks(self, room):
74
+ import livekit.rtc as rtc
75
+
76
+ # camera
77
+ self.video_source = rtc.VideoSource(avatar_mod.SIZE, avatar_mod.SIZE)
78
+ vtrack = rtc.LocalVideoTrack.create_video_track("freestream-face", self.video_source)
79
+ vopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_CAMERA)
80
+ vopts.video_encoding = rtc.VideoEncoding(max_framerate=float(AVATAR_FPS),
81
+ max_bitrate=800_000)
82
+ await room.local_participant.publish_track(vtrack, vopts)
83
+
84
+ # microphone
85
+ self.audio_source = rtc.AudioSource(22050, 1)
86
+ atrack = rtc.LocalAudioTrack.create_audio_track("freestream-voice", self.audio_source)
87
+ aopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
88
+ await room.local_participant.publish_track(atrack, aopts)
89
+
90
+ async def video_loop(self):
91
+ """Render the face continuously; mouth openness follows speech energy."""
92
+ import livekit.rtc as rtc
93
+
94
+ frame_us = int(1e6 / (AVATAR_FPS if self.mouth > 0 else IDLE_FPS))
95
+ last = time.perf_counter()
96
+ while True:
97
+ img = self.renderer.frame(self.mouth)
98
+ rgba = np.ascontiguousarray(np.asarray(img))
99
+ vf = rtc.VideoFrame(avatar_mod.SIZE, avatar_mod.SIZE,
100
+ rtc.VideoBufferType.RGBA, rgba.tobytes())
101
+ self.video_source.capture_frame(vf, timestamp_us=int(time.time() * 1e6))
102
+ now = time.perf_counter()
103
+ fps = AVATAR_FPS if time.perf_counter() < self.speaking_until or self.mouth > 0 else IDLE_FPS
104
+ await asyncio.sleep(max(0.0, 1.0 / fps - (now - last)))
105
+ last = time.perf_counter()
106
+
107
+ async def push_audio(self, pcm: np.ndarray, sr: int):
108
+ import livekit.rtc as rtc
109
+
110
+ chunk = int(sr * 0.01) # 10ms
111
+ for i in range(0, len(pcm), chunk):
112
+ piece = pcm[i : i + chunk]
113
+ frame = rtc.AudioFrame.create(sr, 1, len(piece))
114
+ np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
115
+ await self.audio_source.capture_frame(frame)
116
+
117
+ async def speak(self, text: str, **timing):
118
+ """Synthesize -> mouth sequence -> pre-roll -> audio push."""
119
+ import livekit.rtc as rtc
120
+
121
+ pcm, sr = await asyncio.to_thread(self.voice_backend.synthesize, text)
122
+ t_tts_done = time.perf_counter()
123
+ mouth = avatar_mod.build_mouth_sequence(pcm, sr, pre_roll_frames=3)
124
+ duration = len(pcm) / sr
125
+
126
+ # drive the render loop with the mouth sequence
127
+ t0 = time.perf_counter()
128
+ self.speaking_until = t0 + duration + PRE_ROLL_S + 0.3
129
+
130
+ async def mouth_driver():
131
+ i = 0
132
+ n = len(mouth)
133
+ while i < n:
134
+ self.mouth = float(mouth[i])
135
+ i += 1
136
+ await asyncio.sleep(1.0 / AVATAR_FPS)
137
+ self.mouth = 0.0
138
+
139
+ task = asyncio.create_task(mouth_driver())
140
+ await asyncio.sleep(PRE_ROLL_S) # avatar starts moving first
141
+ t_first_audio = time.perf_counter()
142
+ await self.push_audio(pcm, sr)
143
+ await task
144
+ self.log.append("tts.synthesized", text=text, chars=len(text),
145
+ backend="piper", seconds=round(t_tts_done - timing["t0"], 3))
146
+ emit({"event": "timing", "session_id": self.session_id,
147
+ "tts_s": round(t_tts_done - timing["t0"], 3),
148
+ "first_audio_after_speech_end_s": round(t_first_audio - timing["t0"], 3),
149
+ "spoken_chars": len(text), "audio_s": round(duration, 3)})
150
+
151
+ # -- receive loop ----------------------------------------------------------
152
+ async def on_track(self, room, track, publication, participant):
153
+ import livekit.rtc as rtc
154
+
155
+ if track.kind != rtc.TrackKind.KIND_AUDIO:
156
+ return
157
+ stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
158
+ async for ev in stream:
159
+ pcm = np.frombuffer(ev.frame.data, dtype=np.int16).astype(np.float32) / 32768.0
160
+ for utt in self.segmenter.feed(pcm):
161
+ await self.handle_utterance(utt)
162
+
163
+ async def handle_utterance(self, utt: np.ndarray):
164
+ t_speech_end = time.perf_counter()
165
+ self.set_state("thinking")
166
+ text, asr_s = await asyncio.to_thread(self.transcriber.transcribe, utt)
167
+ t_asr = time.perf_counter()
168
+ if not text:
169
+ self.set_state("listening")
170
+ return
171
+ self.log.append("asr.final", text=text, seconds=round(asr_s, 3),
172
+ audio_s=round(len(utt) / 16000, 2))
173
+ reply = self.agent.reply(text)
174
+ if not self.first_utterance_done:
175
+ reply = self.agent.first_utterance() + " " + reply
176
+ self.first_utterance_done = True
177
+ self.log.append("agent.speak", text=reply)
178
+ self.set_state("speaking")
179
+ try:
180
+ await self.speak(reply, t0=t_speech_end)
181
+ except Exception as e: # noqa: BLE001 — surface as session error, keep bot alive
182
+ self.log.append("session.error", error=str(e)[:200])
183
+ self.set_state("listening")
184
+ return
185
+ total = time.perf_counter() - t_speech_end
186
+ self.log.append("turn.completed", total_s=round(total, 3),
187
+ asr_s=round(t_asr - t_speech_end, 3))
188
+ self.set_state("listening")
189
+
190
+ # -- lifecycle ---------------------------------------------------------------
191
+ async def run(self):
192
+ import livekit.rtc as rtc
193
+
194
+ room = rtc.Room()
195
+ self.set_state("connecting")
196
+ await room.connect(self.url, self.token,
197
+ options=rtc.RoomOptions(auto_subscribe=True))
198
+ t_connected = time.perf_counter()
199
+ await self.publish_tracks(room)
200
+ # Warm identity assets before reporting ready, so the first turn
201
+ # doesn't pay whisper/piper model-load cost (docs/LATENCY.md #4).
202
+ try:
203
+ await asyncio.to_thread(self.transcriber._load)
204
+ await asyncio.to_thread(self.voice_backend.synthesize, "Warmup.")
205
+ except Exception as e: # noqa: BLE001
206
+ self.log.append("session.error", error=f"warmup failed: {e}")
207
+ self.set_state("error", error=str(e)[:200])
208
+ return
209
+ self.set_state("ready", video_published=True, room=self.room_name)
210
+
211
+ @room.on("track_subscribed")
212
+ def _on_track(track, publication, participant):
213
+ asyncio.ensure_future(self.on_track(room, track, publication, participant))
214
+
215
+ video_task = asyncio.create_task(self.video_loop())
216
+
217
+ stop = asyncio.Event()
218
+ loop = asyncio.get_event_loop()
219
+ for sig in (signal.SIGTERM, signal.SIGINT):
220
+ loop.add_signal_handler(sig, stop.set)
221
+
222
+ emit({"event": "timing", "session_id": self.session_id,
223
+ "join_s": round(time.perf_counter() - t_connected, 3)})
224
+ await stop.wait()
225
+ self.set_state("closed")
226
+ await room.disconnect()
227
+ video_task.cancel()
228
+
229
+
230
+ def main():
231
+ p = argparse.ArgumentParser(prog="freestream-bot")
232
+ p.add_argument("--url", required=True)
233
+ p.add_argument("--token", required=True)
234
+ p.add_argument("--room", required=True)
235
+ p.add_argument("--bot-name", required=True)
236
+ p.add_argument("--image", required=True)
237
+ p.add_argument("--voice", required=True)
238
+ p.add_argument("--session-id", required=True)
239
+ p.add_argument("--session-dir", required=True)
240
+ p.add_argument("--system-prompt", default=None)
241
+ args = p.parse_args()
242
+
243
+ session = BotSession(args.url, args.token, args.room, args.bot_name,
244
+ Path(args.image), args.voice, Path(args.session_dir),
245
+ args.session_id, args.system_prompt)
246
+ try:
247
+ asyncio.run(session.run())
248
+ except KeyboardInterrupt:
249
+ pass
250
+
251
+
252
+ if __name__ == "__main__":
253
+ main()