Daniel McKnight NeonClary commited on
Commit
39dbe10
·
unverified ·
1 Parent(s): 070d12d

Support Voice Interaction (#32)

Browse files

* feat: add speech-to-text and text-to-speech functionality

Add /api/transcribe (STT via Whisper proxy), /api/tts (Google Translate TTS), and /api/voice status routes. Add microphone button to EnhancedChatInput, VoiceStatusContext provider, and VoiceToast component.

Made-with: Cursor

* Clean up implementation

* Refactor to simplify STT/TTS endpoint handling

* Remove unused VoiceToast.js

* Refactor `voice_router` API to remove `/api` prefix for consistency with other endpoints

* Pin added `markdown` dependency version

* Remove unused VoiceStatusContext file

* Refactor `LOG` to `logger` for consistency per review

* Remove unused variables

* Add docstrings per review comment

* Add actual voice service status checks with test coverage

* Cursor refactored test patching (original implementation also by Cursor)

* Add comment explaining 44-byte minimum segment length

---------

Co-authored-by: NeonClary <askclary@gmail.com>

Dockerfile CHANGED
@@ -9,9 +9,10 @@ ENV OVOS_CONFIG_FILENAME=neon.yaml
9
  ENV XDG_CONFIG_HOME=/config
10
 
11
  RUN apt-get update && \
12
- apt-get install -y \
13
  python3 \
14
- python3-pip
 
15
 
16
  # ---- Python dependencies (cached unless requirements.txt changes) ----------
17
  WORKDIR /ccai/multi_llm_chatbot_backend
@@ -31,6 +32,10 @@ COPY . .
31
 
32
  # ---- Backend target --------------------------------------------------------
33
  FROM base AS backend
 
 
 
 
34
  WORKDIR /ccai/multi_llm_chatbot_backend
35
  CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
36
 
 
9
  ENV XDG_CONFIG_HOME=/config
10
 
11
  RUN apt-get update && \
12
+ apt-get install -y --no-install-recommends \
13
  python3 \
14
+ python3-pip \
15
+ && rm -rf /var/lib/apt/lists/*
16
 
17
  # ---- Python dependencies (cached unless requirements.txt changes) ----------
18
  WORKDIR /ccai/multi_llm_chatbot_backend
 
32
 
33
  # ---- Backend target --------------------------------------------------------
34
  FROM base AS backend
35
+ # Required for /api/voice/transcribe (browser WebM/Opus → WAV for Whisper).
36
+ RUN apt-get update && \
37
+ apt-get install -y --no-install-recommends ffmpeg && \
38
+ rm -rf /var/lib/apt/lists/*
39
  WORKDIR /ccai/multi_llm_chatbot_backend
40
  CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
41
 
multi_llm_chatbot_backend/app/api/routes/__init__.py CHANGED
@@ -6,6 +6,7 @@ from .provider import router as provider_router
6
  from .debug import router as debug_router
7
  from .root import router as root_router
8
  from .phd_canvas import router as canvas_router
 
9
 
10
  router = APIRouter()
11
  router.include_router(chat_router)
@@ -14,4 +15,5 @@ router.include_router(session_router)
14
  router.include_router(provider_router)
15
  router.include_router(debug_router)
16
  router.include_router(root_router)
17
- router.include_router(canvas_router)
 
 
6
  from .debug import router as debug_router
7
  from .root import router as root_router
8
  from .phd_canvas import router as canvas_router
9
+ from .voice import router as voice_router
10
 
11
  router = APIRouter()
12
  router.include_router(chat_router)
 
15
  router.include_router(provider_router)
16
  router.include_router(debug_router)
17
  router.include_router(root_router)
18
+ router.include_router(canvas_router)
19
+ router.include_router(voice_router)
multi_llm_chatbot_backend/app/api/routes/voice.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import html as html_module
3
+ import logging
4
+ import re
5
+ import struct
6
+ import subprocess
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Dict, List, Optional
10
+ from urllib.parse import quote
11
+
12
+ import httpx
13
+ from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
14
+ from fastapi.responses import Response
15
+ from pydantic import BaseModel
16
+
17
+ from app.core.auth import get_current_active_user
18
+ from app.models.user import User
19
+ from app.config import get_settings
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ router = APIRouter()
24
+
25
+ voice_settings = get_settings().voice
26
+ TTS_BASE = voice_settings.tts_endpoint
27
+ STT_BASE = voice_settings.stt_endpoint
28
+
29
+ HTTP_TIMEOUT = 120
30
+ # Coqui uses GET /synthesize/{text}; keep chunks small for URL limits.
31
+ MAX_SYNTH_CHUNK = 200
32
+
33
+ _SECTION_HEADERS = re.compile(
34
+ r"\b(Thought|What to do|Next step)\s*[:.]?\s*", flags=re.IGNORECASE
35
+ )
36
+
37
+
38
+ class TTSRequest(BaseModel):
39
+ text: str
40
+
41
+
42
+ def _rough_spoken_text(raw: str) -> str:
43
+ """Light cleanup so model markdown is tolerable for TTS (no extra deps)."""
44
+ t = raw.strip()
45
+ t = re.sub(r"```[\s\S]*?```", " ", t)
46
+ t = re.sub(r"`([^`]+)`", r"\1", t)
47
+ t = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", t)
48
+ t = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", t)
49
+ t = re.sub(r"^#{1,6}\s+", "", t, flags=re.MULTILINE)
50
+ t = re.sub(r"[*_]{1,3}", "", t)
51
+ t = html_module.unescape(t)
52
+ t = _SECTION_HEADERS.sub(" ", t)
53
+ t = re.sub(r"\s+", " ", t).strip()
54
+ return t
55
+
56
+
57
+ def _text_chunks(text: str, max_len: int = MAX_SYNTH_CHUNK) -> List[str]:
58
+ text = text.strip()
59
+ if not text:
60
+ return []
61
+ out: List[str] = []
62
+ while text:
63
+ if len(text) <= max_len:
64
+ out.append(text)
65
+ break
66
+ cut = text.rfind(" ", 0, max_len)
67
+ if cut <= 0:
68
+ cut = max_len
69
+ piece = text[:cut].strip()
70
+ if piece:
71
+ out.append(piece)
72
+ text = text[cut:].strip()
73
+ return out
74
+
75
+
76
+ async def _synthesize_one(client: httpx.AsyncClient, chunk: str) -> Optional[bytes]:
77
+ url = f"{TTS_BASE}/synthesize/{quote(chunk, safe='')}"
78
+ try:
79
+ r = await client.get(url)
80
+ r.raise_for_status()
81
+ return r.content
82
+ except Exception as exc:
83
+ logger.warning("TTS chunk failed (%s chars): %s", len(chunk), exc)
84
+ return None
85
+
86
+
87
+ def _concat_wav(segments: List[bytes]) -> bytes:
88
+ if len(segments) == 1:
89
+ return segments[0]
90
+
91
+ pcm_parts: List[bytes] = []
92
+ first_header = b""
93
+
94
+ for i, seg in enumerate(segments):
95
+ # PCM WAV files begin with a 44-byte header; if the segment is shorter,
96
+ # then it cannot be valid WAV audio
97
+ if len(seg) < 44:
98
+ continue
99
+ if i == 0:
100
+ first_header = seg[:44]
101
+ data_offset = 44
102
+ idx = seg.find(b"data")
103
+ if idx != -1 and idx + 8 <= len(seg):
104
+ data_offset = idx + 8
105
+ pcm_parts.append(seg[data_offset:])
106
+
107
+ if not pcm_parts or not first_header:
108
+ return segments[0] if segments else b""
109
+
110
+ all_pcm = b"".join(pcm_parts)
111
+ pcm_len = len(all_pcm)
112
+
113
+ header = bytearray(first_header)
114
+ struct.pack_into("<I", header, 4, pcm_len + 36)
115
+ struct.pack_into("<I", header, 40, pcm_len)
116
+ return bytes(header) + all_pcm
117
+
118
+
119
+ def _convert_to_wav(audio_bytes: bytes, src_mime: str) -> bytes:
120
+ with tempfile.TemporaryDirectory() as tmp:
121
+ ext = "webm" if "webm" in (src_mime or "") else "ogg"
122
+ src = Path(tmp) / f"in.{ext}"
123
+ dst = Path(tmp) / "out.wav"
124
+ src.write_bytes(audio_bytes)
125
+ result = subprocess.run(
126
+ [
127
+ "ffmpeg",
128
+ "-y",
129
+ "-i",
130
+ str(src),
131
+ "-ar",
132
+ "16000",
133
+ "-ac",
134
+ "1",
135
+ "-f",
136
+ "wav",
137
+ str(dst),
138
+ ],
139
+ capture_output=True,
140
+ timeout=30,
141
+ )
142
+ if result.returncode != 0:
143
+ logger.warning(
144
+ "ffmpeg stderr: %s",
145
+ result.stderr.decode(errors="replace")[-500:],
146
+ )
147
+ raise RuntimeError("ffmpeg conversion failed")
148
+ return dst.read_bytes()
149
+
150
+
151
+ @router.get("/voice/status")
152
+ async def voice_status(
153
+ current_user: User = Depends(get_current_active_user),
154
+ ) -> Dict[str, bool]:
155
+ tts_ready = False
156
+ stt_ready = False
157
+ async with httpx.AsyncClient(timeout=5) as client:
158
+ if TTS_BASE not in ("", None):
159
+ try:
160
+ resp = await client.get(f"{TTS_BASE}/status")
161
+ tts_ready = resp.status_code == 200
162
+ except Exception:
163
+ tts_ready = False
164
+ if STT_BASE not in ("", None):
165
+ try:
166
+ resp = await client.get(f"{STT_BASE}/status")
167
+ stt_ready = resp.status_code == 200
168
+ except Exception:
169
+ stt_ready = False
170
+ return {"tts_ready": tts_ready, "stt_ready": stt_ready}
171
+
172
+
173
+ @router.post("/voice/transcribe")
174
+ async def transcribe_audio(
175
+ audio: UploadFile = File(...),
176
+ current_user: User = Depends(get_current_active_user),
177
+ ) -> Dict[str, str]:
178
+ """
179
+ Transcribe an uploaded audio file and return the text.
180
+ @param audio: The uploaded audio file (from a browser recording)
181
+ @param current_user: The authenticated user making the request
182
+ @return: A dictionary with the transcribed text under key "text"
183
+ """
184
+ contents = await audio.read()
185
+ if not contents:
186
+ return {"text": ""}
187
+
188
+ mime = audio.content_type or "audio/webm"
189
+ logger.info("STT: received %s bytes (%s)", len(contents), mime)
190
+
191
+ need_convert = "wav" not in mime.lower()
192
+ if need_convert:
193
+ try:
194
+ loop = asyncio.get_running_loop()
195
+ wav_bytes = await loop.run_in_executor(
196
+ None, _convert_to_wav, contents, mime
197
+ )
198
+ logger.info("STT: converted to WAV (%s bytes)", len(wav_bytes))
199
+ except Exception as e:
200
+ logger.error("STT conversion error: %s", e)
201
+ raise HTTPException(status_code=500, detail="Audio conversion failed")
202
+ else:
203
+ wav_bytes = contents
204
+
205
+ try:
206
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
207
+ resp = await client.post(
208
+ f"{STT_BASE}/stt",
209
+ content=wav_bytes,
210
+ headers={"Content-Type": "audio/wav"},
211
+ )
212
+ resp.raise_for_status()
213
+ text = resp.text.strip().strip('"')
214
+ logger.info("STT result: %r", text[:100])
215
+ return {"text": text}
216
+ except httpx.TimeoutException:
217
+ raise HTTPException(status_code=504, detail="STT service timed out")
218
+ except Exception as e:
219
+ logger.error("STT proxy error: %s", e)
220
+ raise HTTPException(status_code=502, detail="STT service unavailable")
221
+
222
+
223
+ @router.post("/voice/tts")
224
+ async def text_to_speech(
225
+ req: TTSRequest,
226
+ current_user: User = Depends(get_current_active_user),
227
+ ) -> Response:
228
+ """
229
+ Generate spoken audio for the input text
230
+ @param req: A TTSRequest containing the text to synthesize
231
+ @param current_user: The authenticated user making the request
232
+ @return: A Response containing the synthesized audio in WAV format
233
+ """
234
+ raw = req.text.strip()
235
+ if not raw:
236
+ raise HTTPException(status_code=400, detail="Text is required")
237
+
238
+ if len(raw) > 5000:
239
+ raw = raw[:5000]
240
+
241
+ spoken = _rough_spoken_text(raw)
242
+ chunks = _text_chunks(spoken)
243
+ logger.info(
244
+ "TTS: %s chunk(s) from %s input chars → %s spoken chars",
245
+ len(chunks),
246
+ len(req.text),
247
+ len(spoken),
248
+ )
249
+
250
+ try:
251
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
252
+ results = await asyncio.gather(
253
+ *[_synthesize_one(client, c) for c in chunks]
254
+ )
255
+ wav_segments = [r for r in results if r and len(r) > 44]
256
+
257
+ if not wav_segments:
258
+ raise HTTPException(
259
+ status_code=502, detail="TTS synthesis failed for all chunks"
260
+ )
261
+
262
+ combined = _concat_wav(wav_segments)
263
+ return Response(content=combined, media_type="audio/wav")
264
+ except HTTPException:
265
+ raise
266
+ except httpx.TimeoutException:
267
+ raise HTTPException(status_code=504, detail="TTS service timed out")
268
+ except Exception as e:
269
+ logger.error("TTS proxy error: %s", e)
270
+ raise HTTPException(status_code=502, detail="TTS service unavailable")
multi_llm_chatbot_backend/app/config.py CHANGED
@@ -293,6 +293,11 @@ class ToolsConfig(BaseModel):
293
  return cfg if isinstance(cfg, dict) else {}
294
 
295
 
 
 
 
 
 
296
  class AppSettings(BaseModel):
297
  """Top-level container that mirrors the YAML structure."""
298
  app: AppConfig = AppConfig()
@@ -306,6 +311,7 @@ class AppSettings(BaseModel):
306
  llm: LLMConfig = LLMConfig()
307
  rag: RAGConfig = RAGConfig()
308
  tools: ToolsConfig = ToolsConfig()
 
309
 
310
  # ------------------------------------------------------------------
311
  # Convenience helpers
@@ -443,4 +449,4 @@ def generate_persona_colors(name: str) -> dict:
443
  "bg_color": hsl_to_hex(h, 0.60, 0.95),
444
  "dark_color": hsl_to_hex(h, 0.70, 0.70),
445
  "dark_bg_color": hsl_to_hex(h, 0.65, 0.25),
446
- }
 
293
  return cfg if isinstance(cfg, dict) else {}
294
 
295
 
296
+ class VoiceConfig(BaseModel):
297
+ stt_endpoint: str = "https://whisper.neonaiservices.com"
298
+ tts_endpoint: str = "https://coqui.neonaiservices.com"
299
+
300
+
301
  class AppSettings(BaseModel):
302
  """Top-level container that mirrors the YAML structure."""
303
  app: AppConfig = AppConfig()
 
311
  llm: LLMConfig = LLMConfig()
312
  rag: RAGConfig = RAGConfig()
313
  tools: ToolsConfig = ToolsConfig()
314
+ voice: VoiceConfig = VoiceConfig()
315
 
316
  # ------------------------------------------------------------------
317
  # Convenience helpers
 
449
  "bg_color": hsl_to_hex(h, 0.60, 0.95),
450
  "dark_color": hsl_to_hex(h, 0.70, 0.70),
451
  "dark_bg_color": hsl_to_hex(h, 0.65, 0.25),
452
+ }
multi_llm_chatbot_backend/app/tests/unit/test_voice_status.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ import unittest
4
+ from datetime import datetime
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+
7
+ import httpx
8
+ from bson import ObjectId
9
+ from fastapi import APIRouter
10
+
11
+ # app.api.routes.__init__ eagerly imports and wires routers from every
12
+ # sibling route module, several of which spin up the LLM stack, NLTK
13
+ # downloads, and ChromaDB at import time. Stub those heavy modules with
14
+ # harmless substitutes so app.api.routes.voice can be imported via normal
15
+ # import machinery.
16
+ for _name in ("app.core.bootstrap", "app.core.rag_manager"):
17
+ sys.modules.setdefault(_name, MagicMock())
18
+
19
+ _stub_router_module = MagicMock(router=APIRouter())
20
+ for _name in (
21
+ "app.api.routes.chat",
22
+ "app.api.routes.documents",
23
+ "app.api.routes.sessions",
24
+ "app.api.routes.provider",
25
+ "app.api.routes.debug",
26
+ "app.api.routes.root",
27
+ "app.api.routes.phd_canvas",
28
+ "app.api.routes.auth",
29
+ ):
30
+ sys.modules.setdefault(_name, _stub_router_module)
31
+
32
+ from app.api.routes.voice import voice_status # noqa: E402
33
+ from app.models.user import User # noqa: E402
34
+
35
+ FAKE_USER_ID = ObjectId()
36
+
37
+
38
+ def _make_fake_user(**overrides):
39
+ defaults = dict(
40
+ _id=FAKE_USER_ID,
41
+ firstName="Test",
42
+ lastName="User",
43
+ email="test@example.com",
44
+ hashed_password="$2b$12$fakehash",
45
+ is_active=True,
46
+ created_at=datetime(2025, 1, 1),
47
+ )
48
+ defaults.update(overrides)
49
+ return User(**defaults)
50
+
51
+
52
+ def _make_async_client(get_side_effect):
53
+ """Build a mock httpx.AsyncClient whose `async with` yields a client
54
+ with `.get` driven by the supplied side_effect (callable or list)."""
55
+ client = MagicMock()
56
+ client.get = AsyncMock(side_effect=get_side_effect)
57
+
58
+ cm = MagicMock()
59
+ cm.__aenter__ = AsyncMock(return_value=client)
60
+ cm.__aexit__ = AsyncMock(return_value=None)
61
+ return cm, client
62
+
63
+
64
+ def _ok_response():
65
+ resp = MagicMock()
66
+ resp.status_code = 200
67
+ return resp
68
+
69
+
70
+ def _err_response():
71
+ resp = MagicMock()
72
+ resp.status_code = 503
73
+ return resp
74
+
75
+
76
+ # ------------------------------------------------------------------
77
+ # GET /voice/status
78
+ # ------------------------------------------------------------------
79
+
80
+
81
+ class TestVoiceStatus(unittest.TestCase):
82
+
83
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
84
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
85
+ def test_both_services_ready(self):
86
+ cm, client = _make_async_client([_ok_response(), _ok_response()])
87
+ user = _make_fake_user()
88
+
89
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
90
+ result = asyncio.run(voice_status(current_user=user))
91
+
92
+ self.assertEqual(result, {"tts_ready": True, "stt_ready": True})
93
+ self.assertEqual(client.get.await_count, 2)
94
+ client.get.assert_any_await("https://tts.example.com/status")
95
+ client.get.assert_any_await("https://stt.example.com/status")
96
+
97
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
98
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
99
+ def test_tts_ready_stt_failure_status(self):
100
+ cm, _ = _make_async_client([_ok_response(), _err_response()])
101
+ user = _make_fake_user()
102
+
103
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
104
+ result = asyncio.run(voice_status(current_user=user))
105
+
106
+ self.assertEqual(result, {"tts_ready": True, "stt_ready": False})
107
+
108
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
109
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
110
+ def test_tts_failure_status_stt_ready(self):
111
+ cm, _ = _make_async_client([_err_response(), _ok_response()])
112
+ user = _make_fake_user()
113
+
114
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
115
+ result = asyncio.run(voice_status(current_user=user))
116
+
117
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": True})
118
+
119
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
120
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
121
+ def test_tts_exception_does_not_break_stt_check(self):
122
+ cm, client = _make_async_client(
123
+ [httpx.ConnectError("boom"), _ok_response()],
124
+ )
125
+ user = _make_fake_user()
126
+
127
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
128
+ result = asyncio.run(voice_status(current_user=user))
129
+
130
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": True})
131
+ self.assertEqual(client.get.await_count, 2)
132
+
133
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
134
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
135
+ def test_stt_exception_keeps_tts_result(self):
136
+ cm, _ = _make_async_client(
137
+ [_ok_response(), httpx.TimeoutException("slow")],
138
+ )
139
+ user = _make_fake_user()
140
+
141
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
142
+ result = asyncio.run(voice_status(current_user=user))
143
+
144
+ self.assertEqual(result, {"tts_ready": True, "stt_ready": False})
145
+
146
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
147
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
148
+ def test_both_exceptions(self):
149
+ cm, _ = _make_async_client(
150
+ [httpx.ConnectError("nope"), httpx.ConnectError("nope")],
151
+ )
152
+ user = _make_fake_user()
153
+
154
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
155
+ result = asyncio.run(voice_status(current_user=user))
156
+
157
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": False})
158
+
159
+ @patch("app.api.routes.voice.STT_BASE", "")
160
+ @patch("app.api.routes.voice.TTS_BASE", "")
161
+ def test_empty_endpoints_skip_http_calls(self):
162
+ cm, client = _make_async_client([])
163
+ user = _make_fake_user()
164
+
165
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
166
+ result = asyncio.run(voice_status(current_user=user))
167
+
168
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": False})
169
+ client.get.assert_not_awaited()
170
+
171
+ @patch("app.api.routes.voice.STT_BASE", None)
172
+ @patch("app.api.routes.voice.TTS_BASE", None)
173
+ def test_none_endpoints_skip_http_calls(self):
174
+ cm, client = _make_async_client([])
175
+ user = _make_fake_user()
176
+
177
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
178
+ result = asyncio.run(voice_status(current_user=user))
179
+
180
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": False})
181
+ client.get.assert_not_awaited()
182
+
183
+ @patch("app.api.routes.voice.STT_BASE", "https://stt.example.com")
184
+ @patch("app.api.routes.voice.TTS_BASE", "")
185
+ def test_only_stt_configured(self):
186
+ cm, client = _make_async_client([_ok_response()])
187
+ user = _make_fake_user()
188
+
189
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
190
+ result = asyncio.run(voice_status(current_user=user))
191
+
192
+ self.assertEqual(result, {"tts_ready": False, "stt_ready": True})
193
+ client.get.assert_awaited_once_with("https://stt.example.com/status")
194
+
195
+ @patch("app.api.routes.voice.STT_BASE", "")
196
+ @patch("app.api.routes.voice.TTS_BASE", "https://tts.example.com")
197
+ def test_only_tts_configured(self):
198
+ cm, client = _make_async_client([_ok_response()])
199
+ user = _make_fake_user()
200
+
201
+ with patch("app.api.routes.voice.httpx.AsyncClient", return_value=cm):
202
+ result = asyncio.run(voice_status(current_user=user))
203
+
204
+ self.assertEqual(result, {"tts_ready": True, "stt_ready": False})
205
+ client.get.assert_awaited_once_with("https://tts.example.com/status")
206
+
207
+
208
+ if __name__ == "__main__":
209
+ unittest.main()
multi_llm_chatbot_backend/requirements.txt CHANGED
@@ -26,6 +26,7 @@ sentence-transformers~=5.3
26
  # Natural language processing
27
  nltk~=3.9
28
  tiktoken~=0.12
 
29
 
30
  # PDF generation and export
31
  reportlab~=4.4
 
26
  # Natural language processing
27
  nltk~=3.9
28
  tiktoken~=0.12
29
+ markdown~=3.0
30
 
31
  # PDF generation and export
32
  reportlab~=4.4
phd-advisor-frontend/src/components/EnhancedChatInput.js CHANGED
@@ -1,5 +1,5 @@
1
- import React, { useState, useRef, useEffect } from 'react';
2
- import { Send, Paperclip, FileText, X, Trash2, Download } from 'lucide-react';
3
  import FileUpload from './FileUpload';
4
 
5
  const EnhancedChatInput = ({
@@ -9,13 +9,90 @@ const EnhancedChatInput = ({
9
  isLoading,
10
  currentChatSessionId,
11
  authToken,
12
- placeholder = "Ask your advisors anything..."
 
 
 
 
 
 
13
  }) => {
14
  const [inputMessage, setInputMessage] = useState('');
15
  const [showUpload, setShowUpload] = useState(false);
16
  const [showDocuments, setShowDocuments] = useState(false);
17
  const [isUploading, setIsUploading] = useState(false);
 
 
 
 
18
  const textareaRef = useRef(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  const handleSend = () => {
21
  if (!inputMessage.trim() || isLoading || isUploading) return;
@@ -67,6 +144,21 @@ const EnhancedChatInput = ({
67
  }
68
  }, [inputMessage]);
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  const formatFileSize = (bytes) => {
71
  if (bytes === 0) return '0 Bytes';
72
  const k = 1024;
@@ -98,13 +190,14 @@ const EnhancedChatInput = ({
98
  <div className="enhanced-chat-input-container">
99
  {/* File Upload Area */}
