akshay4 commited on
Commit
52ea3bd
·
verified ·
1 Parent(s): 42828b4

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. app.py +64 -48
  2. pyproject.toml +2 -0
  3. uv.lock +0 -0
  4. witgym/config.py +2 -2
  5. witgym/debug_render.py +1 -1
  6. witgym/tts.py +42 -28
app.py CHANGED
@@ -1114,35 +1114,40 @@ body.wg-light-mode footer { display: none !important; }
1114
  100% { opacity: 0; }
1115
  }
1116
 
1117
- /* ── Drill buttons — modern pill chips ──────────────────────────────────── */
1118
- .wg-drill-btn button {
1119
- width: 100%; border-radius: 50px !important; text-align: center !important;
1120
- font-family: 'Bebas Neue', sans-serif !important;
1121
- font-size: 0.78rem !important; letter-spacing: 0.14em !important;
1122
- padding: 0.42rem 0.75rem !important;
1123
- transition: border-color .15s, box-shadow .15s, transform .1s !important;
 
 
 
 
 
 
1124
  }
1125
- .wg-drill-btn:first-of-type button, .wg-drill-btn button:first-child { /* ⚡ Sharpen */
1126
- border-color: rgba(245,197,24,0.45) !important; color: #fcd34d !important;
1127
- background: rgba(245,197,24,0.06) !important;
1128
  }
1129
- .wg-drill-btn:first-of-type button:hover { border-color: #f5c518 !important; box-shadow: 0 0 10px rgba(245,197,24,0.25) !important; }
1130
- .wg-drill-label {
1131
- font-family: 'Bebas Neue', sans-serif; letter-spacing: 0.2em;
1132
- font-size: 0.72rem; color: var(--wg-muted);
1133
- border-bottom: 1px solid var(--wg-border); padding-bottom: 0.3rem;
1134
  }
1135
- #wg-practice .wg-drill-label { color: #9e9288 !important; border-color: #e0d8cc !important; }
1136
- #wg-practice .wg-drill-btn button {
1137
- background: rgba(45,106,79,0.05) !important;
1138
- border-color: rgba(45,106,79,0.3) !important;
1139
- color: #2d6a4f !important;
1140
  }
1141
- #wg-practice .wg-drill-btn button:hover {
1142
- border-color: #2d6a4f !important;
1143
- box-shadow: 0 0 8px rgba(45,106,79,0.2) !important;
1144
- transform: scale(1.02) !important;
1145
  }
 
1146
 
1147
  /* ── Sci-fi flicker input overlay ────────────────────────────────────────── */
1148
  .wg-flicker-wrap { position: relative; }
