Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,9 @@
|
|
| 2 |
Health Voice Assistant
|
| 3 |
- Whisper ASR (incremental)
|
| 4 |
- GPT health guidance (NON-diagnostic)
|
| 5 |
-
- Auto Text-to-Speech (autoplay, no
|
| 6 |
|
| 7 |
-
|
| 8 |
"""
|
| 9 |
|
| 10 |
# ================= IMPORTS =================
|
|
@@ -14,38 +14,25 @@ import re
|
|
| 14 |
import textwrap
|
| 15 |
import base64
|
| 16 |
from io import BytesIO
|
| 17 |
-
from
|
| 18 |
|
|
|
|
| 19 |
import numpy as np
|
| 20 |
import torch
|
| 21 |
import streamlit as st
|
| 22 |
|
| 23 |
-
# THAY THẾ: Dùng thư viện ghi âm ổn định hơn
|
| 24 |
-
from streamlit_webrtc import webrtc_streamer, WebRtcMode, AudioProcessorBase
|
| 25 |
-
# Import ClientSettings đã bị loại bỏ trong các phiên bản mới của streamlit-webrtc
|
| 26 |
-
import av # Cần cho việc xử lý audio frame từ webrtc
|
| 27 |
-
|
| 28 |
from transformers import pipeline
|
| 29 |
from transformers.pipelines.audio_utils import ffmpeg_read
|
| 30 |
from openai import OpenAI
|
| 31 |
from gtts import gTTS
|
| 32 |
|
| 33 |
-
# =================
|
| 34 |
-
|
| 35 |
-
st.session_state.transcript = None
|
| 36 |
-
|
| 37 |
-
if "gpt_text" not in st.session_state:
|
| 38 |
-
st.session_state.gpt_text = None
|
| 39 |
-
|
| 40 |
-
if "audio_html" not in st.session_state:
|
| 41 |
-
st.session_state.audio_html = None
|
| 42 |
-
|
| 43 |
-
if "done" not in st.session_state:
|
| 44 |
-
st.session_state.done = False
|
| 45 |
-
|
| 46 |
-
if "webrtc_audio_bytes" not in st.session_state:
|
| 47 |
-
st.session_state.webrtc_audio_bytes = None
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
# ================= CONFIG =================
|
| 51 |
MODEL_NAME = "openai/whisper-small.en"
|
|
@@ -53,76 +40,20 @@ CHUNK_SEC = 6.0
|
|
| 53 |
OVERLAP_SEC = 0.05
|
| 54 |
MAX_CLIP_SEC = 59.0
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
CHATGPT_MODEL = st.secrets.get("gpt_model", "gpt-3.5-turbo")
|
| 59 |
-
|
| 60 |
-
device = 0 if torch.cuda.is_available() else -1
|
| 61 |
-
|
| 62 |
-
# ================= CLASS XỬ LÝ AUDIO WEBRTC =================
|
| 63 |
|
| 64 |
-
|
| 65 |
-
"""
|
| 66 |
-
Xử lý audio frame từ WebRTC và lưu trữ chúng.
|
| 67 |
-
"""
|
| 68 |
-
def __init__(self) -> None:
|
| 69 |
-
self.audio_frames: List[av.AudioFrame] = []
|
| 70 |
-
# Cờ để kiểm tra xem đã kết thúc ghi âm và đã xử lý chưa
|
| 71 |
-
self._is_processed = False
|
| 72 |
-
|
| 73 |
-
def recv_audio(self, frame: av.AudioFrame) -> av.AudioFrame:
|
| 74 |
-
"""Nhận và lưu trữ frame audio."""
|
| 75 |
-
if not self._is_processed:
|
| 76 |
-
self.audio_frames.append(frame)
|
| 77 |
-
|
| 78 |
-
# TRẢ LẠI frame rỗng (muted) để không phát lại âm thanh qua loa
|
| 79 |
-
return frame.silent()
|
| 80 |
-
|
| 81 |
-
def get_wav_bytes(self) -> Optional[bytes]:
|
| 82 |
-
"""
|
| 83 |
-
Chuyển đổi các frame đã lưu thành WAV bytes.
|
| 84 |
-
Phương thức này chỉ được gọi MỘT LẦN sau khi dừng ghi.
|
| 85 |
-
"""
|
| 86 |
-
if self._is_processed or not self.audio_frames:
|
| 87 |
-
return None # Tránh xử lý lại hoặc xử lý khi không có frame
|
| 88 |
-
|
| 89 |
-
try:
|
| 90 |
-
# Lấy thông số từ frame đầu tiên
|
| 91 |
-
layout = self.audio_frames[0].layout.name
|
| 92 |
-
rate = self.audio_frames[0].sample_rate
|
| 93 |
-
|
| 94 |
-
# Bắt đầu container bộ nhớ (in-memory) để lưu WAV
|
| 95 |
-
output = BytesIO()
|
| 96 |
-
with av.open(output, mode='w', format='wav') as container:
|
| 97 |
-
# Tạo stream cho âm thanh PCM 16-bit little-endian
|
| 98 |
-
stream = container.add_stream('pcm_s16le', rate=rate)
|
| 99 |
-
stream.layout = layout
|
| 100 |
-
|
| 101 |
-
# Ghi từng frame vào container
|
| 102 |
-
for frame in self.audio_frames:
|
| 103 |
-
for p in frame.planes:
|
| 104 |
-
if p.buffer_size > 0:
|
| 105 |
-
stream.encode(frame)
|
| 106 |
-
|
| 107 |
-
# Đóng stream và container
|
| 108 |
-
stream.close()
|
| 109 |
-
|
| 110 |
-
self._is_processed = True
|
| 111 |
-
st.session_state.webrtc_audio_bytes = output.getvalue()
|
| 112 |
-
return st.session_state.webrtc_audio_bytes
|
| 113 |
|
| 114 |
-
|
| 115 |
-
st.error(f"Lỗi khi mã hóa audio: {e}")
|
| 116 |
-
return None
|
| 117 |
|
| 118 |
-
# =================
|
| 119 |
-
st.set_page_config(page_title="Health Voice Assistant", layout="wide")
|
| 120 |
st.title("🩺 Health Voice-Based Assistant")
|
| 121 |
|
| 122 |
MEDICAL_DISCLAIMER = """
|
| 123 |
-
⚠️ IMPORTANT MEDICAL DISCLAIMER
|
| 124 |
-
This assistant is NOT a medical professional.
|
| 125 |
-
It does NOT diagnose diseases or prescribe medication.
|
| 126 |
Information is for GENERAL guidance only.
|
| 127 |
"""
|
| 128 |
|
|
@@ -130,12 +61,13 @@ Information is for GENERAL guidance only.
|
|
| 130 |
st.sidebar.title("🎓 User Manual")
|
| 131 |
st.sidebar.markdown(
|
| 132 |
"""
|
| 133 |
-
1.
|
| 134 |
-
2.
|
| 135 |
-
3.
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
| 139 |
"""
|
| 140 |
)
|
| 141 |
st.sidebar.markdown("---")
|
|
@@ -150,9 +82,7 @@ def load_pipeline():
|
|
| 150 |
chunk_length_s=CHUNK_SEC,
|
| 151 |
device=device,
|
| 152 |
)
|
| 153 |
-
|
| 154 |
try:
|
| 155 |
-
# Cấu hình Whisper để ưu tiên ngôn ngữ tiếng Anh
|
| 156 |
forced_ids = pipe.tokenizer.get_decoder_prompt_ids(
|
| 157 |
language="en", task="transcribe"
|
| 158 |
)
|
|
@@ -160,7 +90,6 @@ def load_pipeline():
|
|
| 160 |
pipe._forced_decoder_ids = forced_ids
|
| 161 |
except Exception:
|
| 162 |
pass
|
| 163 |
-
|
| 164 |
return pipe
|
| 165 |
|
| 166 |
|
|
@@ -171,25 +100,13 @@ client = OpenAI(api_key=CHATGPT_API)
|
|
| 171 |
|
| 172 |
# ================= HELPERS =================
|
| 173 |
def format_text(text: str, width: int = 90) -> str:
|
| 174 |
-
"""Định dạng văn bản thành các đoạn văn bản gói gọn."""
|
| 175 |
text = re.sub(r"\s+", " ", text).strip()
|
| 176 |
sentences = re.split(r"(?<=[.!?])\s+", text)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
for s in sentences:
|
| 180 |
-
buf.append(s)
|
| 181 |
-
# Thử kết hợp 3 câu thành một đoạn
|
| 182 |
-
if len(buf) >= 3:
|
| 183 |
-
paragraphs.append(" ".join(buf))
|
| 184 |
-
buf = []
|
| 185 |
-
if buf:
|
| 186 |
-
paragraphs.append(" ".join(buf))
|
| 187 |
-
|
| 188 |
-
return "\n\n".join(textwrap.fill(p, width) for p in paragraphs)
|
| 189 |
|
| 190 |
|
| 191 |
def merge_overlap(old: str, new: str, max_words: int = 10) -> str:
|
| 192 |
-
"""Hợp nhất hai chuỗi văn bản, loại bỏ phần trùng lặp."""
|
| 193 |
if not old:
|
| 194 |
return new
|
| 195 |
a, b = old.split(), new.split()
|
|
@@ -200,38 +117,31 @@ def merge_overlap(old: str, new: str, max_words: int = 10) -> str:
|
|
| 200 |
|
| 201 |
|
| 202 |
def tts_bytes(text: str) -> BytesIO:
|
| 203 |
-
"""Tạo audio bytes từ văn bản sử dụng gTTS."""
|
| 204 |
mp3 = BytesIO()
|
| 205 |
-
|
| 206 |
-
# Nếu GPT phản hồi bằng Tiếng Việt, gTTS sẽ cố gắng phát âm
|
| 207 |
-
gTTS(text=text, lang="en").write_to_fp(mp3)
|
| 208 |
mp3.seek(0)
|
| 209 |
return mp3
|
| 210 |
|
| 211 |
|
| 212 |
-
# ================= GPT =================
|
| 213 |
def run_gpt(transcript: str) -> str:
|
| 214 |
-
"""Gọi API GPT để lấy hướng dẫn sức khỏe."""
|
| 215 |
prompt = f"""
|
| 216 |
-
|
| 217 |
|
| 218 |
{MEDICAL_DISCLAIMER}
|
| 219 |
|
| 220 |
-
|
| 221 |
{transcript}
|
| 222 |
|
| 223 |
-
|
| 224 |
-
-
|
| 225 |
-
-
|
| 226 |
-
-
|
| 227 |
-
-
|
| 228 |
-
- Phản hồi bằng TIẾNG VIỆT nếu bản ghi có vẻ là tiếng Việt. Nếu không, phản hồi bằng TIẾNG ANH.
|
| 229 |
"""
|
| 230 |
-
|
| 231 |
res = client.chat.completions.create(
|
| 232 |
model=CHATGPT_MODEL,
|
| 233 |
messages=[
|
| 234 |
-
{"role": "system", "content": "
|
| 235 |
{"role": "user", "content": prompt},
|
| 236 |
],
|
| 237 |
temperature=0.3,
|
|
@@ -239,26 +149,49 @@ NHIỆM VỤ (TASK):
|
|
| 239 |
return res.choices[0].message.content.strip()
|
| 240 |
|
| 241 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
# ================= ASR =================
|
| 243 |
-
def
|
| 244 |
-
"""Chuyển đổi audio bytes thành văn bản theo từng phần (incremental)."""
|
| 245 |
sr = pipe.feature_extractor.sampling_rate
|
| 246 |
-
|
| 247 |
-
audio = ffmpeg_read(audio_bytes, sr)
|
| 248 |
|
| 249 |
if audio.ndim > 1:
|
| 250 |
audio = audio.mean(axis=1)
|
| 251 |
|
| 252 |
if audio.shape[0] / sr > MAX_CLIP_SEC:
|
| 253 |
-
raise ValueError(
|
| 254 |
|
| 255 |
chunk_samples = int(CHUNK_SEC * sr)
|
| 256 |
overlap_samples = int(OVERLAP_SEC * sr)
|
| 257 |
|
| 258 |
-
total_chunks = max(1, (len(audio) + chunk_samples - 1) // chunk_samples)
|
| 259 |
-
|
| 260 |
acc = ""
|
| 261 |
-
|
|
|
|
|
|
|
| 262 |
start = max(0, i * chunk_samples - overlap_samples)
|
| 263 |
end = min(len(audio), (i + 1) * chunk_samples + overlap_samples)
|
| 264 |
|
|
@@ -268,138 +201,98 @@ def transcribe(audio_bytes: bytes):
|
|
| 268 |
"forced_decoder_ids": getattr(pipe, "_forced_decoder_ids", None)
|
| 269 |
},
|
| 270 |
)
|
| 271 |
-
|
| 272 |
acc = merge_overlap(acc, result["text"].strip())
|
| 273 |
-
yield acc, i + 1,
|
|
|
|
| 274 |
|
|
|
|
|
|
|
| 275 |
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
| 285 |
)
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
"Upload audio (wav, mp3, m4a, ogg, flac)",
|
| 291 |
-
type=["wav", "mp3", "m4a", "ogg", "flac"],
|
| 292 |
-
)
|
| 293 |
-
if uploaded:
|
| 294 |
-
audio_bytes = uploaded.read()
|
| 295 |
-
st.audio(audio_bytes)
|
| 296 |
-
|
| 297 |
-
# --- 2. Ghi âm Trực tiếp (Sử dụng streamlit-webrtc) ---
|
| 298 |
-
elif source_option == "Ghi âm Trực tiếp":
|
| 299 |
-
st.info("Nhấn **START** để bắt đầu ghi âm bằng microphone. Nhấn **STOP** để dừng và xử lý.")
|
| 300 |
-
|
| 301 |
-
# Reset biến lưu trữ bytes khi chế độ này được chọn
|
| 302 |
-
st.session_state.webrtc_audio_bytes = None
|
| 303 |
-
|
| 304 |
-
# Định nghĩa cấu hình WebRTC (Sử dụng STUN Server công cộng của Google)
|
| 305 |
-
RTC_CONFIGURATION = {
|
| 306 |
-
"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]
|
| 307 |
-
}
|
| 308 |
-
|
| 309 |
-
webrtc_ctx = webrtc_streamer(
|
| 310 |
-
key="health_voice_recorder",
|
| 311 |
-
mode=WebRtcMode.SENDONLY,
|
| 312 |
-
audio_processor_factory=AudioFrameRecorder,
|
| 313 |
-
# THÊM CẤU HÌNH STUN SERVER TẠI ĐÂY
|
| 314 |
-
rtc_configuration=RTC_CONFIGURATION,
|
| 315 |
-
media_stream_constraints={
|
| 316 |
-
"video": False,
|
| 317 |
-
"audio": True,
|
| 318 |
-
},
|
| 319 |
-
)
|
| 320 |
-
|
| 321 |
-
# Kiểm tra trạng thái ghi âm
|
| 322 |
-
if webrtc_ctx.state.playing:
|
| 323 |
-
st.warning("🔴 Đang Ghi âm... Nhấn STOP khi hoàn tất.")
|
| 324 |
-
|
| 325 |
-
# Nếu trạng thái đã dừng VÀ có processor (tức là đã từng ghi âm)
|
| 326 |
-
if webrtc_ctx.audio_processor and not webrtc_ctx.state.playing:
|
| 327 |
-
if st.session_state.webrtc_audio_bytes is None:
|
| 328 |
-
# Lấy dữ liệu lần đầu sau khi dừng
|
| 329 |
-
with st.spinner("Đang xử lý audio đã ghi..."):
|
| 330 |
-
webrtc_ctx.audio_processor.get_wav_bytes()
|
| 331 |
-
|
| 332 |
-
if st.session_state.webrtc_audio_bytes:
|
| 333 |
-
audio_bytes = st.session_state.webrtc_audio_bytes
|
| 334 |
-
st.audio(audio_bytes, format='audio/wav')
|
| 335 |
-
st.success("Đã ghi âm thành công! Sẵn sàng để Transcribe.")
|
| 336 |
-
|
| 337 |
-
# --- Logic Xử lý Chung (Chỉ chạy khi có audio_bytes) ---
|
| 338 |
-
if audio_bytes:
|
| 339 |
-
# Nếu đang ghi âm bằng webrtc, không cho phép bấm Transcribe
|
| 340 |
-
disable_transcribe = (source_option == "Ghi âm Trực tiếp" and webrtc_ctx.state.playing)
|
| 341 |
-
|
| 342 |
-
if st.button("Transcribe", key="transcribe_button", disabled=disable_transcribe):
|
| 343 |
-
|
| 344 |
-
# Reset các kết quả trước đó
|
| 345 |
-
st.session_state.transcript = None
|
| 346 |
-
st.session_state.gpt_text = None
|
| 347 |
-
st.session_state.audio_html = None
|
| 348 |
-
st.session_state.done = False
|
| 349 |
|
|
|
|
| 350 |
try:
|
| 351 |
placeholder = st.empty()
|
| 352 |
progress = st.progress(0.0)
|
| 353 |
|
| 354 |
final_text = ""
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
# Quá trình Transcribe (Incremental ASR)
|
| 358 |
-
for txt, i, total in transcribe(audio_bytes):
|
| 359 |
final_text = txt
|
| 360 |
placeholder.markdown(f"```text\n{format_text(txt)}\n```")
|
| 361 |
progress.progress(i / total)
|
| 362 |
-
time.sleep(0.1) # Tăng độ mượt của thanh progress
|
| 363 |
|
| 364 |
st.session_state.transcript = final_text
|
| 365 |
-
st.
|
| 366 |
-
|
| 367 |
-
# Phân tích bằng GPT
|
| 368 |
-
with st.spinner("🧠 Đang Phân tích với GPT..."):
|
| 369 |
-
st.session_state.gpt_text = run_gpt(final_text)
|
| 370 |
-
|
| 371 |
-
# Text-to-Speech và Tự động phát
|
| 372 |
-
with st.spinner("🔊 Đang tạo Audio Phản hồi..."):
|
| 373 |
-
voice = tts_bytes(st.session_state.gpt_text)
|
| 374 |
-
# Dùng base64 để nhúng audio vào HTML và tự động phát
|
| 375 |
-
b64 = base64.b64encode(voice.read()).decode()
|
| 376 |
-
st.session_state.audio_html = f"""
|
| 377 |
-
<audio autoplay>
|
| 378 |
-
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
|
| 379 |
-
</audio>
|
| 380 |
-
"""
|
| 381 |
|
| 382 |
-
st.session_state.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
|
| 384 |
except Exception as e:
|
| 385 |
-
st.error(f"
|
| 386 |
-
progress.empty()
|
| 387 |
|
| 388 |
-
# =================
|
| 389 |
if st.session_state.transcript:
|
| 390 |
-
st.markdown("### 📝 Transcript
|
| 391 |
st.markdown(f"```text\n{format_text(st.session_state.transcript)}\n```")
|
| 392 |
|
| 393 |
if st.session_state.gpt_text:
|
| 394 |
-
st.markdown("### 🧠
|
| 395 |
st.markdown(st.session_state.gpt_text)
|
| 396 |
|
| 397 |
-
if st.session_state.audio_html
|
| 398 |
-
st.markdown(
|
| 399 |
-
# Sử dụng st.empty().markdown để đảm bảo auto-play được kích hoạt
|
| 400 |
-
st.empty().markdown(st.session_state.audio_html, unsafe_allow_html=True)
|
| 401 |
-
st.markdown("---")
|
| 402 |
-
st.markdown("🎉 Hoàn tất!")
|
| 403 |
|
| 404 |
st.markdown("---")
|
| 405 |
-
st.markdown("⚠️
|
|
|
|
| 2 |
Health Voice Assistant
|
| 3 |
- Whisper ASR (incremental)
|
| 4 |
- GPT health guidance (NON-diagnostic)
|
| 5 |
+
- Auto Text-to-Speech (autoplay, no file saved)
|
| 6 |
|
| 7 |
+
⚠️ GENERAL guidance only – NOT medical advice
|
| 8 |
"""
|
| 9 |
|
| 10 |
# ================= IMPORTS =================
|
|
|
|
| 14 |
import textwrap
|
| 15 |
import base64
|
| 16 |
from io import BytesIO
|
| 17 |
+
from datetime import datetime
|
| 18 |
|
| 19 |
+
import requests
|
| 20 |
import numpy as np
|
| 21 |
import torch
|
| 22 |
import streamlit as st
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
from transformers import pipeline
|
| 25 |
from transformers.pipelines.audio_utils import ffmpeg_read
|
| 26 |
from openai import OpenAI
|
| 27 |
from gtts import gTTS
|
| 28 |
|
| 29 |
+
# ================= PAGE CONFIG (MUST BE FIRST) =================
|
| 30 |
+
st.set_page_config(page_title="Health Voice Assistant", layout="wide")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# ================= SESSION STATE =================
|
| 33 |
+
for k in ["transcript", "gpt_text", "audio_html", "done"]:
|
| 34 |
+
if k not in st.session_state:
|
| 35 |
+
st.session_state[k] = None if k != "done" else False
|
| 36 |
|
| 37 |
# ================= CONFIG =================
|
| 38 |
MODEL_NAME = "openai/whisper-small.en"
|
|
|
|
| 40 |
OVERLAP_SEC = 0.05
|
| 41 |
MAX_CLIP_SEC = 59.0
|
| 42 |
|
| 43 |
+
CHATGPT_API = st.secrets["gpt_apikey"]
|
| 44 |
+
CHATGPT_MODEL = st.secrets.get("gpt_model", "gpt-4.0-mini")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
FIREBASE_DB_URL = st.secrets["firebase_database_url"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# ================= UI HEADER =================
|
|
|
|
| 51 |
st.title("🩺 Health Voice-Based Assistant")
|
| 52 |
|
| 53 |
MEDICAL_DISCLAIMER = """
|
| 54 |
+
⚠️ IMPORTANT MEDICAL DISCLAIMER
|
| 55 |
+
This assistant is NOT a medical professional.
|
| 56 |
+
It does NOT diagnose diseases or prescribe medication.
|
| 57 |
Information is for GENERAL guidance only.
|
| 58 |
"""
|
| 59 |
|
|
|
|
| 61 |
st.sidebar.title("🎓 User Manual")
|
| 62 |
st.sidebar.markdown(
|
| 63 |
"""
|
| 64 |
+
1. Choose input method
|
| 65 |
+
2. Upload audio **or** record directly
|
| 66 |
+
3. Press **Transcribe**
|
| 67 |
+
4. App will:
|
| 68 |
+
- Analyze
|
| 69 |
+
- Give guidance
|
| 70 |
+
- Speak response
|
| 71 |
"""
|
| 72 |
)
|
| 73 |
st.sidebar.markdown("---")
|
|
|
|
| 82 |
chunk_length_s=CHUNK_SEC,
|
| 83 |
device=device,
|
| 84 |
)
|
|
|
|
| 85 |
try:
|
|
|
|
| 86 |
forced_ids = pipe.tokenizer.get_decoder_prompt_ids(
|
| 87 |
language="en", task="transcribe"
|
| 88 |
)
|
|
|
|
| 90 |
pipe._forced_decoder_ids = forced_ids
|
| 91 |
except Exception:
|
| 92 |
pass
|
|
|
|
| 93 |
return pipe
|
| 94 |
|
| 95 |
|
|
|
|
| 100 |
|
| 101 |
# ================= HELPERS =================
|
| 102 |
def format_text(text: str, width: int = 90) -> str:
|
|
|
|
| 103 |
text = re.sub(r"\s+", " ", text).strip()
|
| 104 |
sentences = re.split(r"(?<=[.!?])\s+", text)
|
| 105 |
+
return "\n\n".join(textwrap.fill(" ".join(sentences[i:i+3]), width)
|
| 106 |
+
for i in range(0, len(sentences), 3))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
def merge_overlap(old: str, new: str, max_words: int = 10) -> str:
|
|
|
|
| 110 |
if not old:
|
| 111 |
return new
|
| 112 |
a, b = old.split(), new.split()
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
def tts_bytes(text: str) -> BytesIO:
|
|
|
|
| 120 |
mp3 = BytesIO()
|
| 121 |
+
gTTS(text=text, lang="en").write_to_fp(mp3)
|
|
|
|
|
|
|
| 122 |
mp3.seek(0)
|
| 123 |
return mp3
|
| 124 |
|
| 125 |
|
|
|
|
| 126 |
def run_gpt(transcript: str) -> str:
|
|
|
|
| 127 |
prompt = f"""
|
| 128 |
+
You are a NON-diagnostic health assistant.
|
| 129 |
|
| 130 |
{MEDICAL_DISCLAIMER}
|
| 131 |
|
| 132 |
+
Transcript:
|
| 133 |
{transcript}
|
| 134 |
|
| 135 |
+
TASK:
|
| 136 |
+
- Summarize possible concern categories (NOT diagnosis)
|
| 137 |
+
- Explain in simple language
|
| 138 |
+
- Give safe general advice
|
| 139 |
+
- Clearly state when to seek professional medical help
|
|
|
|
| 140 |
"""
|
|
|
|
| 141 |
res = client.chat.completions.create(
|
| 142 |
model=CHATGPT_MODEL,
|
| 143 |
messages=[
|
| 144 |
+
{"role": "system", "content": "Health assistant"},
|
| 145 |
{"role": "user", "content": prompt},
|
| 146 |
],
|
| 147 |
temperature=0.3,
|
|
|
|
| 149 |
return res.choices[0].message.content.strip()
|
| 150 |
|
| 151 |
|
| 152 |
+
# ================= FIREBASE =================
|
| 153 |
+
def read_firebase_transcribe():
|
| 154 |
+
try:
|
| 155 |
+
url = f"{FIREBASE_DB_URL}/transcribe.json"
|
| 156 |
+
res = requests.get(url, timeout=5)
|
| 157 |
+
if res.status_code != 200:
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
data = res.json()
|
| 161 |
+
if not data:
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
text = data.get("text", "").strip()
|
| 165 |
+
if not text:
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
return {
|
| 169 |
+
"text": text,
|
| 170 |
+
"length": data.get("length"),
|
| 171 |
+
"updated_at": data.get("updated_at"),
|
| 172 |
+
}
|
| 173 |
+
except Exception:
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
# ================= ASR =================
|
| 178 |
+
def transcribe_audio(audio_bytes: bytes):
|
|
|
|
| 179 |
sr = pipe.feature_extractor.sampling_rate
|
| 180 |
+
audio = ffmpeg_read(audio_bytes, sr)
|
|
|
|
| 181 |
|
| 182 |
if audio.ndim > 1:
|
| 183 |
audio = audio.mean(axis=1)
|
| 184 |
|
| 185 |
if audio.shape[0] / sr > MAX_CLIP_SEC:
|
| 186 |
+
raise ValueError("Audio too long (max 59s)")
|
| 187 |
|
| 188 |
chunk_samples = int(CHUNK_SEC * sr)
|
| 189 |
overlap_samples = int(OVERLAP_SEC * sr)
|
| 190 |
|
|
|
|
|
|
|
| 191 |
acc = ""
|
| 192 |
+
total = max(1, len(audio) // chunk_samples + 1)
|
| 193 |
+
|
| 194 |
+
for i in range(total):
|
| 195 |
start = max(0, i * chunk_samples - overlap_samples)
|
| 196 |
end = min(len(audio), (i + 1) * chunk_samples + overlap_samples)
|
| 197 |
|
|
|
|
| 201 |
"forced_decoder_ids": getattr(pipe, "_forced_decoder_ids", None)
|
| 202 |
},
|
| 203 |
)
|
|
|
|
| 204 |
acc = merge_overlap(acc, result["text"].strip())
|
| 205 |
+
yield acc, i + 1, total
|
| 206 |
+
|
| 207 |
|
| 208 |
+
# ================= INPUT MODE =================
|
| 209 |
+
st.markdown("## 🎤 Audio Input Method")
|
| 210 |
|
| 211 |
+
input_mode = st.radio(
|
| 212 |
+
"Choose input method:",
|
| 213 |
+
["Upload audio file", "Record audio (from Firebase)"],
|
| 214 |
+
horizontal=True,
|
| 215 |
+
)
|
| 216 |
|
| 217 |
+
# ================= MODE 2: FIREBASE =================
|
| 218 |
+
if input_mode == "Record audio (from Firebase)":
|
| 219 |
+
st.info("📡 Waiting for recorded audio from Firebase...")
|
| 220 |
+
fb = read_firebase_transcribe()
|
| 221 |
+
|
| 222 |
+
if fb is None:
|
| 223 |
+
st.warning("No recorded data found. Redirecting...")
|
| 224 |
+
st.markdown(
|
| 225 |
+
"""
|
| 226 |
+
<meta http-equiv="refresh" content="2; url=https://nolist-ssp-recordoption.hf.space">
|
| 227 |
+
""",
|
| 228 |
+
unsafe_allow_html=True,
|
| 229 |
+
)
|
| 230 |
+
st.stop()
|
| 231 |
+
|
| 232 |
+
st.success("✅ Data received from Firebase")
|
| 233 |
+
st.markdown("### 📝 Transcript (from Firebase)")
|
| 234 |
+
st.markdown(f"```text\n{format_text(fb['text'])}\n```")
|
| 235 |
+
|
| 236 |
+
if st.button("Transcribe"):
|
| 237 |
+
st.session_state.transcript = fb["text"]
|
| 238 |
+
st.session_state.gpt_text = run_gpt(fb["text"])
|
| 239 |
+
|
| 240 |
+
voice = tts_bytes(st.session_state.gpt_text)
|
| 241 |
+
b64 = base64.b64encode(voice.read()).decode()
|
| 242 |
+
st.session_state.audio_html = f"""
|
| 243 |
+
<audio autoplay>
|
| 244 |
+
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
|
| 245 |
+
</audio>
|
| 246 |
+
"""
|
| 247 |
|
| 248 |
+
st.stop()
|
| 249 |
+
|
| 250 |
+
# ================= MODE 1: UPLOAD AUDIO =================
|
| 251 |
+
uploaded = st.file_uploader(
|
| 252 |
+
"Upload audio (wav, mp3, m4a, ogg, flac)",
|
| 253 |
+
type=["wav", "mp3", "m4a", "ogg", "flac"],
|
| 254 |
)
|
| 255 |
|
| 256 |
+
if uploaded:
|
| 257 |
+
audio_bytes = uploaded.read()
|
| 258 |
+
st.audio(audio_bytes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
if st.button("Transcribe"):
|
| 261 |
try:
|
| 262 |
placeholder = st.empty()
|
| 263 |
progress = st.progress(0.0)
|
| 264 |
|
| 265 |
final_text = ""
|
| 266 |
+
for txt, i, total in transcribe_audio(audio_bytes):
|
|
|
|
|
|
|
|
|
|
| 267 |
final_text = txt
|
| 268 |
placeholder.markdown(f"```text\n{format_text(txt)}\n```")
|
| 269 |
progress.progress(i / total)
|
|
|
|
| 270 |
|
| 271 |
st.session_state.transcript = final_text
|
| 272 |
+
st.session_state.gpt_text = run_gpt(final_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
+
voice = tts_bytes(st.session_state.gpt_text)
|
| 275 |
+
b64 = base64.b64encode(voice.read()).decode()
|
| 276 |
+
st.session_state.audio_html = f"""
|
| 277 |
+
<audio autoplay>
|
| 278 |
+
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
|
| 279 |
+
</audio>
|
| 280 |
+
"""
|
| 281 |
|
| 282 |
except Exception as e:
|
| 283 |
+
st.error(f"{e}\n{traceback.format_exc()}")
|
|
|
|
| 284 |
|
| 285 |
+
# ================= OUTPUT =================
|
| 286 |
if st.session_state.transcript:
|
| 287 |
+
st.markdown("### 📝 Transcript")
|
| 288 |
st.markdown(f"```text\n{format_text(st.session_state.transcript)}\n```")
|
| 289 |
|
| 290 |
if st.session_state.gpt_text:
|
| 291 |
+
st.markdown("### 🧠 Health Guidance")
|
| 292 |
st.markdown(st.session_state.gpt_text)
|
| 293 |
|
| 294 |
+
if st.session_state.audio_html:
|
| 295 |
+
st.markdown(st.session_state.audio_html, unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
st.markdown("---")
|
| 298 |
+
st.markdown("⚠️ NOT medical advice. Seek professionals when needed.")
|