LoveLogicAI commited on
Commit
272bea9
·
verified ·
1 Parent(s): 638265c

Cache consent disclosure at warmup; first audio pays zero Piper synth

Browse files
Files changed (1) hide show
  1. freestream/bot.py +24 -25
freestream/bot.py CHANGED
@@ -60,6 +60,7 @@ class BotSession:
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):
@@ -114,10 +115,11 @@ class BotSession:
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
- """Pipelined sentence synthesis (docs/LATENCY.md #2): sentence 1 is
119
- synthesized and starts playing while the remaining sentences are
120
- synthesized in a background task — no gaps between sentences."""
 
121
  import re
122
 
123
  sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
@@ -128,23 +130,18 @@ class BotSession:
128
  total_audio = 0.0
129
  total_chars = 0
130
 
131
- pcm, sr = await asyncio.to_thread(self.voice_backend.synthesize, sentences[0])
132
- t_first_synth = time.perf_counter()
133
- emit({"event": "timing", "session_id": self.session_id,
134
- "sentence": 1, "synth_s": round(t_first_synth - t0, 3),
135
- "chars": len(sentences[0])})
136
  rest_q: asyncio.Queue = asyncio.Queue()
137
 
138
  async def synth_rest():
139
- for i, s in enumerate(sentences[1:], start=2):
140
  p, r = await asyncio.to_thread(self.voice_backend.synthesize, s)
141
- await rest_q.put((p, r, i, len(s)))
142
  await rest_q.put(None)
143
 
144
  rest_task = asyncio.create_task(synth_rest()) # synthesizes while we play
145
 
146
- async def play_one(pcm_i, sr_i, idx, chars):
147
- nonlocal total_audio, total_chars
148
  mouth = avatar_mod.build_mouth_sequence(pcm_i, sr_i)
149
  duration = len(pcm_i) / sr_i
150
  total_audio += duration
@@ -160,28 +157,24 @@ class BotSession:
160
  task = asyncio.create_task(mouth_driver())
161
  if first_audio is None:
162
  await asyncio.sleep(PRE_ROLL_S) # avatar starts moving first
163
- first_audio_local = time.perf_counter()
164
- else:
165
- first_audio_local = None
166
  await self.push_audio(pcm_i, sr_i)
167
  await task
168
- return first_audio_local
169
 
170
- first_audio = await play_one(pcm, sr, 1, len(sentences[0]))
 
171
  while True:
172
  item = await rest_q.get()
173
  if item is None:
174
  break
175
- p, r, i, chars = item
176
- fa = await play_one(p, r, i, chars)
177
- if first_audio is None:
178
- first_audio = fa
179
  await rest_task
180
  if first_audio is None:
181
  raise RuntimeError("synthesis produced no audio")
182
  self.log.append("tts.synthesized", text=text, chars=total_chars,
183
  backend="piper", seconds=round(first_audio - t0, 3),
184
- sentences=len(sentences))
185
  emit({"event": "timing", "session_id": self.session_id,
186
  "tts_first_s": round(first_audio - t0, 3),
187
  "spoken_chars": total_chars, "audio_s": round(total_audio, 3)})
@@ -209,13 +202,14 @@ class BotSession:
209
  self.log.append("asr.final", text=text, seconds=round(asr_s, 3),
210
  audio_s=round(len(utt) / 16000, 2))
211
  reply = self.agent.reply(text)
 
212
  if not self.first_utterance_done:
213
- reply = self.agent.first_utterance() + " " + reply
214
  self.first_utterance_done = True
215
  self.log.append("agent.speak", text=reply)
216
  self.set_state("speaking")
217
  try:
218
- await self.speak(reply, t0=t_speech_end)
219
  except Exception as e: # noqa: BLE001 — surface as session error, keep bot alive
220
  import traceback