@@ -1510,14 +1515,28 @@ window.wgPlayConfirm = function() {
1510
  /* ── Update practice header with selected coach ─────────────────────────── */
1511
  window.wgUpdateCoachHeader = function() {
1512
  var c = window._wgSelectedChar;
1513
- if (!c || c.name === 'AI') return; // keep default mug + WITGYM text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1514
  var mugWrap = document.querySelector('#wg-coach-avatar-wrap svg.wg-mascot-like, #wg-coach-avatar-wrap svg');
1515
  if (mugWrap) mugWrap.style.display = 'none';
1516
  var img = document.getElementById('wg-coach-avatar');
1517
  if (img) {
1518
  img.src = c.avatarUrl || '';
1519
  img.alt = c.name;
1520
- if (c.fallbackUrl) img.onerror = function() { this.onerror=null; this.src=c.fallbackUrl; };
1521
  img.style.display = 'block';
1522
  }
1523
  var nameEl = document.getElementById('wg-coach-name');
@@ -1875,6 +1894,8 @@ def _bg_warmup():
1875
  global _warmup_error
1876
  try:
1877
  _get_shared()
 
 
1878
  except Exception as e:
1879
  logger.exception("Background warmup failed")
1880
  _warmup_error = _format_warmup_error(e)
@@ -2006,6 +2027,18 @@ _MUG_SVG = (
2006
  _ROAST_FLOAT_HTML = '<div id="wg-roast-host" aria-hidden="true"></div>'
2007
 
2008
 
 
 
 
 
 
 
 
 
 
 
 
 
2009
  def _practice_header_html() -> str:
2010
  # IDs wg-coach-avatar, wg-coach-name, wg-coach-role are injected by wgUpdateCoachHeader() JS
2011
  # on start_btn click — no Gradio re-render needed.
@@ -2095,11 +2128,10 @@ def practice(user_input: str, session, show_debug: bool, progress=gr.Progress())
2095
  if audio_url:
2096
  event.response.tts_audio_url = audio_url
2097
  session["traces"][-1] = (user_input, event.response)
2098
- yield (
2099
- format_transcript_html(session["traces"], show_debug=show_debug, selected_char=selected_char),
2100
- gr.update(value="", interactive=True),
2101
- session,
2102
- )
2103
  return
2104
  yield (
2105
  format_transcript_with_streaming(session["traces"], stream_state, show_debug=show_debug, selected_char=selected_char),
@@ -2219,16 +2251,7 @@ def build_ui():
2219
  outputs=[transcript, user_input, session_state],
2220
  show_progress="full", show_progress_on=submit_btn,
2221
  )
2222
- gr.HTML('<div class="wg-sidebar-label wg-drill-label" style="margin-top:.85rem">Coach Drills</div>')
2223
- drill_btns = []
2224
- _DRILL_ICONS = {"sharpen it": "⚡", "different angle": "↗", "explain the joke": "🔍"}
2225
- for label, drill_text in DRILL_ACTIONS:
2226
- icon = _DRILL_ICONS.get(label, "↻")
2227
- db = gr.Button(
2228
- f"{icon} {label}", size="sm", variant="secondary",
2229
- elem_classes=["wg-drill-btn"],
2230
- )
2231
- drill_btns.append((db, drill_text))
2232
 
2233
  # ── Event wiring ──────────────────────────────────────────
2234
 
@@ -2264,13 +2287,6 @@ def build_ui():
2264
  inputs=[show_debug_state],
2265
  outputs=[transcript, user_input, session_state],
2266
  )
2267
- for db, drill_text in drill_btns:
2268
- db.click(
2269
- fn=practice,
2270
- inputs=[gr.State(drill_text), session_state, show_debug_state],
2271
- outputs=[transcript, user_input, session_state],
2272
- show_progress="full", show_progress_on=submit_btn,
2273
- )
2274
  demo.load(fn=_on_page_load, outputs=transcript, show_progress="hidden")
2275
 
2276
  return demo
 
1114
  100% { opacity: 0; }
1115
  }
1116
 
1117
+ /* ── Sidebar bubble head ─────────────────────────────────────────────────── */
1118
+ @keyframes wg-bubble-bob {
1119
+ 0%, 100% { transform: translateY(0) rotate(0deg); }
1120
+ 50% { transform: translateY(-6px) rotate(0.4deg); }
1121
+ }
1122
+ .wg-bubble-head {
1123
+ display: flex; flex-direction: column; align-items: center;
1124
+ padding: 1.4rem 0.5rem 0.6rem; user-select: none;
1125
+ }
1126
+ .wg-bubble-head-inner {
1127
+ animation: wg-bubble-bob 2.8s ease-in-out infinite;
1128
+ transition: transform 0.22s ease;
1129
+ cursor: pointer;
1130
  }
1131
+ .wg-bubble-head-inner:hover {
1132
+ animation-play-state: paused;
1133
+ transform: scale(1.1) rotate(5deg) !important;
1134
  }
1135
+ .wg-bubble-avatar-large {
1136
+ width: 90px; height: 90px; border-radius: 50%;
1137
+ border: 2.5px solid var(--wg-green);
1138
+ box-shadow: 0 0 18px rgba(74,222,128,0.22), 0 3px 10px rgba(0,0,0,0.35);
1139
+ object-fit: cover; display: block;
1140
  }
1141
+ .wg-bubble-char-name {
1142
+ font-family: 'Bebas Neue', sans-serif; letter-spacing: 0.18em;
1143
+ font-size: 0.68rem; color: var(--wg-muted);
1144
+ margin-top: 0.5rem; text-align: center;
 
1145
  }
1146
+ #wg-practice .wg-bubble-avatar-large {
1147
+ border-color: #2d6a4f;
1148
+ box-shadow: 0 0 16px rgba(45,106,79,0.18), 0 2px 8px rgba(0,0,0,0.1);
 
1149
  }