100
  {showUpload && (
101
- <div className="floating-upload-section">
102
  <FileUpload
103
  onFileUploaded={handleFileUploaded}
104
  isUploading={isUploading}
105
  currentChatSessionId={currentChatSessionId}
106
  authToken={authToken}
107
  onUploadStart={handleUploadStart}
 
108
  />
109
  </div>
110
  )}
@@ -184,6 +277,7 @@ const EnhancedChatInput = ({
184
  {/* Left - File Controls */}
185
  <div className="file-controls">
186
  <button
 
187
  onClick={toggleUpload}
188
  className={`add-docs-btn ${showUpload ? 'active' : ''}`}
189
  disabled={isUploading}
@@ -204,21 +298,102 @@ const EnhancedChatInput = ({
204
  <span className="docs-count">{uploadedDocuments.length}</span>
205
  </button>
206
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  </div>
208
 
209
- {/* Right - Send Button */}
210
- <button
211
- onClick={handleSend}
212
- disabled={!canSend}
213
- className={`send-button ${canSend ? 'enabled' : 'disabled'}`}
214
- type="button"
215
- >
216
- <Send size={16} />
217
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  </div>
219
  </div>
220
  </div>
221
  );
222
  };
223
 
224
- export default EnhancedChatInput;
 
1
+ import React, { useState, useRef, useEffect, useCallback } from 'react';
2
+ import { Send, Paperclip, FileText, X, Trash2, Download, Mic, MicOff, MessageCircle, ClipboardList, Loader2, Columns3, FileOutput } from 'lucide-react';
3
  import FileUpload from './FileUpload';
4
 
5
  const EnhancedChatInput = ({
 
9
  isLoading,
10
  currentChatSessionId,
11
  authToken,
12
+ placeholder = "Ask your advisors anything...",
13
+ showProfileButtons = false,
14
+ onOpenOnboarding,
15
+ onOpenProfileForm,
16
+ synthesizedMode = false,
17
+ onToggleSynthesized,
18
+ ensureSessionId,
19
  }) => {
20
  const [inputMessage, setInputMessage] = useState('');
21
  const [showUpload, setShowUpload] = useState(false);
22
  const [showDocuments, setShowDocuments] = useState(false);
23
  const [isUploading, setIsUploading] = useState(false);
24
+ const [isRecording, setIsRecording] = useState(false);
25
+ const [isTranscribing, setIsTranscribing] = useState(false);
26
+ const mediaRecorderRef = useRef(null);
27
+ const audioChunksRef = useRef([]);
28
  const textareaRef = useRef(null);
29
+ const uploadRef = useRef(null);
30
+ const uploadBtnRef = useRef(null);
31
+
32
+ const sendForTranscription = useCallback(async (blob) => {
33
+ if (!blob || blob.size < 100) {
34
+ console.warn('STT: blob too small, skipping', blob?.size);
35
+ return;
36
+ }
37
+ setIsTranscribing(true);
38
+ try {
39
+ const form = new FormData();
40
+ form.append('audio', blob, 'recording.webm');
41
+ const token = authToken || localStorage.getItem('authToken');
42
+ const resp = await fetch(`${process.env.REACT_APP_API_URL}/voice/transcribe`, {
43
+ method: 'POST',
44
+ headers: { 'Authorization': `Bearer ${token}` },
45
+ body: form,
46
+ });
47
+ if (resp.ok) {
48
+ const data = await resp.json();
49
+ const text = data?.text?.trim();
50
+ if (text) {
51
+ setInputMessage(prev => prev ? `${prev} ${text}` : text);
52
+ }
53
+ } else {
54
+ console.error('STT response not ok:', resp.status, await resp.text().catch(() => ''));
55
+ }
56
+ } catch (err) {
57
+ console.error('Transcription failed:', err);
58
+ } finally {
59
+ setIsTranscribing(false);
60
+ }
61
+ }, [authToken]);
62
+
63
+ const toggleRecording = useCallback(async () => {
64
+ if (isRecording) {
65
+ mediaRecorderRef.current?.stop();
66
+ setIsRecording(false);
67
+ return;
68
+ }
69
+ try {
70
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
71
+
72
+ // Pick a supported mimeType
73
+ const mimeType = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', '']
74
+ .find(mt => mt === '' || MediaRecorder.isTypeSupported(mt));
75
+ const options = mimeType ? { mimeType } : undefined;
76
+ const mediaRecorder = new MediaRecorder(stream, options);
77
+
78
+ audioChunksRef.current = [];
79
+ mediaRecorder.ondataavailable = (e) => {
80
+ if (e.data && e.data.size > 0) audioChunksRef.current.push(e.data);
81
+ };
82
+ mediaRecorder.onstop = () => {
83
+ stream.getTracks().forEach(t => t.stop());
84
+ const blobType = mediaRecorder.mimeType || 'audio/webm';
85
+ const blob = new Blob(audioChunksRef.current, { type: blobType });
86
+ sendForTranscription(blob);
87
+ };
88
+ mediaRecorderRef.current = mediaRecorder;
89
+ // Request data every 500ms so chunks are available when stop() fires
90
+ mediaRecorder.start(500);
91
+ setIsRecording(true);
92
+ } catch (err) {
93
+ console.error('Microphone access error:', err);
94
+ }
95
+ }, [isRecording, sendForTranscription]);
96
 
97
  const handleSend = () => {
98
  if (!inputMessage.trim() || isLoading || isUploading) return;
 
144
  }
145
  }, [inputMessage]);
146
 
147
+ // Close upload panel when clicking outside
148
+ useEffect(() => {
149
+ if (!showUpload) return;
150
+ const handleClickOutside = (e) => {
151
+ if (
152
+ uploadRef.current && !uploadRef.current.contains(e.target) &&
153
+ uploadBtnRef.current && !uploadBtnRef.current.contains(e.target)
154
+ ) {
155
+ setShowUpload(false);
156
+ }
157
+ };
158
+ document.addEventListener('mousedown', handleClickOutside);
159
+ return () => document.removeEventListener('mousedown', handleClickOutside);
160
+ }, [showUpload]);
161
+
162
  const formatFileSize = (bytes) => {
163
  if (bytes === 0) return '0 Bytes';
164
  const k = 1024;
 
190
  <div className="enhanced-chat-input-container">
191
  {/* File Upload Area */}
192
  {showUpload && (
193
+ <div className="floating-upload-section" ref={uploadRef}>
194
  <FileUpload
195
  onFileUploaded={handleFileUploaded}
196
  isUploading={isUploading}
197
  currentChatSessionId={currentChatSessionId}
198
  authToken={authToken}
199
  onUploadStart={handleUploadStart}
200
+ ensureSessionId={ensureSessionId}
201
  />
202
  </div>
203
  )}
 
277
  {/* Left - File Controls */}
278
  <div className="file-controls">
279
  <button
280
+ ref={uploadBtnRef}
281
  onClick={toggleUpload}
282
  className={`add-docs-btn ${showUpload ? 'active' : ''}`}
283
  disabled={isUploading}
 
298
  <span className="docs-count">{uploadedDocuments.length}</span>
299
  </button>
300
  )}