221
  self.log.append("session.error", error=str(e)[:200],
@@ -242,6 +236,11 @@ class BotSession:
242
  try:
243
  await asyncio.to_thread(self.transcriber._load)
244
  await asyncio.to_thread(self.voice_backend.synthesize, "Warmup.")
 
 
 
 
 
245
  except Exception as e: # noqa: BLE001
246
  self.log.append("session.error", error=f"warmup failed: {e}")
247
  self.set_state("error", error=str(e)[:200])
 
60
  self.transcriber = Transcriber()
61
  self.segmenter = Segmenter()
62
  self.first_utterance_done = False
63
+ self.disclosure_segment = None # (pcm, sr) consent line, cached at warmup
64
 
65
  # -- state ---------------------------------------------------------------
66
  def set_state(self, s: str, **extra):
 
115
  np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
116
  await self.audio_source.capture_frame(frame)
117
 
118
+ async def speak(self, text: str, pre_segment=None, **timing):
119
+ """Pipelined sentence synthesis (docs/LATENCY.md #2): playback starts
120
+ while later sentences are still synthesizing. pre_segment is an
121
+ optional (pcm, sr) already synthesized at session start — the fixed
122
+ consent disclosure — so the first audible output pays no synth cost."""
123
  import re
124
 
125
  sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
 
130
  total_audio = 0.0
131
  total_chars = 0
132
 
 
 
 
 
 
133
  rest_q: asyncio.Queue = asyncio.Queue()
134
 
135
  async def synth_rest():
136
+ for s in sentences:
137
  p, r = await asyncio.to_thread(self.voice_backend.synthesize, s)
138
+ await rest_q.put((p, r, len(s)))
139
  await rest_q.put(None)
140
 
141
  rest_task = asyncio.create_task(synth_rest()) # synthesizes while we play
142
 
143
+ async def play_one(pcm_i, sr_i, chars):
144
+ nonlocal total_audio, total_chars, first_audio
145
  mouth = avatar_mod.build_mouth_sequence(pcm_i, sr_i)
146
  duration = len(pcm_i) / sr_i
147
  total_audio += duration
 
157
  task = asyncio.create_task(mouth_driver())
158
  if first_audio is None:
159
  await asyncio.sleep(PRE_ROLL_S) # avatar starts moving first
160
+ first_audio = time.perf_counter()
 
 
161
  await self.push_audio(pcm_i, sr_i)
162
  await task
 
163
 
164
+ if pre_segment is not None:
165
+ await play_one(pre_segment[0], pre_segment[1], 0)
166
  while True:
167
  item = await rest_q.get()
168
  if item is None:
169
  break
170
+ p, r, chars = item
171
+ await play_one(p, r, chars)
 
 
172
  await rest_task
173
  if first_audio is None:
174
  raise RuntimeError("synthesis produced no audio")
175
  self.log.append("tts.synthesized", text=text, chars=total_chars,
176
  backend="piper", seconds=round(first_audio - t0, 3),
177
+ sentences=len(sentences), pre_cached=pre_segment is not None)
178
  emit({"event": "timing", "session_id": self.session_id,
179
  "tts_first_s": round(first_audio - t0, 3),
180
  "spoken_chars": total_chars, "audio_s": round(total_audio, 3)})
 
202
  self.log.append("asr.final", text=text, seconds=round(asr_s, 3),
203
  audio_s=round(len(utt) / 16000, 2))
204
  reply = self.agent.reply(text)
205
+ pre = None
206
  if not self.first_utterance_done:
207
+ pre = self.disclosure_segment # cached consent line, zero synth cost
208
  self.first_utterance_done = True
209
  self.log.append("agent.speak", text=reply)
210
  self.set_state("speaking")
211
  try:
212
+ await self.speak(reply, pre_segment=pre, t0=t_speech_end)
213
  except Exception as e: # noqa: BLE001 — surface as session error, keep bot alive
214
  import traceback
215
  self.log.append("session.error", error=str(e)[:200],
 
236
  try:
237
  await asyncio.to_thread(self.transcriber._load)
238
  await asyncio.to_thread(self.voice_backend.synthesize, "Warmup.")
239
+ # Pre-synthesize the fixed consent disclosure (CONSENT.md #2): it is
240
+ # static text, so the first turn's first audio never pays Piper's
241
+ # in-context synth latency (measured RTF ~1.2 in-process).
242
+ self.disclosure_segment = await asyncio.to_thread(
243
+ self.voice_backend.synthesize, self.agent.first_utterance())
244
  except Exception as e: # noqa: BLE001
245
  self.log.append("session.error", error=f"warmup failed: {e}")
246
  self.set_state("error", error=str(e)[:200])