1150
+ #wg-practice .wg-bubble-char-name { color: #9e9288; }
1151
 
1152
  /* ── Sci-fi flicker input overlay ────────────────────────────────────────── */
1153
  .wg-flicker-wrap { position: relative; }
 
1515
  /* ── Update practice header with selected coach ─────────────────────────── */
1516
  window.wgUpdateCoachHeader = function() {
1517
  var c = window._wgSelectedChar;
1518
+ if (!c) return;
1519
+
1520
+ // Always update sidebar bubble head regardless of character type
1521
+ var bubbleImg = document.getElementById('wg-bubble-avatar-large');
1522
+ var bubbleName = document.getElementById('wg-bubble-char-name');
1523
+ if (bubbleImg) {
1524
+ bubbleImg.src = c.avatarUrl || '';
1525
+ bubbleImg.alt = c.name;
1526
+ if (c.fallbackUrl) bubbleImg.onerror = function() { this.onerror = null; this.src = c.fallbackUrl; };
1527
+ bubbleImg.style.display = 'block';
1528
+ }
1529
+ if (bubbleName) bubbleName.textContent = c.name === 'AI' ? 'AI COACH' : c.name.toUpperCase() + ' COACH';
1530
+
1531
+ if (c.name === 'AI') return; // keep default mug + WITGYM text for practice bar header
1532
+
1533
  var mugWrap = document.querySelector('#wg-coach-avatar-wrap svg.wg-mascot-like, #wg-coach-avatar-wrap svg');
1534
  if (mugWrap) mugWrap.style.display = 'none';
1535
  var img = document.getElementById('wg-coach-avatar');
1536
  if (img) {
1537
  img.src = c.avatarUrl || '';
1538
  img.alt = c.name;
1539
+ if (c.fallbackUrl) img.onerror = function() { this.onerror = null; this.src = c.fallbackUrl; };
1540
  img.style.display = 'block';
1541
  }
1542
  var nameEl = document.getElementById('wg-coach-name');
 
1894
  global _warmup_error
1895
  try:
1896
  _get_shared()
1897
+ from witgym.tts import _get_pipeline
1898
+ _get_pipeline() # pre-warm Kokoro so first TTS call isn't slow
1899
  except Exception as e:
1900
  logger.exception("Background warmup failed")
1901
  _warmup_error = _format_warmup_error(e)
 
2027
  _ROAST_FLOAT_HTML = '<div id="wg-roast-host" aria-hidden="true"></div>'
2028
 
2029
 
2030
+ def _sidebar_bubble_head_html() -> str:
2031
+ ai_src = char_avatar_svg("AI")
2032
+ return (
2033
+ '<div class="wg-bubble-head">'
2034
+ '<div class="wg-bubble-head-inner">'
2035
+ f'<img id="wg-bubble-avatar-large" class="wg-bubble-avatar-large" src="{ai_src}" alt="AI Coach"/>'
2036
+ '</div>'
2037
+ '<div class="wg-bubble-char-name" id="wg-bubble-char-name">AI COACH</div>'
2038
+ '</div>'
2039
+ )
2040
+
2041
+
2042
  def _practice_header_html() -> str:
2043
  # IDs wg-coach-avatar, wg-coach-name, wg-coach-role are injected by wgUpdateCoachHeader() JS
2044
  # on start_btn click — no Gradio re-render needed.
 
2128
  if audio_url:
2129
  event.response.tts_audio_url = audio_url
2130
  session["traces"][-1] = (user_input, event.response)
2131
+ final_html = format_transcript_html(session["traces"], show_debug=show_debug, selected_char=selected_char)
2132
+ # Strip audio from session so gr.State doesn't carry ~500KB per turn
2133
+ event.response.tts_audio_url = None
2134
+ yield (final_html, gr.update(value="", interactive=True), session)
 
2135
  return
2136
  yield (
2137
  format_transcript_with_streaming(session["traces"], stream_state, show_debug=show_debug, selected_char=selected_char),
 
2251
  outputs=[transcript, user_input, session_state],
2252
  show_progress="full", show_progress_on=submit_btn,
2253
  )
2254
+ gr.HTML(_sidebar_bubble_head_html())
 
 
 
 
 
 
 
 
 
2255
 
2256
  # ── Event wiring ──────────────────────────────────────────
2257
 
 
2287
  inputs=[show_debug_state],
2288
  outputs=[transcript, user_input, session_state],
2289
  )
 
 
 
 
 
 
 
