J Z commited on
Commit
83ba15e
·
verified ·
1 Parent(s): c819c5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +362 -253
app.py CHANGED
@@ -1,10 +1,11 @@
1
  """
2
  Avatar Chatbot - HuggingFace Spaces Edition
3
  Phase 1: Chat UI + Idle Video Loop + LLM (Groq) + TTS (Groq)
4
- Phase 2: FLOAT lipsync (async background generation)
5
  """
6
  from fastapi import FastAPI, HTTPException, Request
7
  from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
 
8
  from pathlib import Path
9
  import mimetypes
10
  import os
@@ -12,8 +13,6 @@ import logging
12
  import asyncio
13
  import time
14
  import subprocess
15
- import uuid
16
- import threading
17
 
18
  logging.basicConfig(level=logging.INFO)
19
  logger = logging.getLogger(__name__)
@@ -25,19 +24,14 @@ VIDEOS_DIR = Path("/tmp/videos")
25
  TTS_DIR = Path("/tmp/tts_output")
26
  LIPSYNC_DIR = Path("/tmp/lipsync_output")
27
  REPO_ID = os.environ.get("SPACE_ID", "ffbeqwbe/AvatarChatbot")
 
28
  FLOAT_ENABLED = os.environ.get("FLOAT_ENABLED", "true").lower() == "true"
29
 
30
  for d in [VIDEOS_DIR, TTS_DIR, LIPSYNC_DIR]:
31
  d.mkdir(parents=True, exist_ok=True)
32
 
33
- # --- Background job tracking ---
34
- # job_id -> {"status": "pending"|"done"|"error", "result": {...}}
35
- lipsync_jobs = {}
36
-
37
 
38
- # ======================================================================
39
- # STARTUP
40
- # ======================================================================
41
  @app.on_event("startup")
42
  async def startup():
43
  await download_videos()
@@ -61,23 +55,29 @@ async def init_float():
61
  checkpoints_dir = Path("/app/checkpoints")
62
  checkpoints_dir.mkdir(parents=True, exist_ok=True)
63
 
64
- # Download wav2vec2-base-960h
65
  w2v_dir = checkpoints_dir / "wav2vec2-base-960h"
66
  if not w2v_dir.exists():
67
  logger.info("[STARTUP] Downloading wav2vec2-base-960h...")
68
  from huggingface_hub import snapshot_download
69
- snapshot_download(repo_id="facebook/wav2vec2-base-960h", local_dir=str(w2v_dir))
 
 
 
70
  logger.info("[STARTUP] wav2vec2-base-960h downloaded")
71
 
72
- # Download emotion recognition model
73
  emo_dir = checkpoints_dir / "wav2vec-english-speech-emotion-recognition"
74
  if not emo_dir.exists():
75
  logger.info("[STARTUP] Downloading emotion recognition model...")
76
  from huggingface_hub import snapshot_download
77
- snapshot_download(repo_id="r-f/wav2vec-english-speech-emotion-recognition", local_dir=str(emo_dir))
 
 
 
78
  logger.info("[STARTUP] Emotion model downloaded")
79
 
80
- # Download float.pth from repo (xet storage)
81
  float_ckpt = checkpoints_dir / "float.pth"
82
  if not float_ckpt.exists() or float_ckpt.stat().st_size < 1024:
83
  logger.info("[STARTUP] Downloading float.pth from repo...")
@@ -91,29 +91,38 @@ async def init_float():
91
  logger.info(f"[STARTUP] float.pth downloaded: {float_ckpt.stat().st_size / 1e6:.1f} MB")
92
  except Exception as e:
93
  logger.warning(f"[STARTUP] Could not download float.pth: {e}")
 
 
94
  return
95
 
96
- # Download reference image from repo
97
  assets_dir = Path("/app/assets")
98
  assets_dir.mkdir(parents=True, exist_ok=True)
99
  ref_image = assets_dir / "ref.png"
100
  if not ref_image.exists() or ref_image.stat().st_size < 1024:
101
  logger.info("[STARTUP] Looking for reference image in repo...")
102
- for ext in ["ref.png", "ref.jpg", "ref.jpeg", "main2.png"]:
103
- try:
104
- downloaded = hf_hub_download(
105
- repo_id=REPO_ID, repo_type="space",
106
- filename=f"app/assets/{ext}", local_dir="/tmp/hf_download",
107
- )
108
- dest = assets_dir / ext
109
- shutil.copy2(downloaded, dest)
110
- ref_image = dest
111
- logger.info(f"[STARTUP] Reference image downloaded: {ext}")
112
- break
113
- except Exception:
114
- continue
115
- else:
116
- logger.warning("[STARTUP] No reference image found in app/assets/")
 
 
 
 
 
 
 
117
  return
118
 
119
  # Initialize FLOAT
@@ -134,6 +143,7 @@ async def init_float():
134
  async def download_videos():
135
  from huggingface_hub import HfApi, hf_hub_download
136
  import shutil
 
137
  try:
138
  api = HfApi()
139
  files = api.list_repo_files(repo_id=REPO_ID, repo_type="space")
@@ -143,6 +153,7 @@ async def download_videos():
143
  and any(f.endswith(ext) for ext in (".mp4", ".webm", ".mkv", ".mov"))
144
  ]
145
  logger.info(f"Found {len(video_files)} video files in repo")
 
146
  for vf in video_files:
147
  filename = Path(vf).name
148
  dest = VIDEOS_DIR / filename
@@ -159,10 +170,7 @@ async def download_videos():
159
  logger.error(f"Error downloading videos: {e}")
160
 
161
 
162
- # ======================================================================
163
- # API ENDPOINTS
164
- # ======================================================================
165
-
166
  @app.get("/api/videos")
167
  async def list_videos():
168
  if not VIDEOS_DIR.exists():
@@ -174,14 +182,17 @@ async def list_videos():
174
  return JSONResponse({"videos": videos})
175
 
176
 
 
177
  @app.get("/api/stream/{filename}")
178
  async def stream_video(filename: str):
 
179
  video_path = None
180
  for search_dir in [VIDEOS_DIR, LIPSYNC_DIR, TTS_DIR]:
181
  candidate = search_dir / filename
182
  if candidate.exists() and candidate.is_file():
183
  video_path = candidate
184
  break
 
185
  if not video_path:
186
  raise HTTPException(status_code=404, detail="Video not found")
187
 
@@ -194,11 +205,13 @@ async def stream_video(filename: str):
194
  yield chunk
195
 
196
  return StreamingResponse(
197
- iter_file(), media_type=mime_type,
 
198
  headers={"Content-Length": str(file_size), "Accept-Ranges": "bytes"},
199
  )
200
 
201
 
 
202
  @app.get("/api/audio/{filename}")
203
  async def stream_audio(filename: str):
204
  audio_path = TTS_DIR / filename
@@ -214,36 +227,73 @@ async def stream_audio(filename: str):
214
  yield chunk
215
 
216
  return StreamingResponse(
217
- iter_file(), media_type=mime_type,
 
218
  headers={"Content-Length": str(file_size)},
219
  )
220
 
221
 