301
+ {showProfileButtons && (
302
+ <>
303
+ <button
304
+ onClick={onOpenOnboarding}
305
+ className="add-docs-btn"
306
+ type="button"
307
+ >
308
+ <MessageCircle size={16} />
309
+ <span>Tell us about yourself</span>
310
+ </button>
311
+ <button
312
+ onClick={onOpenProfileForm}
313
+ className="add-docs-btn"
314
+ type="button"
315
+ >
316
+ <ClipboardList size={16} />
317
+ <span>Fill out profile form</span>
318
+ </button>
319
+ </>
320
+ )}
321
  </div>
322
 
323
+ {/* Right - Mode Toggle + Mic + Send */}
324
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
325
+ {onToggleSynthesized && (
326
+ <div style={{
327
+ display: 'flex', borderRadius: '18px', overflow: 'hidden',
328
+ border: '1px solid #3b82f6', flexShrink: 0,
329
+ }}>
330
+ <button
331
+ onClick={synthesizedMode ? onToggleSynthesized : undefined}
332
+ type="button"
333
+ title="Panel Response (3 advisors)"
334
+ style={{
335
+ display: 'flex', alignItems: 'center', gap: '4px',
336
+ padding: '5px 10px', fontSize: '12px', fontWeight: 600,
337
+ cursor: synthesizedMode ? 'pointer' : 'default',
338
+ border: 'none', transition: 'all 0.2s', whiteSpace: 'nowrap',
339
+ background: !synthesizedMode ? '#3b82f6' : 'transparent',
340
+ color: !synthesizedMode ? '#fff' : '#3b82f6',
341
+ }}
342
+ >
343
+ <Columns3 size={13} />
344
+ Panel
345
+ </button>
346
+ <div style={{ width: 1, background: '#3b82f6', alignSelf: 'stretch' }} />
347
+ <button
348
+ onClick={!synthesizedMode ? onToggleSynthesized : undefined}
349
+ type="button"
350
+ title="Aggregate synthesized answer"
351
+ style={{
352
+ display: 'flex', alignItems: 'center', gap: '4px',
353
+ padding: '5px 10px', fontSize: '12px', fontWeight: 600,
354
+ cursor: !synthesizedMode ? 'pointer' : 'default',
355
+ border: 'none', transition: 'all 0.2s', whiteSpace: 'nowrap',
356
+ background: synthesizedMode ? '#3b82f6' : 'transparent',
357
+ color: synthesizedMode ? '#fff' : '#3b82f6',
358
+ }}
359
+ >
360
+ <FileOutput size={13} />
361
+ Aggregate
362
+ </button>
363
+ </div>
364
+ )}
365
+ <button
366
+ onClick={toggleRecording}
367
+ disabled={isTranscribing}
368
+ className={`mic-button ${isRecording ? 'listening' : ''}`}
369
+ type="button"
370
+ title={isTranscribing ? 'Transcribing...' : isRecording ? 'Stop recording' : 'Voice input'}
371
+ style={{
372
+ background: isRecording ? '#EF4444' : 'transparent',
373
+ border: isRecording ? '1px solid #EF4444' : '1px solid var(--border-primary)',
374
+ color: isRecording ? '#fff' : 'var(--text-secondary)',
375
+ borderRadius: '50%', width: 36, height: 36,
376
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
377
+ cursor: isTranscribing ? 'wait' : 'pointer', transition: 'all 0.2s',
378
+ animation: isRecording ? 'mic-pulse 1.5s ease-in-out infinite' : 'none',
379
+ opacity: isTranscribing ? 0.6 : 1,
380
+ }}
381
+ >
382
+ {isTranscribing ? <Loader2 size={16} className="spinning" /> : isRecording ? <MicOff size={16} /> : <Mic size={16} />}
383
+ </button>
384
+ <button
385
+ onClick={handleSend}
386
+ disabled={!canSend}
387
+ className={`send-button ${canSend ? 'enabled' : 'disabled'}`}
388
+ type="button"
389
+ >
390
+ <Send size={16} />
391
+ </button>
392
+ </div>
393
  </div>