2290
  demo.load(fn=_on_page_load, outputs=transcript, show_progress="hidden")
2291
 
2292
  return demo
pyproject.toml CHANGED
@@ -18,6 +18,8 @@ dependencies = [
18
  "datasets>=2.19.0",
19
  "sentencepiece>=0.2.0",
20
  "gradio>=5.0.0",
 
 
21
  ]
22
 
23
  [project.scripts]
 
18
  "datasets>=2.19.0",
19
  "sentencepiece>=0.2.0",
20
  "gradio>=5.0.0",
21
+ "kokoro>=0.9.2",
22
+ "soundfile>=0.14.0",
23
  ]
24
 
25
  [project.scripts]
uv.lock CHANGED
The diff for this file is too large to render. See raw diff
 
witgym/config.py CHANGED
@@ -107,9 +107,9 @@ HF_API_MAX_RETRIES = int(os.getenv("HF_API_MAX_RETRIES", "3"))
107
  TTS_ENABLED = os.getenv("TTS_ENABLED", "1").strip().lower() not in {"0", "false", "no"}
108
  TTS_MODEL_ID = os.getenv("TTS_MODEL_ID", "hexgrad/Kokoro-82M")
109
  TTS_AUDIO_FORMAT = os.getenv("TTS_AUDIO_FORMAT", "audio/flac")
110
- TTS_API_TIMEOUT = float(os.getenv("TTS_API_TIMEOUT", "10"))
111
  TTS_INFERENCE_PROVIDERS = [
112
  p.strip()
113
- for p in os.getenv("TTS_INFERENCE_PROVIDERS", "fal-ai,auto").split(",")
114
  if p.strip()
115
  ]
 
107
  TTS_ENABLED = os.getenv("TTS_ENABLED", "1").strip().lower() not in {"0", "false", "no"}
108
  TTS_MODEL_ID = os.getenv("TTS_MODEL_ID", "hexgrad/Kokoro-82M")
109
  TTS_AUDIO_FORMAT = os.getenv("TTS_AUDIO_FORMAT", "audio/flac")
110
+ TTS_API_TIMEOUT = float(os.getenv("TTS_API_TIMEOUT", "6"))
111
  TTS_INFERENCE_PROVIDERS = [
112
  p.strip()
113
+ for p in os.getenv("TTS_INFERENCE_PROVIDERS", "auto").split(",")
114
  if p.strip()
115
  ]
witgym/debug_render.py CHANGED
@@ -113,7 +113,7 @@ def _voice_gender(selected_char: str) -> str:
113
 
114
 
115
  def _allow_browser_voice(selected_char: str) -> str:
116
- return "true" if _voice_gender(selected_char) == "neutral" else "false"
117
 
118
 
119
  def _reply_actions_html() -> str:
 
113
 
114
 
115
  def _allow_browser_voice(selected_char: str) -> str:
116
+ return "true" # always allow browser TTS fallback for old turns that lost Kokoro audio
117
 
118
 
119
  def _reply_actions_html() -> str:
witgym/tts.py CHANGED
@@ -1,12 +1,13 @@
1
- """Minimal post-pipeline TTS helper using HF Inference Providers."""
2
 
3
  from __future__ import annotations
4
 
5
  import base64
6
- from functools import lru_cache
 