222
- # --- Chat: returns LLM text + TTS audio immediately, kicks off lipsync in background ---
223
  @app.post("/api/chat")
224
  async def chat(request: Request):
 
 
 
 
 
225
  body = await request.json()
226
  user_text = body.get("text", "").strip()
 
227
  if not user_text:
228
  raise HTTPException(status_code=400, detail="No text provided")
229
 
230
  logger.info(f"[CHAT] User: {user_text}")
231
 
232
- # 1. LLM (fast)
233
  from llm import generate_darwin_response
234
  llm_result = generate_darwin_response(user_text)
235
  reply_text = llm_result['text']
236
  logger.info(f"[CHAT] Darwin: {reply_text}")
237
 
238
- # 2. TTS (fast ~1-2s)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  from tts import generate_audio
240
- audio_path = generate_audio(reply_text)
241
  audio_url = None
242
  audio_duration = 0
243
 
244
  if audio_path and os.path.exists(audio_path):
245
  audio_filename = os.path.basename(audio_path)
246
  audio_url = f"/api/audio/{audio_filename}"
 
247
  try:
248
  result = subprocess.run(
249
  ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
@@ -254,65 +304,31 @@ async def chat(request: Request):
254
  except Exception:
255
  audio_duration = 3.0
256
 
257
- # 3. Kick off lipsync in background thread (slow ~20s, don't block)
258
- job_id = None
259
  if FLOAT_ENABLED and audio_path and os.path.exists(audio_path):
260
  try:
261
  from float_lipsync import get_lipsync
262
  lipsync = get_lipsync()
263
  if lipsync.ready:
264
- job_id = str(uuid.uuid4())[:8]
265
- lipsync_jobs[job_id] = {"status": "pending"}
266
- # Run in background thread so this response returns immediately
267
- thread = threading.Thread(
268
- target=_run_lipsync_job,
269
- args=(job_id, audio_path),
270
- daemon=True
271
- )
272
- thread.start()
273
- logger.info(f"[CHAT] Lipsync job started: {job_id}")
274
  except Exception as e:
275
- logger.error(f"[CHAT] Lipsync setup failed: {e}")
276
 
277
  return JSONResponse({
278
- "text": reply_text,
279
- "emotion": llm_result.get('emotion', 'neutral'),
280
  "audio_url": audio_url,
281
  "audio_duration": audio_duration,
282
- "lipsync_job_id": job_id, # Frontend polls this
283
  })
284
 
285
 
286
- def _run_lipsync_job(job_id: str, audio_path: str):
287
- """Runs FLOAT inference in a background thread."""
288
- try:
289
- from float_lipsync import get_lipsync
290
- lipsync = get_lipsync()
291
- logger.info(f"[LIPSYNC-{job_id}] Starting generation...")
292
- lipsync_path = lipsync.generate(audio_path)
293
- if lipsync_path and os.path.exists(lipsync_path):
294
- lipsync_filename = os.path.basename(lipsync_path)
295
- lipsync_jobs[job_id] = {
296
- "status": "done",
297
- "lipsync_video_url": f"/api/stream/{lipsync_filename}",
298
- }
299
- logger.info(f"[LIPSYNC-{job_id}] Done: {lipsync_filename}")
300
- else:
301
- lipsync_jobs[job_id] = {"status": "error", "message": "No output file"}
302
- except Exception as e:
303
- logger.error(f"[LIPSYNC-{job_id}] Failed: {e}", exc_info=True)
304
- lipsync_jobs[job_id] = {"status": "error", "message": str(e)}
305
-
306
-
307
- # --- Poll for lipsync job result ---
308
- @app.get("/api/lipsync/{job_id}")
309
- async def poll_lipsync(job_id: str):
310
- job = lipsync_jobs.get(job_id)
311
- if not job:
312
- raise HTTPException(status_code=404, detail="Job not found")
313
- return JSONResponse(job)
314
-
315
-
316
  @app.post("/api/reset")
317
  async def reset_chat():
318
  from llm import reset_conversation
@@ -320,9 +336,7 @@ async def reset_chat():
320
  return JSONResponse({"status": "ok"})
321
 
322
 
323
- # ======================================================================
324
- # MAIN PAGE
325
- # ======================================================================
326
  @app.get("/", response_class=HTMLResponse)
327
  async def index():
328
  return HTML_PAGE
@@ -337,7 +351,6 @@ HTML_PAGE = """\
337
  <title>Darwin Avatar Chatbot</title>
338
  <style>
339
  * { margin: 0; padding: 0; box-sizing: border-box; }
340
-
341
  body {
342
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
343
  background: #0a0f1c;
@@ -347,7 +360,7 @@ HTML_PAGE = """\
347
  flex-direction: column;
348
  overflow: hidden;
349
  }
350
-
351
  .app-container {
352
  display: flex;
353
  flex-direction: column;
@@ -358,8 +371,7 @@ HTML_PAGE = """\
358
  padding: 1rem;
359
  gap: 0.75rem;
360
  }
361
-
362
- /* --- VIDEO --- */
363
  .video-section {
364
  position: relative;
365
  width: 100%;
@@ -373,95 +385,158 @@ HTML_PAGE = """\
373
  align-items: center;
374
  justify-content: center;
375
  }
376
- .video-container { position: relative; width: 100%; height: 100%; }
 
 
 
 
377
  .video-container video {
378
- width: 100%; height: 100%; object-fit: contain; display: block;
 
 
 
379
  }
380
  #videoA, #videoB {
381
- position: absolute; top: 0; left: 0; width: 100%; height: 100%;
382
- object-fit: contain; transition: opacity 0.25s ease;
 
 
 
383
  }
384
  #videoA { z-index: 1; opacity: 1; }
385
  #videoB { z-index: 0; opacity: 0; }
386
  .video-status {
387
- position: absolute; bottom: 8px; right: 12px;
388
- font-size: 0.7rem; color: rgba(255,255,255,0.4);
389
- background: rgba(0,0,0,0.5); padding: 2px 8px;
390
- border-radius: 4px; z-index: 10;
 
 
 
 
 
391
  }
392
-
393
- /* --- CHAT --- */
394
  .chat-section {
395
- flex: 1; display: flex; flex-direction: column; min-height: 0;
 
 
 
396
  background: rgba(15, 23, 42, 0.6);
397
  border: 1px solid rgba(59, 130, 246, 0.15);
398
- border-radius: 12px; overflow: hidden;
 
399
  }
400
  .chat-log {
401
- flex: 1; overflow-y: auto; padding: 1rem;
402
- display: flex; flex-direction: column; gap: 0.5rem;
 
 
 
 
403
  }
404
  .chat-log::-webkit-scrollbar { width: 6px; }
 
405
  .chat-log::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; }
 
406
  .msg { display: flex; width: 100%; }
407
  .msg.user { justify-content: flex-end; }
408
  .msg.bot { justify-content: flex-start; }
409
  .bubble {
410
- max-width: 85%; padding: 10px 14px; border-radius: 12px;
411
- word-wrap: break-word; font-size: 0.9rem; line-height: 1.4;
 
 
 
 
412
  }