394
  </div>
395
  </div>
396
  );
397
  };
398
 
399
+ export default EnhancedChatInput;
phd-advisor-frontend/src/components/MessageBubble.js CHANGED
@@ -5,8 +5,6 @@ import { Reply, Copy, Check, Maximize2, FileText, Hash, Target, Volume2, VolumeX
5
  import * as LucideIcons from 'lucide-react';
6
  import { useAppConfig } from '../contexts/AppConfigContext';
7
  import { useTheme } from '../contexts/ThemeContext';
8
- import { useVoiceStatus } from '../contexts/VoiceStatusContext';
9
-
10
  const stripMarkdown = (md) => {
11
  if (!md) return '';
12
  return md
@@ -35,7 +33,6 @@ const MessageBubble = ({
35
  }) => {
36
  const { isDark } = useTheme();
37
  const { allPersonas: advisors, getAllPersonaColors: getAdvisorColors } = useAppConfig();
38
- const voiceStatus = useVoiceStatus();
39
  const [showTooltip, setShowTooltip] = useState(null);
40
  const [copiedStates, setCopiedStates] = useState({});
41
  const [isSpeaking, setIsSpeaking] = useState(false);
@@ -55,14 +52,12 @@ const MessageBubble = ({
55
  setIsLoadingTTS(false);
56
  return;
57
  }
58
- if (voiceStatus && !voiceStatus.ensureReady('tts')) return;
59
-
60
  const text = (content || '').trim();
61
  if (!text) return;
62
  setIsLoadingTTS(true);
63
  try {
64
  const token = localStorage.getItem('authToken');
65
- const resp = await fetch(`${process.env.REACT_APP_API_URL}/api/tts`, {
66
  method: 'POST',
67
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
68
  body: JSON.stringify({ text }),
@@ -82,7 +77,7 @@ const MessageBubble = ({
82
  setIsLoadingTTS(false);
83
  setIsSpeaking(false);
84
  }
85
- }, [isSpeaking, isLoadingTTS, voiceStatus]);
86
 
87
  useEffect(() => {
88
  return () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } };
 
5
  import * as LucideIcons from 'lucide-react';
6
  import { useAppConfig } from '../contexts/AppConfigContext';
7
  import { useTheme } from '../contexts/ThemeContext';
 
 
8
  const stripMarkdown = (md) => {
9
  if (!md) return '';
10
  return md
 
33
  }) => {
34
  const { isDark } = useTheme();
35
  const { allPersonas: advisors, getAllPersonaColors: getAdvisorColors } = useAppConfig();
 
36
  const [showTooltip, setShowTooltip] = useState(null);
37
  const [copiedStates, setCopiedStates] = useState({});
38
  const [isSpeaking, setIsSpeaking] = useState(false);
 
52
  setIsLoadingTTS(false);
53
  return;
54
  }
 
 
55
  const text = (content || '').trim();
56
  if (!text) return;
57
  setIsLoadingTTS(true);
58
  try {
59
  const token = localStorage.getItem('authToken');
60
+ const resp = await fetch(`${process.env.REACT_APP_API_URL}/voice/tts`, {
61
  method: 'POST',
62
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
63
  body: JSON.stringify({ text }),
 
77
  setIsLoadingTTS(false);
78
  setIsSpeaking(false);
79
  }
80
+ }, [isSpeaking, isLoadingTTS]);
81
 
82
  useEffect(() => {
83
  return () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } };
phd-advisor-frontend/src/contexts/VoiceStatusContext.js DELETED
@@ -1,13 +0,0 @@
1
- import React, { createContext, useContext } from 'react';
2
-
3
- const VoiceStatusContext = createContext(null);
4
-
5
- export const useVoiceStatus = () => useContext(VoiceStatusContext);
6
-
7
- export const VoiceStatusProvider = ({ children }) => (
8
- <VoiceStatusContext.Provider value={null}>
9
- {children}
10
- </VoiceStatusContext.Provider>
11
- );
12
-
13
- export default VoiceStatusContext;