7
 
8
- from huggingface_hub import InferenceClient
9
- from huggingface_hub.errors import HfHubHTTPError, InferenceTimeoutError
10
  from loguru import logger
11
 
12
  from witgym import config
@@ -37,37 +38,50 @@ def _voice_for_character(character: str) -> str:
37
  return _FEMALE_VOICES["AI"]
38
 
39
 
40
- @lru_cache(maxsize=4)
41
- def _client(provider: str) -> InferenceClient:
42
- return InferenceClient(
43
- provider=provider,
44
- api_key=config.HF_TOKEN or None,
45
- timeout=config.TTS_API_TIMEOUT,
46
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
 
49
  def synthesize_line(text: str, character: str = "AI") -> str | None:
50
- """Return a data URL for generated audio, or None on failure."""
51
  if not config.TTS_ENABLED:
52
  return None
53
-
54
  text = (text or "").strip()
55
  if not text:
56
  return None
57
 
 
 
 
 
58
  voice = _voice_for_character(character or "AI")
59
- for provider in config.TTS_INFERENCE_PROVIDERS:
60
- try:
61
- audio = _client(provider).text_to_speech(
62
- text=text,
63
- model=config.TTS_MODEL_ID,
64
- extra_body={"voice": voice},
65
- )
66
- b64 = base64.b64encode(audio).decode("ascii")
67
- return f"data:{config.TTS_AUDIO_FORMAT};base64,{b64}"
68
- except (InferenceTimeoutError, HfHubHTTPError) as exc:
69
- logger.warning(f"TTS failed via provider={provider} voice={voice}: {exc}")
70
- except Exception as exc: # pragma: no cover - safety fallback for provider drift
71
- logger.warning(f"Unexpected TTS failure via provider={provider} voice={voice}: {exc}")
72
-
73
- return None
 
1
+ """Local Kokoro-82M TTS — runs on-device, no API calls, no provider dependency."""
2
 
3
  from __future__ import annotations
4
 
5
  import base64
6
+ import io
7
+ from threading import Lock
8
 
9
+ import numpy as np
10
+ import soundfile as sf
11
  from loguru import logger
12
 
13
  from witgym import config
 
38
  return _FEMALE_VOICES["AI"]
39
 
40
 
41
+ _pipeline = None
42
+ _pipeline_lock = Lock()
43
+
44
+
45
+ def _get_pipeline():
46
+ global _pipeline
47
+ if _pipeline is not None:
48
+ return _pipeline
49
+ with _pipeline_lock:
50
+ if _pipeline is not None:
51
+ return _pipeline
52
+ try:
53
+ from kokoro import KPipeline
54
+ logger.info("Loading Kokoro-82M pipeline (first call)…")
55
+ _pipeline = KPipeline(lang_code="a")
56
+ logger.info("Kokoro-82M ready.")
57
+ except Exception as exc:
58
+ logger.error(f"Failed to load Kokoro pipeline: {exc}")
59
+ _pipeline = None
60
+ return _pipeline
61
 
62
 
63
  def synthesize_line(text: str, character: str = "AI") -> str | None:
64
+ """Return a FLAC data URL for the text, or None on failure."""
65
  if not config.TTS_ENABLED:
66
  return None
 
67
  text = (text or "").strip()
68
  if not text:
69
  return None
70
 
71
+ pipeline = _get_pipeline()
72
+ if pipeline is None:
73
+ return None
74
+
75
  voice = _voice_for_character(character or "AI")
76
+ try:
77
+ chunks = [audio for _, _, audio in pipeline(text, voice=voice)]
78
+ if not chunks:
79
+ return None
80
+ audio = np.concatenate(chunks)
81
+ buf = io.BytesIO()
82
+ sf.write(buf, audio, 24000, format="FLAC")
83
+ b64 = base64.b64encode(buf.getvalue()).decode("ascii")
84
+ return f"data:audio/flac;base64,{b64}"
85
+ except Exception as exc:
86
+ logger.warning(f"Kokoro TTS failed voice={voice}: {exc}")
87
+ return None