J Z commited on
Commit
c1a26d2
·
verified ·
1 Parent(s): b133bc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -66
app.py CHANGED
@@ -1,14 +1,17 @@
1
  """
2
  Avatar Chatbot - HuggingFace Spaces Edition
3
- Single response per message: LLM → TTS → FLOAT lipsync → play
4
  """
5
  from fastapi import FastAPI, HTTPException, Request
6
  from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
7
  from pathlib import Path
8
  import mimetypes
9
  import os
 
10
  import logging
11
  import subprocess
 
 
12
 
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
@@ -24,6 +27,10 @@ FLOAT_ENABLED = os.environ.get("FLOAT_ENABLED", "true").lower() == "true"
24
  for d in [VIDEOS_DIR, TTS_DIR, LIPSYNC_DIR]:
25
  d.mkdir(parents=True, exist_ok=True)
26
 
 
 
 
 
27
 
28
  @app.on_event("startup")
29
  async def startup():
@@ -146,18 +153,28 @@ async def stream_audio(filename: str):
146
  headers={"Content-Length": str(path.stat().st_size)})
147
 
148
 
 
 
 
 
 
 
149
  @app.post("/api/chat")
150
  async def chat(request: Request):
151
- import time as _time
 
 
 
 
 
152
  t0 = _time.time()
153
-
154
  body = await request.json()
155
  user_text = body.get("text", "").strip()
156
  if not user_text: raise HTTPException(400, "No text")
157
 
158
  logger.info(f"[CHAT] User: {user_text}")
159
 
160
- # 1. LLM
161
  t1 = _time.time()
162
  from llm import generate_darwin_response
163
  llm_result = generate_darwin_response(user_text)
@@ -166,11 +183,64 @@ async def chat(request: Request):
166
  logger.info(f"[CHAT] Darwin: {reply_text}")
167
  logger.info(f"[TIMING] LLM: {t2-t1:.2f}s")
168
 
169
- # 2. TTS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  from tts import generate_audio
171
- audio_path = generate_audio(reply_text)
172
- t3 = _time.time()
173
- logger.info(f"[TIMING] TTS: {t3-t2:.2f}s")
 
174
 
175
  audio_url = None
176
  audio_duration = 0
@@ -178,36 +248,44 @@ async def chat(request: Request):
178
  audio_url = f"/api/audio/{os.path.basename(audio_path)}"
179
  try:
180
  r = subprocess.run(["ffprobe","-v","quiet","-show_entries","format=duration",
181
- "-of","csv=p=0",audio_path], capture_output=True, text=True, check=True)
182
  audio_duration = float(r.stdout.strip())
183
  except Exception:
184
  audio_duration = 3.0
185
 
186
- # 3. Lipsync
187
  lipsync_video_url = None
188
  if FLOAT_ENABLED and audio_path and os.path.exists(audio_path):
189
  try:
190
  from float_lipsync import get_lipsync
191
  lipsync = get_lipsync()
192
  if lipsync.ready:
193
- logger.info("[CHAT] Running FLOAT lipsync...")
194
- t4 = _time.time()
195
  lp = lipsync.generate(audio_path)
196
- t5 = _time.time()
197
- logger.info(f"[TIMING] FLOAT total: {t5-t4:.2f}s")
198
  if lp and os.path.exists(lp):
199
  lipsync_video_url = f"/api/stream/{os.path.basename(lp)}"
200
- else:
201
- logger.info("[CHAT] FLOAT not ready")
202
  except Exception as e:
203
- logger.error(f"[CHAT] Lipsync failed: {e}", exc_info=True)
 
 
 
204
 
205
- t_end = _time.time()
206
- logger.info(f"[TIMING] TOTAL request: {t_end-t0:.2f}s")
 
 
 
 
 
207
 