413
  .bubble.user {
414
- background: linear-gradient(135deg, #1e40af, #3b82f6); color: #fff;
 
415
  border-bottom-right-radius: 4px;
416
  }
417
  .bubble.bot {
418
  background: rgba(30, 41, 59, 0.8);
419
- border: 1px solid rgba(59, 130, 246, 0.2); color: #e2e8f0;
 
420
  border-bottom-left-radius: 4px;
421
  }
422
- .bubble .label { color: #60a5fa; font-weight: 600; font-size: 0.8rem; margin-bottom: 2px; }
423
- .bubble.user .label { color: rgba(255,255,255,0.7); }
424
- .bubble.typing { color: #64748b; font-style: italic; }
 
 
 
425
  .bubble.error {
426
  background: rgba(127, 29, 29, 0.5);
427
- border-color: rgba(239, 68, 68, 0.3); color: #fca5a5;
 
 
 
 
 
 
 
 
 
 
 
428
  }
429
- @keyframes dots { 0%,20%{content:''} 40%{content:'.'} 60%{content:'..'} 80%,100%{content:'...'} }
430
- .typing-dots::after { content: ''; animation: dots 1.5s infinite; }
431
  .streaming-cursor::after {
432
- content: '▊'; animation: blink 0.7s infinite; color: #60a5fa;
 
 
433
  }
434
- @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0} }
435
-
436
- /* --- INPUT --- */
437
  .input-bar {
438
- display: flex; gap: 0.5rem; padding: 0.75rem 1rem;
 
 
439
  background: rgba(15, 23, 42, 0.8);
440
  border-top: 1px solid rgba(59, 130, 246, 0.1);
441
  }
442
  .input-bar input {
443
- flex: 1; background: rgba(30, 41, 59, 0.8);
444
- border: 1px solid rgba(59, 130, 246, 0.25); border-radius: 8px;
445
- padding: 10px 14px; color: #e2e8f0; font-size: 0.9rem; outline: none;
 
 
 
 
 
 
 
 
 
446
  }
447
- .input-bar input:focus { border-color: #3b82f6; }
448
  .input-bar input::placeholder { color: #64748b; }
449
  .input-bar button {
450
- padding: 10px 20px; border: none; border-radius: 8px;
451
- font-size: 0.9rem; cursor: pointer; font-weight: 500;
 
 
 
 
 
 
 
 
 
452
  }
453
- .btn-send { background: #3b82f6; color: #fff; }
454
  .btn-send:hover { background: #2563eb; }
455
  .btn-send:disabled { background: #334155; color: #64748b; cursor: not-allowed; }
456
  .btn-reset {
457
- background: rgba(100,116,139,0.3); color: #94a3b8;
458
- border: 1px solid rgba(100,116,139,0.3);
 
459
  }
460
- .btn-reset:hover { background: rgba(100,116,139,0.5); }
461
  </style>
462
  </head>
463
  <body>
464
  <div class="app-container">
 
465
  <div class="video-section">
466
  <div class="video-container">
467
  <video id="videoA" muted autoplay playsinline></video>
@@ -469,16 +544,17 @@ HTML_PAGE = """\
469
  </div>
470
  <div class="video-status" id="videoStatus">Loading...</div>
471
  </div>
 
472
  <div class="chat-section">
473
  <div class="chat-log" id="chatLog"></div>
474
  <div class="input-bar">
475
- <input type="text" id="chatInput" placeholder="Ask Darwin something..." autocomplete="off" />
 
476
  <button class="btn-send" id="btnSend">Send</button>
477
- <button class="btn-reset" id="btnReset" title="Reset conversation">&#x21bb;</button>
478
  </div>
479
  </div>
480
  </div>
481
-
482
  <script>
483
  // ======================================================================
484
  // STATE
@@ -488,9 +564,6 @@ let currentVideo = 'A';
488
  let isTransitioning = false;
489
  let isProcessing = false;
490
  let lastPlayed = null;
491
- let pendingLipsyncUrl = null; // set when lipsync is ready
492
- let currentAudio = null;
493
-
494
  const videoA = document.getElementById('videoA');
495
  const videoB = document.getElementById('videoB');
496
  const videoStatus = document.getElementById('videoStatus');
@@ -498,30 +571,26 @@ const chatLog = document.getElementById('chatLog');
498
  const chatInput = document.getElementById('chatInput');
499
  const btnSend = document.getElementById('btnSend');
500
  const btnReset = document.getElementById('btnReset');
501
-
502
  // ======================================================================
503
- // VIDEO: Crossfade
504
  // ======================================================================
505
  function getActiveVideo() { return currentVideo === 'A' ? videoA : videoB; }
506
  function getInactiveVideo() { return currentVideo === 'A' ? videoB : videoA; }
507
-
508
- function crossfadeTo(videoUrl, muted) {
509
- if (isTransitioning) {
510
- setTimeout(() => crossfadeTo(videoUrl, muted), 200);
511
- return;
512
- }
513
  isTransitioning = true;
514
  const prev = getActiveVideo();
515
  const next = getInactiveVideo();
516
- next.muted = (muted !== false);
 
517
  next.src = videoUrl;
518
  next.load();
519
-
520
  next.onloadeddata = function() {
521
  next.style.zIndex = '2';
522
  prev.style.zIndex = '1';
523
  next.style.opacity = '0';
524
  next.play().then(() => {
 
525
  next.style.opacity = '1';
526
  setTimeout(() => {
527
  prev.style.opacity = '0';
@@ -532,62 +601,117 @@ function crossfadeTo(videoUrl, muted) {
532
  currentVideo = currentVideo === 'A' ? 'B' : 'A';
533
  isTransitioning = false;
534
  }, 300);
535
- }).catch(() => {
 
 
 
536
  next.muted = true;
537
  next.play().then(() => {
538
  next.style.opacity = '1';
539
  setTimeout(() => {
540
- prev.style.opacity = '0'; prev.pause(); prev.src = '';
541
- prev.style.zIndex = '0'; next.style.zIndex = '1';
 
 
 
542
  currentVideo = currentVideo === 'A' ? 'B' : 'A';
543
  isTransitioning = false;
544
  }, 300);
545
- }).catch(() => { isTransitioning = false; setTimeout(playNextIdle, 500); });
 
 
 
546
  });
547
  };
548
- next.onerror = function() { isTransitioning = false; setTimeout(playNextIdle, 500); };
 
 
 
549
  }
550
-
551
  function pickRandomIdle() {
552
  if (videos.length === 0) return null;
553
  if (videos.length === 1) return videos[0];
554
  let pick;
555
- do { pick = videos[Math.floor(Math.random() * videos.length)]; }
556
- while (pick.filename === lastPlayed && videos.length > 1);
 
557
  return pick;
558
  }
559
-
560
  function playNextIdle() {
561
- // If a lipsync video is ready, play it instead!
562
- if (pendingLipsyncUrl) {
563
- const url = pendingLipsyncUrl;
564
- pendingLipsyncUrl = null;
565
- videoStatus.textContent = 'speaking...';
566
- crossfadeTo(url, true);
567
- return;
568
- }
569
  const clip = pickRandomIdle();
570
  if (!clip) return;
571
  lastPlayed = clip.filename;
572
  videoStatus.textContent = 'idle: ' + clip.name;
573
  crossfadeTo('/api/stream/' + encodeURIComponent(clip.filename), true);
574
  }
575
-
576
- // When a video ends, play next
577
- videoA.addEventListener('ended', () => { if (currentVideo === 'A') playNextIdle(); });
578
- videoB.addEventListener('ended', () => { if (currentVideo === 'B') playNextIdle(); });
579
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  // ======================================================================
581
- // CHAT
582
  // ======================================================================
583
  let msgCounter = 0;
584
-
585
- function addMessage(role, text, extraClass) {
586
- const id = 'msg_' + msgCounter++;
587
  const wrapper = document.createElement('div');
588
- wrapper.className = 'msg ' + role;
589
  const bubble = document.createElement('div');
590
- bubble.className = 'bubble ' + role + ' ' + (extraClass || '');
591
  bubble.id = id;
592
  const label = document.createElement('div');
593
  label.className = 'label';
@@ -600,118 +724,102 @@ function addMessage(role, text, extraClass) {
600
  wrapper.appendChild(bubble);
601
  chatLog.appendChild(wrapper);
602
  chatLog.scrollTop = chatLog.scrollHeight;
603
- return { id: id, contentEl: content, bubbleEl: bubble };
604
  }
605
-
606
- function streamText(el, text, ms) {
607
- el.className = 'content streaming-cursor';
608
- el.textContent = '';
609
- let i = 0;
610
- const delay = ms / text.length;
611
- const iv = setInterval(() => {
612
- if (i < text.length) { el.textContent += text[i]; i++; chatLog.scrollTop = chatLog.scrollHeight; }
613
- else { clearInterval(iv); el.classList.remove('streaming-cursor'); }
614
- }, delay);
615
  }
616
-
617
- // ======================================================================
618
- // LIPSYNC POLLING
619
- // ======================================================================
620
- async function pollLipsyncJob(jobId) {
621
- // Poll every 2 seconds until done
622
- for (let attempt = 0; attempt < 30; attempt++) {
623
- await new Promise(r => setTimeout(r, 2000));
624
- try {
625
- const res = await fetch('/api/lipsync/' + jobId);
626
- if (!res.ok) break;
627
- const job = await res.json();
628
- if (job.status === 'done' && job.lipsync_video_url) {
629
- console.log('[POLL] Lipsync ready:', job.lipsync_video_url);
630
- // Queue it — will play when current idle clip ends
631
- pendingLipsyncUrl = job.lipsync_video_url;
632
- return;
633
- }
634
- if (job.status === 'error') {
635
- console.warn('[POLL] Lipsync job error:', job.message);
636
- return;
637
- }
638
- // Still pending — keep polling
639
- } catch (e) {
640
- console.error('[POLL] Error:', e);
641
- break;
642
  }
643
- }
644
- console.warn('[POLL] Lipsync job timed out');
645
  }
646
-
647
  // ======================================================================
648
- // SEND MESSAGE
649
  // ======================================================================
650
  async function sendMessage() {
651
  const text = chatInput.value.trim();
652
  if (!text || isProcessing) return;
653
-
654
  isProcessing = true;
655
  btnSend.disabled = true;
656
  chatInput.value = '';
657
-
658
  addMessage('user', text);
659
- const typing = addMessage('bot', '', 'typing');
660
- typing.contentEl.className = 'content typing-dots';
661
- typing.contentEl.textContent = 'thinking';
662
-
663
  try {
 
664
  const res = await fetch('/api/chat', {
665
  method: 'POST',
666
  headers: { 'Content-Type': 'application/json' },
667
- body: JSON.stringify({ text: text })
668
  });
669
- if (!res.ok) throw new Error('HTTP ' + res.status);
670
  const data = await res.json();
671
-
672
- // Show text immediately
673
  typing.bubbleEl.classList.remove('typing');
674
  typing.contentEl.classList.remove('typing-dots');
675
-
676
- const streamDuration = data.audio_duration ? data.audio_duration * 1000 : 2000;
677
- streamText(typing.contentEl, data.text, streamDuration);
678
-
679
- // Play TTS audio immediately
680
- if (data.audio_url) {
681
- if (currentAudio) { currentAudio.pause(); currentAudio = null; }
682
- currentAudio = new Audio(data.audio_url);
683
- currentAudio.play().catch(e => console.warn('[AUDIO] Play blocked:', e));
684
- }
685
-
686
- // Poll for lipsync in background (non-blocking)
687
- if (data.lipsync_job_id) {
688
- pollLipsyncJob(data.lipsync_job_id);
689
- // This runs in background — sendMessage returns immediately
 
 
 
 
 
 
 
 
 
 
690
  }
691
-
692
  } catch (err) {
693
  typing.bubbleEl.classList.remove('typing');
694
  typing.bubbleEl.classList.add('error');
695
  typing.contentEl.classList.remove('typing-dots');
696
  typing.contentEl.textContent = 'Error: ' + err.message;
 
 
697
  }
698
-
699
- isProcessing = false;
700
- btnSend.disabled = false;
701
- chatInput.focus();
702
  }
703
-
704
  btnSend.addEventListener('click', sendMessage);
705
  chatInput.addEventListener('keydown', (e) => {
706
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
 
 
 
707
  });
708
-
709
  btnReset.addEventListener('click', async () => {
710
  await fetch('/api/reset', { method: 'POST' });
711
  chatLog.innerHTML = '';
712
  addMessage('bot', 'Ah, a fresh start! How may I assist you, my good fellow?');
713
  });
714
-
715
  // ======================================================================
716
  // INIT
717
  // ======================================================================
@@ -726,7 +834,9 @@ async function init() {
726
  }
727
  videos = data.videos;
728
  videoStatus.textContent = videos.length + ' idle clips loaded';
 
729
  playNextIdle();
 
730
  addMessage('bot',
731
  'Good day! I am Charles Darwin, er, recreated in this curious digital form. ' +
732
  'Do feel free to ask me anything, umm, about the natural world or otherwise.'
@@ -735,7 +845,6 @@ async function init() {
735
  videoStatus.textContent = 'Error: ' + e.message;
736
  }
737
  }
738
-
739
  init();
740
  </script>
741
  </body>
 
1
  """
2
  Avatar Chatbot - HuggingFace Spaces Edition
3
  Phase 1: Chat UI + Idle Video Loop + LLM (Groq) + TTS (Groq)
4
+ Phase 2: FLOAT lipsync (to be added)
5
  """
6
  from fastapi import FastAPI, HTTPException, Request
7
  from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
8
+ from fastapi.staticfiles import StaticFiles
9
  from pathlib import Path
10
  import mimetypes
11
  import os
 
13
  import asyncio
14
  import time
15
  import subprocess
 
 
16
 
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
 
24
  TTS_DIR = Path("/tmp/tts_output")
25
  LIPSYNC_DIR = Path("/tmp/lipsync_output")
26
  REPO_ID = os.environ.get("SPACE_ID", "ffbeqwbe/AvatarChatbot")
27
+
28
  FLOAT_ENABLED = os.environ.get("FLOAT_ENABLED", "true").lower() == "true"
29
 
30
  for d in [VIDEOS_DIR, TTS_DIR, LIPSYNC_DIR]:
31
  d.mkdir(parents=True, exist_ok=True)
32
 
 
 
 
 
33
 
34
+ # --- Startup: download idle videos + init FLOAT ---
 
 
35
  @app.on_event("startup")
36
  async def startup():
37
  await download_videos()
 
55
  checkpoints_dir = Path("/app/checkpoints")
56
  checkpoints_dir.mkdir(parents=True, exist_ok=True)
57
 
58
+ # Download wav2vec2-base-960h from HuggingFace
59
  w2v_dir = checkpoints_dir / "wav2vec2-base-960h"
60
  if not w2v_dir.exists():
61
  logger.info("[STARTUP] Downloading wav2vec2-base-960h...")
62
  from huggingface_hub import snapshot_download
63
+ snapshot_download(
64
+ repo_id="facebook/wav2vec2-base-960h",
65
+ local_dir=str(w2v_dir),
66
+ )
67
  logger.info("[STARTUP] wav2vec2-base-960h downloaded")
68
 
69
+ # Download wav2vec-english-speech-emotion-recognition
70
  emo_dir = checkpoints_dir / "wav2vec-english-speech-emotion-recognition"
71
  if not emo_dir.exists():
72
  logger.info("[STARTUP] Downloading emotion recognition model...")
73
  from huggingface_hub import snapshot_download
74
+ snapshot_download(
75
+ repo_id="r-f/wav2vec-english-speech-emotion-recognition",
76
+ local_dir=str(emo_dir),
77
+ )
78
  logger.info("[STARTUP] Emotion model downloaded")
79
 
80
+ # Check for float.pth - download from repo if not present (xet storage)
81
  float_ckpt = checkpoints_dir / "float.pth"
82
  if not float_ckpt.exists() or float_ckpt.stat().st_size < 1024:
83
  logger.info("[STARTUP] Downloading float.pth from repo...")
 
91
  logger.info(f"[STARTUP] float.pth downloaded: {float_ckpt.stat().st_size / 1e6:.1f} MB")
92
  except Exception as e:
93
  logger.warning(f"[STARTUP] Could not download float.pth: {e}")
94
+ logger.warning("[STARTUP] Upload it to your Space repo under app/checkpoints/float.pth")
95
+ logger.warning("[STARTUP] FLOAT lipsync will be disabled until checkpoint is available")
96
  return
97
 
98
+ # Check for reference image - download from repo if needed
99
  assets_dir = Path("/app/assets")
100
  assets_dir.mkdir(parents=True, exist_ok=True)
101
  ref_image = assets_dir / "ref.png"
102
  if not ref_image.exists() or ref_image.stat().st_size < 1024:
103
  logger.info("[STARTUP] Looking for reference image in repo...")
104
+ try:
105
+ # Try common image extensions
106
+ for ext in ["ref.png", "ref.jpg", "ref.jpeg", "main2.png"]:
107
+ try:
108
+ downloaded = hf_hub_download(
109
+ repo_id=REPO_ID, repo_type="space",
110
+ filename=f"app/assets/{ext}",
111
+ local_dir="/tmp/hf_download",
112
+ )
113
+ dest = assets_dir / ext
114
+ shutil.copy2(downloaded, dest)
115
+ ref_image = dest
116
+ logger.info(f"[STARTUP] Reference image downloaded: {ext}")
117
+ break
118
+ except Exception:
119
+ continue
120
+ else:
121
+ logger.warning("[STARTUP] No reference image found in app/assets/")
122
+ logger.warning("[STARTUP] Upload a face image as app/assets/ref.png")
123
+ return
124
+ except Exception as e:
125
+ logger.warning(f"[STARTUP] Could not download reference image: {e}")
126
  return
127
 
128
  # Initialize FLOAT
 
143
  async def download_videos():
144
  from huggingface_hub import HfApi, hf_hub_download
145
  import shutil
146
+
147
  try:
148
  api = HfApi()
149
  files = api.list_repo_files(repo_id=REPO_ID, repo_type="space")
 
153
  and any(f.endswith(ext) for ext in (".mp4", ".webm", ".mkv", ".mov"))
154
  ]
155
  logger.info(f"Found {len(video_files)} video files in repo")
156
+
157
  for vf in video_files:
158
  filename = Path(vf).name
159
  dest = VIDEOS_DIR / filename
 
170
  logger.error(f"Error downloading videos: {e}")
171
 
172
 
173
+ # --- API: list idle videos ---
 
 
 
174
  @app.get("/api/videos")
175
  async def list_videos():
176
  if not VIDEOS_DIR.exists():
 
182
  return JSONResponse({"videos": videos})
183
 
184
 
185
+ # --- API: stream a video file ---
186
  @app.get("/api/stream/{filename}")
187
  async def stream_video(filename: str):
188
+ # Check both idle videos and lipsync output
189
  video_path = None
190
  for search_dir in [VIDEOS_DIR, LIPSYNC_DIR, TTS_DIR]:
191
  candidate = search_dir / filename
192
  if candidate.exists() and candidate.is_file():
193
  video_path = candidate
194
  break
195
+
196
  if not video_path:
197
  raise HTTPException(status_code=404, detail="Video not found")
198
 
 
205
  yield chunk
206
 
207
  return StreamingResponse(
208
+ iter_file(),
209
+ media_type=mime_type,
210
  headers={"Content-Length": str(file_size), "Accept-Ranges": "bytes"},
211
  )
212
 
213
 
214
+ # --- API: stream audio file ---
215
  @app.get("/api/audio/{filename}")
216
  async def stream_audio(filename: str):
217
  audio_path = TTS_DIR / filename
 
227
  yield chunk
228
 
229
  return StreamingResponse(
230
+ iter_file(),
231
+ media_type=mime_type,
232
  headers={"Content-Length": str(file_size)},
233
  )
234
 
235
 
236
+ # --- API: chat endpoint (returns text immediately, then streams lipsync chunks) ---
237
  @app.post("/api/chat")
238
  async def chat(request: Request):
239
+ """
240
+ Step 1: LLM generates full response text.
241
+ Step 2: Returns text immediately so frontend can show it.
242
+ Step 3: Frontend then calls /api/chat/generate to get lipsync chunks via SSE.
243
+ """
244
  body = await request.json()
245
  user_text = body.get("text", "").strip()
246
+
247
  if not user_text:
248
  raise HTTPException(status_code=400, detail="No text provided")
249
 
250
  logger.info(f"[CHAT] User: {user_text}")
251
 
252
+ # 1. LLM
253
  from llm import generate_darwin_response
254
  llm_result = generate_darwin_response(user_text)
255
  reply_text = llm_result['text']
256
  logger.info(f"[CHAT] Darwin: {reply_text}")
257
 
258
+ # Split into sentences (by period only, not commas)
259
+ import re
260
+ raw_sentences = re.split(r'(?<=\.)\s+', reply_text)
261
+ sentences = [s.strip() for s in raw_sentences if s.strip()]
262
+ # If no periods found, treat whole text as one chunk
263
+ if not sentences:
264
+ sentences = [reply_text]
265
+
266
+ return JSONResponse({
267
+ "text": reply_text,
268
+ "emotion": llm_result.get('emotion', 'neutral'),
269
+ "sentences": sentences,
270
+ })
271
+
272
+
273
+ @app.post("/api/chat/generate")
274
+ async def chat_generate(request: Request):
275
+ """
276
+ SSE endpoint: receives a sentence, generates TTS + lipsync, returns result.
277
+ Called once per sentence by the frontend.
278
+ """
279
+ body = await request.json()
280
+ sentence = body.get("sentence", "").strip()
281
+
282
+ if not sentence:
283
+ raise HTTPException(status_code=400, detail="No sentence provided")
284
+
285
+ logger.info(f"[GEN] Sentence: {sentence[:60]}...")
286
+
287
+ # 1. TTS
288
  from tts import generate_audio
289
+ audio_path = generate_audio(sentence)
290
  audio_url = None
291
  audio_duration = 0
292
 
293
  if audio_path and os.path.exists(audio_path):
294
  audio_filename = os.path.basename(audio_path)
295
  audio_url = f"/api/audio/{audio_filename}"
296
+
297
  try:
298
  result = subprocess.run(
299
  ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
 
304
  except Exception:
305
  audio_duration = 3.0
306
 
307
+ # 2. Lipsync
308
+ lipsync_video_url = None
309
  if FLOAT_ENABLED and audio_path and os.path.exists(audio_path):
310
  try:
311
  from float_lipsync import get_lipsync
312
  lipsync = get_lipsync()
313
  if lipsync.ready:
314
+ logger.info(f"[GEN] Running FLOAT lipsync...")
315
+ lipsync_path = lipsync.generate(audio_path)
316
+ if lipsync_path and os.path.exists(lipsync_path):
317
+ lipsync_filename = os.path.basename(lipsync_path)
318
+ lipsync_video_url = f"/api/stream/{lipsync_filename}"
319
+ logger.info(f"[GEN] Lipsync video: {lipsync_video_url}")
 
 
 
 
320
  except Exception as e:
321
+ logger.error(f"[GEN] Lipsync failed: {e}", exc_info=True)
322
 
323
  return JSONResponse({
324
+ "sentence": sentence,
 
325
  "audio_url": audio_url,
326
  "audio_duration": audio_duration,
327
+ "lipsync_video_url": lipsync_video_url,
328
  })
329
 
330
 
331
+ # --- API: reset conversation ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  @app.post("/api/reset")
333
  async def reset_chat():
334
  from llm import reset_conversation
 
336
  return JSONResponse({"status": "ok"})
337
 
338
 
339
+ # --- Main page ---
 
 
340
  @app.get("/", response_class=HTMLResponse)
341
  async def index():
342
  return HTML_PAGE
 
351
  <title>Darwin Avatar Chatbot</title>
352
  <style>
353
  * { margin: 0; padding: 0; box-sizing: border-box; }
 
354
  body {
355
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
356
  background: #0a0f1c;
 
360
  flex-direction: column;
361
  overflow: hidden;
362
  }
363
+ /* --- LAYOUT --- */
364
  .app-container {
365
  display: flex;
366
  flex-direction: column;
 
371
  padding: 1rem;
372
  gap: 0.75rem;
373
  }
374
+ /* --- VIDEO PLAYER --- */
 
375
  .video-section {
376
  position: relative;
377
  width: 100%;
 
385
  align-items: center;
386
  justify-content: center;
387
  }
388
+ .video-container {
389
+ position: relative;
390
+ width: 100%;
391
+ height: 100%;
392
+ }
393
  .video-container video {
394
+ width: 100%;
395
+ height: 100%;
396
+ object-fit: contain;
397
+ display: block;
398
  }
399
  #videoA, #videoB {
400
+ position: absolute;
401
+ top: 0; left: 0;
402
+ width: 100%; height: 100%;
403
+ object-fit: contain;
404
+ transition: opacity 0.25s ease;
405
  }
406
  #videoA { z-index: 1; opacity: 1; }
407
  #videoB { z-index: 0; opacity: 0; }
408
  .video-status {
409
+ position: absolute;
410
+ bottom: 8px;
411
+ right: 12px;
412
+ font-size: 0.7rem;
413
+ color: rgba(255,255,255,0.4);
414
+ background: rgba(0,0,0,0.5);
415
+ padding: 2px 8px;
416
+ border-radius: 4px;
417
+ z-index: 10;
418
  }
419
+ /* --- CHAT LOG --- */
 
420
  .chat-section {
421
+ flex: 1;
422
+ display: flex;
423
+ flex-direction: column;
424
+ min-height: 0;
425
  background: rgba(15, 23, 42, 0.6);
426
  border: 1px solid rgba(59, 130, 246, 0.15);
427
+ border-radius: 12px;
428
+ overflow: hidden;
429
  }
430
  .chat-log {
431
+ flex: 1;
432
+ overflow-y: auto;
433
+ padding: 1rem;
434
+ display: flex;
435
+ flex-direction: column;
436
+ gap: 0.5rem;
437
  }
438
  .chat-log::-webkit-scrollbar { width: 6px; }
439
+ .chat-log::-webkit-scrollbar-track { background: transparent; }
440
  .chat-log::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; }
441
+ /* Message bubbles */
442
  .msg { display: flex; width: 100%; }
443
  .msg.user { justify-content: flex-end; }
444
  .msg.bot { justify-content: flex-start; }
445
  .bubble {
446
+ max-width: 85%;
447
+ padding: 10px 14px;
448
+ border-radius: 12px;
449
+ word-wrap: break-word;
450
+ font-size: 0.9rem;
451
+ line-height: 1.4;
452
  }
453
  .bubble.user {
454
+ background: linear-gradient(135deg, #1e40af, #3b82f6);
455
+ color: #fff;
456
  border-bottom-right-radius: 4px;
457
  }
458
  .bubble.bot {
459
  background: rgba(30, 41, 59, 0.8);
460
+ border: 1px solid rgba(59, 130, 246, 0.2);
461
+ color: #e2e8f0;
462
  border-bottom-left-radius: 4px;
463
  }
464
+ .bubble.bot .label { color: #60a5fa; font-weight: 600; font-size: 0.8rem; margin-bottom: 2px; }
465
+ .bubble.user .label { color: rgba(255,255,255,0.7); font-weight: 600; font-size: 0.8rem; margin-bottom: 2px; }
466
+ .bubble.typing {
467
+ color: #64748b;
468
+ font-style: italic;
469
+ }
470
  .bubble.error {
471
  background: rgba(127, 29, 29, 0.5);
472
+ border-color: rgba(239, 68, 68, 0.3);
473
+ color: #fca5a5;
474
+ }
475
+ @keyframes dots {
476
+ 0%, 20% { content: ''; }
477
+ 40% { content: '.'; }
478
+ 60% { content: '..'; }
479
+ 80%, 100% { content: '...'; }
480
+ }
481
+ .typing-dots::after {
482
+ content: '';
483
+ animation: dots 1.5s infinite;
484
  }
 
 
485
  .streaming-cursor::after {
486
+ content: '▊';
487
+ animation: blink 0.7s infinite;
488
+ color: #60a5fa;
489
  }
490
+ @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
491
+ /* --- INPUT BAR --- */
 
492
  .input-bar {
493
+ display: flex;
494
+ gap: 0.5rem;
495
+ padding: 0.75rem 1rem;
496
  background: rgba(15, 23, 42, 0.8);
497
  border-top: 1px solid rgba(59, 130, 246, 0.1);
498
  }
499
  .input-bar input {
500
+ flex: 1;
501
+ background: rgba(30, 41, 59, 0.8);
502
+ border: 1px solid rgba(59, 130, 246, 0.25);
503
+ border-radius: 8px;
504
+ padding: 10px 14px;
505
+ color: #e2e8f0;
506
+ font-size: 0.9rem;
507
+ outline: none;
508
+ transition: border-color 0.2s;
509
+ }
510
+ .input-bar input:focus {
511
+ border-color: #3b82f6;
512
  }
 
513
  .input-bar input::placeholder { color: #64748b; }
514
  .input-bar button {
515
+ padding: 10px 20px;
516
+ border: none;
517
+ border-radius: 8px;
518
+ font-size: 0.9rem;
519
+ cursor: pointer;
520
+ transition: all 0.15s;
521
+ font-weight: 500;
522
+ }
523
+ .btn-send {
524
+ background: #3b82f6;
525
+ color: #fff;
526
  }
 
527
  .btn-send:hover { background: #2563eb; }
528
  .btn-send:disabled { background: #334155; color: #64748b; cursor: not-allowed; }
529
  .btn-reset {
530
+ background: rgba(100, 116, 139, 0.3);
531
+ color: #94a3b8;
532
+ border: 1px solid rgba(100, 116, 139, 0.3);
533
  }
534
+ .btn-reset:hover { background: rgba(100, 116, 139, 0.5); }
535
  </style>
536
  </head>
537
  <body>
538
  <div class="app-container">
539
+ <!-- VIDEO PLAYER with crossfade -->
540
  <div class="video-section">
541
  <div class="video-container">
542
  <video id="videoA" muted autoplay playsinline></video>
 
544
  </div>
545
  <div class="video-status" id="videoStatus">Loading...</div>
546
  </div>
547
+ <!-- CHAT -->
548
  <div class="chat-section">
549
  <div class="chat-log" id="chatLog"></div>
550
  <div class="input-bar">
551
+ <input type="text" id="chatInput" placeholder="Ask Darwin something..."
552
+ autocomplete="off" />
553
  <button class="btn-send" id="btnSend">Send</button>
554
+ <button class="btn-reset" id="btnReset" title="Reset conversation">↻</button>
555
  </div>
556
  </div>
557
  </div>
 
558
  <script>
559
  // ======================================================================
560
  // STATE
 
564
  let isTransitioning = false;
565
  let isProcessing = false;
566
  let lastPlayed = null;
 
 
 
567
  const videoA = document.getElementById('videoA');
568
  const videoB = document.getElementById('videoB');
569
  const videoStatus = document.getElementById('videoStatus');
 
571
  const chatInput = document.getElementById('chatInput');
572
  const btnSend = document.getElementById('btnSend');
573
  const btnReset = document.getElementById('btnReset');
 
574
  // ======================================================================
575
+ // VIDEO: Crossfade System
576
  // ======================================================================
577
  function getActiveVideo() { return currentVideo === 'A' ? videoA : videoB; }
578
  function getInactiveVideo() { return currentVideo === 'A' ? videoB : videoA; }
579
+ function crossfadeTo(videoUrl, isMuted) {
580
+ if (isTransitioning) return;
 
 
 
 
581
  isTransitioning = true;
582
  const prev = getActiveVideo();
583
  const next = getInactiveVideo();
584
+ // Set muted state (idle=muted, lipsync=unmuted if audio separate)
585
+ next.muted = (isMuted !== false);
586
  next.src = videoUrl;
587
  next.load();
 
588
  next.onloadeddata = function() {
589
  next.style.zIndex = '2';
590
  prev.style.zIndex = '1';
591
  next.style.opacity = '0';
592
  next.play().then(() => {
593
+ // Fade in the new video
594
  next.style.opacity = '1';
595
  setTimeout(() => {
596
  prev.style.opacity = '0';
 
601
  currentVideo = currentVideo === 'A' ? 'B' : 'A';
602
  isTransitioning = false;
603
  }, 300);
604
+ }).catch(err => {
605
+ console.error('[VIDEO] Play failed:', err);
606
+ isTransitioning = false;
607
+ // Retry once on autoplay failure
608
  next.muted = true;
609
  next.play().then(() => {
610
  next.style.opacity = '1';
611
  setTimeout(() => {
612
+ prev.style.opacity = '0';
613
+ prev.pause();
614
+ prev.src = '';
615
+ prev.style.zIndex = '0';
616
+ next.style.zIndex = '1';
617
  currentVideo = currentVideo === 'A' ? 'B' : 'A';
618
  isTransitioning = false;
619
  }, 300);
620
+ }).catch(e => {
621
+ console.error('[VIDEO] Muted retry also failed:', e);
622
+ isTransitioning = false;
623
+ });
624
  });
625
  };
626
+ next.onerror = function() {
627
+ console.error('[VIDEO] Load failed:', videoUrl);
628
+ isTransitioning = false;
629
+ };
630
  }
 
631
  function pickRandomIdle() {
632
  if (videos.length === 0) return null;
633
  if (videos.length === 1) return videos[0];
634
  let pick;
635
+ do {
636
+ pick = videos[Math.floor(Math.random() * videos.length)];
637
+ } while (pick.filename === lastPlayed && videos.length > 1);
638
  return pick;
639
  }
 
640
  function playNextIdle() {
 
 
 
 
 
 
 
 
641
  const clip = pickRandomIdle();
642
  if (!clip) return;
643
  lastPlayed = clip.filename;
644
  videoStatus.textContent = 'idle: ' + clip.name;
645
  crossfadeTo('/api/stream/' + encodeURIComponent(clip.filename), true);
646
  }
647
+ // When active video ends → play next idle OR next queued lipsync
648
+ videoA.addEventListener('ended', () => { if (currentVideo === 'A') onVideoEnded(); });
649
+ videoB.addEventListener('ended', () => { if (currentVideo === 'B') onVideoEnded(); });
650
+ let lipsyncQueue = [];
651
+ let playingLipsync = false;
652
+ function onVideoEnded() {
653
+ if (lipsyncQueue.length > 0 && !playingLipsync) {
654
+ playNextLipsync();
655
+ } else if (!playingLipsync) {
656
+ playNextIdle();
657
+ }
658
+ }
659
+ function playNextLipsync() {
660
+ if (lipsyncQueue.length === 0) {
661
+ playingLipsync = false;
662
+ playNextIdle();
663
+ return;
664
+ }
665
+ playingLipsync = true;
666
+ const item = lipsyncQueue.shift();
667
+ videoStatus.textContent = 'speaking...';
668
+ // Play audio
669
+ if (item.audio_url) {
670
+ const audio = new Audio(item.audio_url);
671
+ audio.play().catch(e => console.warn('[AUDIO] Play failed:', e));
672
+ }
673
+ if (item.lipsync_video_url) {
674
+ crossfadeTo(item.lipsync_video_url, true);
675
+ // The 'ended' event on the video will trigger onVideoEnded → playNextLipsync
676
+ // But we need to set playingLipsync=false when THIS lipsync video ends
677
+ const checkEnd = () => {
678
+ const active = getActiveVideo();
679
+ // Wait for crossfade to complete, then listen for ended
680
+ setTimeout(() => {
681
+ const nowActive = getActiveVideo();
682
+ const onEnd = () => {
683
+ nowActive.removeEventListener('ended', onEnd);
684
+ playingLipsync = false;
685
+ onVideoEnded(); // chain to next
686
+ };
687
+ nowActive.addEventListener('ended', onEnd);
688
+ }, 500);
689
+ };
690
+ checkEnd();
691
+ } else {
692
+ // No lipsync video, just play audio over idle, then move to next
693
+ if (item.audio_url) {
694
+ const waitMs = (item.audio_duration || 3) * 1000;
695
+ setTimeout(() => {
696
+ playingLipsync = false;
697
+ onVideoEnded();
698
+ }, waitMs);
699
+ } else {
700
+ playingLipsync = false;
701
+ onVideoEnded();
702
+ }
703
+ }
704
+ }
705
  // ======================================================================
706
+ // CHAT: Message rendering
707
  // ======================================================================
708
  let msgCounter = 0;
709
+ function addMessage(role, text, extraClass = '') {
710
+ const id = `msg_${msgCounter++}`;
 
711
  const wrapper = document.createElement('div');
712
+ wrapper.className = `msg ${role}`;
713
  const bubble = document.createElement('div');
714
+ bubble.className = `bubble ${role} ${extraClass}`;
715
  bubble.id = id;
716
  const label = document.createElement('div');
717
  label.className = 'label';
 
724
  wrapper.appendChild(bubble);
725
  chatLog.appendChild(wrapper);
726
  chatLog.scrollTop = chatLog.scrollHeight;
727
+ return { id, contentEl: content, bubbleEl: bubble };
728
  }
729
+ function addTypingIndicator() {
730
+ const { id, contentEl, bubbleEl } = addMessage('bot', '', 'typing');
731
+ contentEl.className = 'content typing-dots';
732
+ contentEl.textContent = 'thinking';
733
+ return { id, contentEl, bubbleEl };
 
 
 
 
 
734
  }
735
+ function streamText(contentEl, text, durationMs) {
736
+ contentEl.className = 'content streaming-cursor';
737
+ contentEl.textContent = '';
738
+ let i = 0;
739
+ const delay = durationMs / text.length;
740
+ const interval = setInterval(() => {
741
+ if (i < text.length) {
742
+ contentEl.textContent += text[i];
743
+ i++;
744
+ chatLog.scrollTop = chatLog.scrollHeight;
745
+ } else {
746
+ clearInterval(interval);
747
+ contentEl.classList.remove('streaming-cursor');
 
 
 
 
 
 
 
 
 
 
 
 
 
748
  }
749
+ }, delay);
 
750
  }
 
751
  // ======================================================================
752
+ // CHAT: Send message
753
  // ======================================================================
754
  async function sendMessage() {
755
  const text = chatInput.value.trim();
756
  if (!text || isProcessing) return;
 
757
  isProcessing = true;
758
  btnSend.disabled = true;
759
  chatInput.value = '';
760
+ // Show user message
761
  addMessage('user', text);
762
+ // Show typing indicator
763
+ const typing = addTypingIndicator();
 
 
764
  try {
765
+ // Step 1: Get LLM response (fast - just text)
766
  const res = await fetch('/api/chat', {
767
  method: 'POST',
768
  headers: { 'Content-Type': 'application/json' },
769
+ body: JSON.stringify({ text })
770
  });
771
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
772
  const data = await res.json();
773
+ // Show the text immediately
 
774
  typing.bubbleEl.classList.remove('typing');
775
  typing.contentEl.classList.remove('typing-dots');
776
+ typing.contentEl.textContent = data.text;
777
+ // Re-enable input immediately so user can keep chatting
778
+ isProcessing = false;
779
+ btnSend.disabled = false;
780
+ chatInput.focus();
781
+ // Step 2: Generate TTS + lipsync for each sentence in background
782
+ const sentences = data.sentences || [data.text];
783
+ for (const sentence of sentences) {
784
+ try {
785
+ const genRes = await fetch('/api/chat/generate', {
786
+ method: 'POST',
787
+ headers: { 'Content-Type': 'application/json' },
788
+ body: JSON.stringify({ sentence })
789
+ });
790
+ if (!genRes.ok) continue;
791
+ const chunk = await genRes.json();
792
+ // Queue the lipsync chunk
793
+ lipsyncQueue.push(chunk);
794
+ // If nothing is currently playing lipsync, start
795
+ if (!playingLipsync) {
796
+ playNextLipsync();
797
+ }
798
+ } catch (e) {
799
+ console.error('[CHAT] Chunk generation failed:', e);
800
+ }
801
  }
 
802
  } catch (err) {
803
  typing.bubbleEl.classList.remove('typing');
804
  typing.bubbleEl.classList.add('error');
805
  typing.contentEl.classList.remove('typing-dots');
806
  typing.contentEl.textContent = 'Error: ' + err.message;
807
+ isProcessing = false;
808
+ btnSend.disabled = false;
809
  }
 
 
 
 
810
  }
 
811
  btnSend.addEventListener('click', sendMessage);
812
  chatInput.addEventListener('keydown', (e) => {
813
+ if (e.key === 'Enter' && !e.shiftKey) {
814
+ e.preventDefault();
815
+ sendMessage();
816
+ }
817
  });
 
818
  btnReset.addEventListener('click', async () => {
819
  await fetch('/api/reset', { method: 'POST' });
820
  chatLog.innerHTML = '';
821
  addMessage('bot', 'Ah, a fresh start! How may I assist you, my good fellow?');
822
  });
 
823
  // ======================================================================
824
  // INIT
825
  // ======================================================================
 
834
  }
835
  videos = data.videos;
836
  videoStatus.textContent = videos.length + ' idle clips loaded';
837
+ // Start idle loop
838
  playNextIdle();
839
+ // Welcome message
840
  addMessage('bot',
841
  'Good day! I am Charles Darwin, er, recreated in this curious digital form. ' +
842
  'Do feel free to ask me anything, umm, about the natural world or otherwise.'
 
845
  videoStatus.textContent = 'Error: ' + e.message;
846
  }
847
  }
 
848
  init();
849
  </script>
850
  </body>