208
  return JSONResponse({
209
- "text": reply_text,
210
- "emotion": llm_result.get('emotion','neutral'),
 
 
 
211
  "audio_url": audio_url,
212
  "audio_duration": audio_duration,
213
  "lipsync_video_url": lipsync_video_url,
@@ -285,33 +363,30 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;backgrou
285
  </div>
286
  </div>
287
  <script>
 
 
 
288
  let videos=[], currentVideo='A', isTransitioning=false, isProcessing=false, lastPlayed=null, msgCounter=0;
289
  const videoA=document.getElementById('videoA'), videoB=document.getElementById('videoB');
290
  const videoStatus=document.getElementById('videoStatus'), chatLog=document.getElementById('chatLog');
291
  const chatInput=document.getElementById('chatInput'), btnSend=document.getElementById('btnSend');
292
  const btnReset=document.getElementById('btnReset');
293
 
 
 
 
294
  function getActiveVideo(){return currentVideo==='A'?videoA:videoB}
295
  function getInactiveVideo(){return currentVideo==='A'?videoB:videoA}
296
 
297
  function crossfadeTo(url, muted){
298
- if(isTransitioning) return;
299
- isTransitioning=true;
300
- const prev=getActiveVideo(), next=getInactiveVideo();
301
- next.muted=(muted!==false);
302
- next.src=url; next.load();
303
- next.onloadeddata=function(){
304
- next.style.zIndex='2'; prev.style.zIndex='1'; next.style.opacity='0';
305
- next.play().then(()=>{
306
- next.style.opacity='1';
307
- setTimeout(()=>{
308
- prev.style.opacity='0'; prev.pause(); prev.src='';
309
- prev.style.zIndex='0'; next.style.zIndex='1';
310
- currentVideo=currentVideo==='A'?'B':'A';
311
- isTransitioning=false;
312
- },300);
313
- }).catch(()=>{
314
- next.muted=true;
315
  next.play().then(()=>{
316
  next.style.opacity='1';
317
  setTimeout(()=>{
@@ -319,11 +394,24 @@ function crossfadeTo(url, muted){
319
  prev.style.zIndex='0'; next.style.zIndex='1';
320
  currentVideo=currentVideo==='A'?'B':'A';
321
  isTransitioning=false;
 
322
  },300);
323
- }).catch(()=>{ isTransitioning=false; });
324
- });
325
- };
326
- next.onerror=function(){ isTransitioning=false; };
 
 
 
 
 
 
 
 
 
 
 
 
327
  }
328
 
329
  function pickRandomIdle(){
@@ -340,9 +428,28 @@ function playNextIdle(){
340
  crossfadeTo('/api/stream/'+encodeURIComponent(c.filename), true);
341
  }
342
 
 
343
  videoA.addEventListener('ended',()=>{ if(currentVideo==='A'&&!isProcessing) playNextIdle(); });
344
  videoB.addEventListener('ended',()=>{ if(currentVideo==='B'&&!isProcessing) playNextIdle(); });
345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  function addMessage(role, text, extra){
347
  const id='msg_'+(msgCounter++);
348
  const w=document.createElement('div'); w.className='msg '+role;
@@ -360,15 +467,9 @@ function addTypingIndicator(){
360
  return r;
361
  }
362
 
363
- function streamText(el, text, ms){
364
- el.className='content streaming-cursor'; el.textContent='';
365
- let i=0; const d=ms/text.length;
366
- const iv=setInterval(()=>{
367
- if(i<text.length){ el.textContent+=text[i]; i++; chatLog.scrollTop=chatLog.scrollHeight; }
368
- else{ clearInterval(iv); el.classList.remove('streaming-cursor'); }
369
- }, d);
370
- }
371
-
372
  async function sendMessage(){
373
  const text=chatInput.value.trim();
374
  if(!text||isProcessing) return;
@@ -377,6 +478,7 @@ async function sendMessage(){
377
  const typing=addTypingIndicator();
378
 
379
  try{
 
380
  const res=await fetch('/api/chat',{
381
  method:'POST', headers:{'Content-Type':'application/json'},
382
  body:JSON.stringify({text:text})
@@ -384,25 +486,56 @@ async function sendMessage(){
384
  if(!res.ok) throw new Error('HTTP '+res.status);
385
  const data=await res.json();
386
 
 
387
  typing.bubbleEl.classList.remove('typing');
388
  typing.contentEl.classList.remove('typing-dots');
389
- const dur=data.audio_duration?data.audio_duration*1000:2000;
390
- streamText(typing.contentEl, data.text, dur);
391
-
392
- if(data.audio_url){
393
- const audio=new Audio(data.audio_url);
394
- audio.play().catch(e=>console.warn('[AUDIO]',e));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
  }
396
 
397
- if(data.lipsync_video_url){
398
- videoStatus.textContent='speaking...';
399
- crossfadeTo(data.lipsync_video_url, true);
400
- setTimeout(()=>{
401
- const active=getActiveVideo();
402
- const onEnd=()=>{ active.removeEventListener('ended',onEnd); playNextIdle(); };
403
- active.addEventListener('ended',onEnd);
404
- },500);
405
- }
406
  }catch(err){
407
  typing.bubbleEl.classList.remove('typing');
408
  typing.bubbleEl.classList.add('error');
@@ -420,6 +553,9 @@ btnReset.addEventListener('click', async()=>{
420
  addMessage('bot','Ah, a fresh start! How may I assist you, my good fellow?');
421
  });
422
 
 
 
 
423
  async function init(){
424
  try{
425
  const res=await fetch('/api/videos');
 
1
  """
2
  Avatar Chatbot - HuggingFace Spaces Edition
3
+ Chunked pipeline: LLM (once) → split sentences → TTS+FLOAT per chunk → stream to frontend
4
  """
5
  from fastapi import FastAPI, HTTPException, Request
6
  from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
7
  from pathlib import Path
8
  import mimetypes
9
  import os
10
+ import re
11
  import logging
12
  import subprocess
13
+ import time as _time
14
+ import uuid
15
 
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
 
27
  for d in [VIDEOS_DIR, TTS_DIR, LIPSYNC_DIR]:
28
  d.mkdir(parents=True, exist_ok=True)
29
 
30
+ # In-memory store for chunked generation results
31
+ # session_id -> { "chunks": [...], "done": bool }
32
+ _sessions = {}
33
+
34
 
35
  @app.on_event("startup")
36
  async def startup():
 
153
  headers={"Content-Length": str(path.stat().st_size)})
154
 
155
 
156
+ def split_sentences(text):
157
+ """Split text by periods, exclamation marks, and question marks. Not commas."""
158
+ parts = re.split(r'(?<=[.!?])\s+', text)
159
+ return [s.strip() for s in parts if s.strip()]
160
+
161
+
162
  @app.post("/api/chat")
163
  async def chat(request: Request):
164
+ """
165
+ Step 1: LLM generates full response (fast).
166
+ Step 2: Split into sentences.
167
+ Step 3: Return text + session_id immediately.
168
+ Step 4: Frontend polls /api/chat/next to get chunks as they're generated.
169
+ """
170
  t0 = _time.time()
 
171
  body = await request.json()
172
  user_text = body.get("text", "").strip()
173
  if not user_text: raise HTTPException(400, "No text")
174
 
175
  logger.info(f"[CHAT] User: {user_text}")
176
 
177
+ # 1. LLM (single call)
178
  t1 = _time.time()
179
  from llm import generate_darwin_response
180
  llm_result = generate_darwin_response(user_text)
 
183
  logger.info(f"[CHAT] Darwin: {reply_text}")
184
  logger.info(f"[TIMING] LLM: {t2-t1:.2f}s")
185
 
186
+ # 2. Split into sentences
187
+ sentences = split_sentences(reply_text)
188
+ if not sentences:
189
+ sentences = [reply_text]
190
+ logger.info(f"[CHAT] Split into {len(sentences)} chunks")
191
+
192
+ # 3. Create session
193
+ session_id = str(uuid.uuid4())[:8]
194
+ _sessions[session_id] = {
195
+ "sentences": sentences,
196
+ "next_index": 0,
197
+ "total": len(sentences),
198
+ "done": False,
199
+ "created": _time.time(),
200
+ }
201
+
202
+ logger.info(f"[TIMING] Chat response ready: {_time.time()-t0:.2f}s")
203
+
204
+ return JSONResponse({
205
+ "text": reply_text,
206
+ "emotion": llm_result.get('emotion', 'neutral'),
207
+ "session_id": session_id,
208
+ "total_chunks": len(sentences),
209
+ })
210
+
211
+
212
+ @app.post("/api/chat/next")
213
+ async def chat_next(request: Request):
214
+ """
215
+ Generate TTS + lipsync for the next sentence in the session.
216
+ Called sequentially by the frontend — one chunk at a time.
217
+ Returns the audio URL, lipsync video URL, duration, and sentence text.
218
+ """
219
+ body = await request.json()
220
+ session_id = body.get("session_id", "")
221
+ session = _sessions.get(session_id)
222
+
223
+ if not session:
224
+ raise HTTPException(404, "Session not found")
225
+
226
+ idx = session["next_index"]
227
+ if idx >= session["total"]:
228
+ session["done"] = True
229
+ return JSONResponse({"done": True})
230
+
231
+ sentence = session["sentences"][idx]
232
+ session["next_index"] = idx + 1
233
+ is_last = (idx + 1 >= session["total"])
234
+
235
+ logger.info(f"[CHUNK {idx+1}/{session['total']}] {sentence[:60]}...")
236
+ t0 = _time.time()
237
+
238
+ # 1. TTS
239
  from tts import generate_audio
240
+ t1 = _time.time()
241
+ audio_path = generate_audio(sentence)
242
+ t2 = _time.time()
243
+ logger.info(f"[TIMING] Chunk {idx+1} TTS: {t2-t1:.2f}s")
244
 
245
  audio_url = None
246
  audio_duration = 0
 
248
  audio_url = f"/api/audio/{os.path.basename(audio_path)}"
249
  try:
250
  r = subprocess.run(["ffprobe","-v","quiet","-show_entries","format=duration",
251
+ "-of","csv=p=0", audio_path], capture_output=True, text=True, check=True)
252
  audio_duration = float(r.stdout.strip())
253
  except Exception:
254
  audio_duration = 3.0
255
 
256
+ # 2. Lipsync
257
  lipsync_video_url = None
258
  if FLOAT_ENABLED and audio_path and os.path.exists(audio_path):
259
  try:
260
  from float_lipsync import get_lipsync
261
  lipsync = get_lipsync()
262
  if lipsync.ready:
263
+ t3 = _time.time()
 
264
  lp = lipsync.generate(audio_path)
265
+ t4 = _time.time()
266
+ logger.info(f"[TIMING] Chunk {idx+1} FLOAT: {t4-t3:.2f}s")
267
  if lp and os.path.exists(lp):
268
  lipsync_video_url = f"/api/stream/{os.path.basename(lp)}"
 
 
269
  except Exception as e:
270
+ logger.error(f"[CHUNK] Lipsync failed: {e}", exc_info=True)
271
+
272
+ total_time = _time.time() - t0
273
+ logger.info(f"[TIMING] Chunk {idx+1} TOTAL: {total_time:.2f}s")
274
 
275
+ if is_last:
276
+ session["done"] = True
277
+ # Clean up old sessions (keep last 10)
278
+ if len(_sessions) > 10:
279
+ oldest = sorted(_sessions.keys(), key=lambda k: _sessions[k]["created"])
280
+ for k in oldest[:-10]:
281
+ del _sessions[k]
282
 
283
  return JSONResponse({
284
+ "done": False,
285
+ "chunk_index": idx,
286
+ "total_chunks": session["total"],
287
+ "is_last": is_last,
288
+ "sentence": sentence,
289
  "audio_url": audio_url,
290
  "audio_duration": audio_duration,
291
  "lipsync_video_url": lipsync_video_url,
 
363
  </div>
364
  </div>
365
  <script>
366
+ // ======================================================================
367
+ // STATE
368
+ // ======================================================================
369
  let videos=[], currentVideo='A', isTransitioning=false, isProcessing=false, lastPlayed=null, msgCounter=0;
370
  const videoA=document.getElementById('videoA'), videoB=document.getElementById('videoB');
371
  const videoStatus=document.getElementById('videoStatus'), chatLog=document.getElementById('chatLog');
372
  const chatInput=document.getElementById('chatInput'), btnSend=document.getElementById('btnSend');
373
  const btnReset=document.getElementById('btnReset');
374
 
375
+ // ======================================================================
376
+ // VIDEO: Crossfade
377
+ // ======================================================================
378
  function getActiveVideo(){return currentVideo==='A'?videoA:videoB}
379
  function getInactiveVideo(){return currentVideo==='A'?videoB:videoA}
380
 
381
  function crossfadeTo(url, muted){
382
+ return new Promise((resolve)=>{
383
+ if(isTransitioning){ resolve(); return; }
384
+ isTransitioning=true;
385
+ const prev=getActiveVideo(), next=getInactiveVideo();
386
+ next.muted=(muted!==false);
387
+ next.src=url; next.load();
388
+ next.onloadeddata=function(){
389
+ next.style.zIndex='2'; prev.style.zIndex='1'; next.style.opacity='0';
 
 
 
 
 
 
 
 
 
390
  next.play().then(()=>{
391
  next.style.opacity='1';
392
  setTimeout(()=>{
 
394
  prev.style.zIndex='0'; next.style.zIndex='1';
395
  currentVideo=currentVideo==='A'?'B':'A';
396
  isTransitioning=false;
397
+ resolve();
398
  },300);
399
+ }).catch(()=>{
400
+ next.muted=true;
401
+ next.play().then(()=>{
402
+ next.style.opacity='1';
403
+ setTimeout(()=>{
404
+ prev.style.opacity='0'; prev.pause(); prev.src='';
405
+ prev.style.zIndex='0'; next.style.zIndex='1';
406
+ currentVideo=currentVideo==='A'?'B':'A';
407
+ isTransitioning=false;
408
+ resolve();
409
+ },300);
410
+ }).catch(()=>{ isTransitioning=false; resolve(); });
411
+ });
412
+ };
413
+ next.onerror=function(){ isTransitioning=false; resolve(); };
414
+ });
415
  }
416
 
417
  function pickRandomIdle(){
 
428
  crossfadeTo('/api/stream/'+encodeURIComponent(c.filename), true);
429
  }
430
 
431
+ // Idle loop: when video ends and not speaking, play next idle
432
  videoA.addEventListener('ended',()=>{ if(currentVideo==='A'&&!isProcessing) playNextIdle(); });
433
  videoB.addEventListener('ended',()=>{ if(currentVideo==='B'&&!isProcessing) playNextIdle(); });
434
 
435
+ // ======================================================================
436
+ // VIDEO: Wait for current lipsync video to end
437
+ // ======================================================================
438
+ function waitForVideoEnd(){
439
+ return new Promise((resolve)=>{
440
+ const active=getActiveVideo();
441
+ // If video is very short or already ended, resolve quickly
442
+ if(active.ended || active.paused || !active.src){
443
+ resolve(); return;
444
+ }
445
+ const onEnd=()=>{ active.removeEventListener('ended',onEnd); resolve(); };
446
+ active.addEventListener('ended', onEnd);
447
+ });
448
+ }
449
+
450
+ // ======================================================================
451
+ // CHAT: Messages
452
+ // ======================================================================
453
  function addMessage(role, text, extra){
454
  const id='msg_'+(msgCounter++);
455
  const w=document.createElement('div'); w.className='msg '+role;
 
467
  return r;
468
  }
469
 
470
+ // ======================================================================
471
+ // CHAT: Send message with chunked playback
472
+ // ======================================================================
 
 
 
 
 
 
473
  async function sendMessage(){
474
  const text=chatInput.value.trim();
475
  if(!text||isProcessing) return;
 
478
  const typing=addTypingIndicator();
479
 
480
  try{
481
+ // Step 1: Get LLM response + session (fast, ~0.5s)
482
  const res=await fetch('/api/chat',{
483
  method:'POST', headers:{'Content-Type':'application/json'},
484
  body:JSON.stringify({text:text})
 
486
  if(!res.ok) throw new Error('HTTP '+res.status);
487
  const data=await res.json();
488
 
489
+ // Show full text immediately
490
  typing.bubbleEl.classList.remove('typing');
491
  typing.contentEl.classList.remove('typing-dots');
492
+ typing.contentEl.textContent=data.text;
493
+ chatLog.scrollTop=chatLog.scrollHeight;
494
+
495
+ const sessionId=data.session_id;
496
+ const totalChunks=data.total_chunks;
497
+
498
+ videoStatus.textContent='generating 1/'+totalChunks+'...';
499
+
500
+ // Step 2: Request chunks one at a time, play each as it arrives
501
+ for(let i=0; i<totalChunks; i++){
502
+ videoStatus.textContent='generating '+(i+1)+'/'+totalChunks+'...';
503
+
504
+ const chunkRes=await fetch('/api/chat/next',{
505
+ method:'POST', headers:{'Content-Type':'application/json'},
506
+ body:JSON.stringify({session_id:sessionId})
507
+ });
508
+ if(!chunkRes.ok) continue;
509
+ const chunk=await chunkRes.json();
510
+ if(chunk.done) break;
511
+
512
+ videoStatus.textContent='speaking '+(i+1)+'/'+totalChunks;
513
+
514
+ // Play audio
515
+ let audioPromise=null;
516
+ if(chunk.audio_url){
517
+ const audio=new Audio(chunk.audio_url);
518
+ audioPromise=new Promise((resolve)=>{
519
+ audio.onended=resolve;
520
+ audio.onerror=resolve;
521
+ audio.play().catch(()=>resolve());
522
+ });
523
+ }
524
+
525
+ // Play lipsync video
526
+ if(chunk.lipsync_video_url){
527
+ await crossfadeTo(chunk.lipsync_video_url, true);
528
+ // Wait for this lipsync video to finish before next chunk
529
+ await waitForVideoEnd();
530
+ } else if(audioPromise){
531
+ // No lipsync, just wait for audio to finish
532
+ await audioPromise;
533
+ }
534
  }
535
 
536
+ // All chunks done, return to idle
537
+ playNextIdle();
538
+
 
 
 
 
 
 
539
  }catch(err){
540
  typing.bubbleEl.classList.remove('typing');
541
  typing.bubbleEl.classList.add('error');
 
553
  addMessage('bot','Ah, a fresh start! How may I assist you, my good fellow?');
554
  });
555
 
556
+ // ======================================================================
557
+ // INIT
558
+ // ======================================================================
559
  async function init(){
560
  try{
561
  const res=await fetch('/api/videos');