commit
Browse files- app.py +1 -1
- requirements.txt +1 -1
- speech_io.py +159 -300
app.py
CHANGED
|
@@ -474,7 +474,7 @@ def toggle_recording():
|
|
| 474 |
# =====================================================
|
| 475 |
# UI – GRADIO với tất cả tính năng mới
|
| 476 |
# =====================================================
|
| 477 |
-
with gr.Blocks(title="Prüfungsrechts-Chatbot (RAG + Sprache) - Enhanced", css=".gradio-container {max-width: 1200px; margin: auto;}") as demo:
|
| 478 |
|
| 479 |
# Custom CSS
|
| 480 |
gr.HTML("""
|
|
|
|
| 474 |
# =====================================================
|
| 475 |
# UI – GRADIO với tất cả tính năng mới
|
| 476 |
# =====================================================
|
| 477 |
+
with gr.Blocks(title="Prüfungsrechts-Chatbot (RAG + Sprache) - Enhanced", theme=gr.themes.Soft(), css=".gradio-container {max-width: 1200px; margin: auto;}") as demo:
|
| 478 |
|
| 479 |
# Custom CSS
|
| 480 |
gr.HTML("""
|
requirements.txt
CHANGED
|
@@ -35,7 +35,7 @@ torchaudio
|
|
| 35 |
torch
|
| 36 |
librosa # For better audio processing
|
| 37 |
webrtcvad # Alternative VAD library
|
| 38 |
-
|
| 39 |
|
| 40 |
# === OpenAI + HF Hub ===
|
| 41 |
openai
|
|
|
|
| 35 |
torch
|
| 36 |
librosa # For better audio processing
|
| 37 |
webrtcvad # Alternative VAD library
|
| 38 |
+
|
| 39 |
|
| 40 |
# === OpenAI + HF Hub ===
|
| 41 |
openai
|
speech_io.py
CHANGED
|
@@ -1,25 +1,20 @@
|
|
| 1 |
"""
|
| 2 |
-
speech_io.py - Enhanced Version
|
| 3 |
|
| 4 |
Sprachbasierte Ein-/Ausgabe với:
|
| 5 |
-
- Audio Recording (Ghi âm trực tiếp)
|
| 6 |
- Speech-to-Text (STT) với Whisper
|
| 7 |
- Text-to-Speech (TTS)
|
| 8 |
-
- Voice Activity Detection (VAD)
|
| 9 |
"""
|
| 10 |
|
| 11 |
import os
|
| 12 |
import time
|
| 13 |
-
import wave
|
| 14 |
-
import pyaudio
|
| 15 |
-
import threading
|
| 16 |
from typing import Optional, Tuple, Dict, Any
|
| 17 |
import numpy as np
|
| 18 |
import soundfile as sf
|
| 19 |
from scipy.signal import butter, filtfilt, resample
|
| 20 |
import re
|
| 21 |
import difflib
|
| 22 |
-
import queue
|
| 23 |
|
| 24 |
# ========================================================
|
| 25 |
# CẤU HÌNH
|
|
@@ -29,180 +24,24 @@ WHISPER_MODEL = os.getenv("WHISPER_MODEL", "base")
|
|
| 29 |
ASR_MODEL_ID = f"openai/whisper-{WHISPER_MODEL}"
|
| 30 |
TTS_MODEL_ID = os.getenv("TTS_MODEL_ID", "facebook/mms-tts-deu")
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
RECORD_FORMAT = pyaudio.paInt16
|
| 37 |
|
| 38 |
# VAD Configuration
|
| 39 |
ENABLE_VAD = os.getenv("ENABLE_VAD", "true").lower() == "true"
|
| 40 |
-
VAD_THRESHOLD = float(os.getenv("VAD_THRESHOLD", "0.
|
|
|
|
| 41 |
|
| 42 |
# Other Configs
|
| 43 |
ASR_DEFAULT_LANGUAGE = os.getenv("ASR_LANGUAGE", "de")
|
| 44 |
TTS_ENABLED = os.getenv("TTS_ENABLED", "1").lower() not in ("0", "false", "no")
|
| 45 |
ASR_MAX_DURATION_S = int(os.getenv("ASR_MAX_DURATION_S", "30"))
|
| 46 |
|
| 47 |
-
#
|
| 48 |
_asr = None
|
| 49 |
_tts = None
|
| 50 |
-
_audio_queue = queue.Queue()
|
| 51 |
-
_is_recording = False
|
| 52 |
-
_audio_thread = None
|
| 53 |
-
|
| 54 |
-
# ========================================================
|
| 55 |
-
# AUDIO RECORDING FUNCTIONS
|
| 56 |
-
# ========================================================
|
| 57 |
-
def record_audio(duration: float = 5.0) -> Tuple[Optional[np.ndarray], int]:
|
| 58 |
-
"""
|
| 59 |
-
Ghi âm trực tiếp từ microphone
|
| 60 |
-
|
| 61 |
-
Args:
|
| 62 |
-
duration: Thời gian ghi âm (giây)
|
| 63 |
-
|
| 64 |
-
Returns:
|
| 65 |
-
Tuple (audio_data, sample_rate)
|
| 66 |
-
"""
|
| 67 |
-
global _is_recording
|
| 68 |
-
|
| 69 |
-
print(f"Starting audio recording for {duration} seconds...")
|
| 70 |
-
|
| 71 |
-
try:
|
| 72 |
-
p = pyaudio.PyAudio()
|
| 73 |
-
|
| 74 |
-
# Mở stream
|
| 75 |
-
stream = p.open(
|
| 76 |
-
format=RECORD_FORMAT,
|
| 77 |
-
channels=RECORD_CHANNELS,
|
| 78 |
-
rate=RECORD_SAMPLE_RATE,
|
| 79 |
-
input=True,
|
| 80 |
-
frames_per_buffer=RECORD_CHUNK_SIZE,
|
| 81 |
-
input_device_index=None # Sử dụng default device
|
| 82 |
-
)
|
| 83 |
-
|
| 84 |
-
frames = []
|
| 85 |
-
total_frames = int(RECORD_SAMPLE_RATE / RECORD_CHUNK_SIZE * duration)
|
| 86 |
-
|
| 87 |
-
print(f"Recording {total_frames} chunks...")
|
| 88 |
-
|
| 89 |
-
for i in range(total_frames):
|
| 90 |
-
try:
|
| 91 |
-
data = stream.read(RECORD_CHUNK_SIZE, exception_on_overflow=False)
|
| 92 |
-
frames.append(data)
|
| 93 |
-
|
| 94 |
-
# Hiển thị progress
|
| 95 |
-
if i % 50 == 0:
|
| 96 |
-
print(f"Recording... {i/total_frames*100:.1f}%")
|
| 97 |
-
|
| 98 |
-
except Exception as e:
|
| 99 |
-
print(f"Error reading audio chunk: {e}")
|
| 100 |
-
break
|
| 101 |
-
|
| 102 |
-
print("Recording completed")
|
| 103 |
-
|
| 104 |
-
# Dừng stream
|
| 105 |
-
stream.stop_stream()
|
| 106 |
-
stream.close()
|
| 107 |
-
p.terminate()
|
| 108 |
-
|
| 109 |
-
# Chuyển đổi frames thành numpy array
|
| 110 |
-
audio_bytes = b''.join(frames)
|
| 111 |
-
audio_array = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
|
| 112 |
-
|
| 113 |
-
print(f"Recorded audio shape: {audio_array.shape}")
|
| 114 |
-
|
| 115 |
-
return audio_array, RECORD_SAMPLE_RATE
|
| 116 |
-
|
| 117 |
-
except Exception as e:
|
| 118 |
-
print(f"Error in record_audio: {e}")
|
| 119 |
-
return None, RECORD_SAMPLE_RATE
|
| 120 |
-
|
| 121 |
-
def record_audio_with_vad(
|
| 122 |
-
max_duration: float = 10.0,
|
| 123 |
-
silence_duration: float = 1.0,
|
| 124 |
-
threshold: float = 0.1
|
| 125 |
-
) -> Tuple[Optional[np.ndarray], int]:
|
| 126 |
-
"""
|
| 127 |
-
Ghi âm với VAD - tự động dừng khi hết giọng nói
|
| 128 |
-
|
| 129 |
-
Args:
|
| 130 |
-
max_duration: Thời gian tối đa (giây)
|
| 131 |
-
silence_duration: Thời gian im lặng để dừng (giây)
|
| 132 |
-
threshold: Ngưỡng VAD
|
| 133 |
-
|
| 134 |
-
Returns:
|
| 135 |
-
Tuple (audio_data, sample_rate)
|
| 136 |
-
"""
|
| 137 |
-
print(f"Recording with VAD (max: {max_duration}s, silence: {silence_duration}s)")
|
| 138 |
-
|
| 139 |
-
try:
|
| 140 |
-
p = pyaudio.PyAudio()
|
| 141 |
-
|
| 142 |
-
stream = p.open(
|
| 143 |
-
format=RECORD_FORMAT,
|
| 144 |
-
channels=RECORD_CHANNELS,
|
| 145 |
-
rate=RECORD_SAMPLE_RATE,
|
| 146 |
-
input=True,
|
| 147 |
-
frames_per_buffer=RECORD_CHUNK_SIZE
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
frames = []
|
| 151 |
-
is_speaking = False
|
| 152 |
-
silence_frames = 0
|
| 153 |
-
max_silence_frames = int(silence_duration * RECORD_SAMPLE_RATE / RECORD_CHUNK_SIZE)
|
| 154 |
-
max_total_frames = int(max_duration * RECORD_SAMPLE_RATE / RECORD_CHUNK_SIZE)
|
| 155 |
-
|
| 156 |
-
print("Listening... (speak now)")
|
| 157 |
-
|
| 158 |
-
for i in range(max_total_frames):
|
| 159 |
-
try:
|
| 160 |
-
data = stream.read(RECORD_CHUNK_SIZE, exception_on_overflow=False)
|
| 161 |
-
frames.append(data)
|
| 162 |
-
|
| 163 |
-
# Kiểm tra VAD mỗi 10 frames
|
| 164 |
-
if i % 10 == 0 and len(frames) > 0:
|
| 165 |
-
# Chuyển chunk cuối cùng sang numpy để kiểm tra
|
| 166 |
-
chunk_bytes = frames[-1]
|
| 167 |
-
chunk_array = np.frombuffer(chunk_bytes, dtype=np.int16).astype(np.float32) / 32768.0
|
| 168 |
-
|
| 169 |
-
# Simple energy-based VAD
|
| 170 |
-
energy = np.mean(chunk_array ** 2)
|
| 171 |
-
|
| 172 |
-
if energy > threshold:
|
| 173 |
-
is_speaking = True
|
| 174 |
-
silence_frames = 0
|
| 175 |
-
print("🎤 Speech detected")
|
| 176 |
-
else:
|
| 177 |
-
if is_speaking:
|
| 178 |
-
silence_frames += 1
|
| 179 |
-
if silence_frames > max_silence_frames:
|
| 180 |
-
print("⏸️ Silence detected, stopping recording")
|
| 181 |
-
break
|
| 182 |
-
|
| 183 |
-
except Exception as e:
|
| 184 |
-
print(f"Error in VAD recording: {e}")
|
| 185 |
-
break
|
| 186 |
-
|
| 187 |
-
stream.stop_stream()
|
| 188 |
-
stream.close()
|
| 189 |
-
p.terminate()
|
| 190 |
-
|
| 191 |
-
if len(frames) == 0:
|
| 192 |
-
print("No audio recorded")
|
| 193 |
-
return None, RECORD_SAMPLE_RATE
|
| 194 |
-
|
| 195 |
-
# Chuyển đổi frames
|
| 196 |
-
audio_bytes = b''.join(frames)
|
| 197 |
-
audio_array = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
|
| 198 |
-
|
| 199 |
-
print(f"VAD recording completed: {len(audio_array)/RECORD_SAMPLE_RATE:.2f}s")
|
| 200 |
-
|
| 201 |
-
return audio_array, RECORD_SAMPLE_RATE
|
| 202 |
-
|
| 203 |
-
except Exception as e:
|
| 204 |
-
print(f"Error in record_audio_with_vad: {e}")
|
| 205 |
-
return None, RECORD_SAMPLE_RATE
|
| 206 |
|
| 207 |
# ========================================================
|
| 208 |
# AUDIO PROCESSING UTILITIES
|
|
@@ -217,6 +56,30 @@ def butter_highpass_filter(data, cutoff=60, fs=16000, order=4):
|
|
| 217 |
b, a = butter(order, normal_cutoff, btype='high', analog=False)
|
| 218 |
return filtfilt(b, a, data)
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
def normalize_audio(audio_data: np.ndarray) -> np.ndarray:
|
| 221 |
"""Chuẩn hóa audio về [-1, 1]"""
|
| 222 |
if len(audio_data) == 0:
|
|
@@ -233,8 +96,8 @@ def normalize_audio(audio_data: np.ndarray) -> np.ndarray:
|
|
| 233 |
|
| 234 |
return audio_data
|
| 235 |
|
| 236 |
-
def
|
| 237 |
-
"""Tiền xử lý audio cho
|
| 238 |
if len(audio_data) == 0:
|
| 239 |
return audio_data
|
| 240 |
|
|
@@ -245,14 +108,7 @@ def preprocess_audio(audio_data: np.ndarray, sample_rate: int) -> np.ndarray:
|
|
| 245 |
# Normalize
|
| 246 |
audio_data = normalize_audio(audio_data)
|
| 247 |
|
| 248 |
-
#
|
| 249 |
-
TARGET_SR = 16000
|
| 250 |
-
if sample_rate != TARGET_SR:
|
| 251 |
-
target_len = int(len(audio_data) * TARGET_SR / sample_rate)
|
| 252 |
-
audio_data = resample(audio_data, target_len)
|
| 253 |
-
sample_rate = TARGET_SR
|
| 254 |
-
|
| 255 |
-
# Highpass filter
|
| 256 |
try:
|
| 257 |
audio_data = butter_highpass_filter(audio_data, cutoff=80, fs=sample_rate)
|
| 258 |
except:
|
|
@@ -261,20 +117,22 @@ def preprocess_audio(audio_data: np.ndarray, sample_rate: int) -> np.ndarray:
|
|
| 261 |
return audio_data
|
| 262 |
|
| 263 |
# ========================================================
|
| 264 |
-
# VOICE ACTIVITY DETECTION (VAD) -
|
| 265 |
# ========================================================
|
| 266 |
def detect_voice_activity(
|
| 267 |
audio_data: np.ndarray,
|
| 268 |
sample_rate: int,
|
| 269 |
-
threshold: float = 0.
|
|
|
|
| 270 |
) -> Dict[str, Any]:
|
| 271 |
"""
|
| 272 |
-
Phát hiện hoạt động giọng nói - Phiên bản
|
| 273 |
|
| 274 |
Args:
|
| 275 |
audio_data: Mảng numpy chứa audio samples
|
| 276 |
sample_rate: Tần số lấy mẫu
|
| 277 |
threshold: Ngưỡng ph��t hiện (0-1)
|
|
|
|
| 278 |
|
| 279 |
Returns:
|
| 280 |
Dict với thông tin phát hiện
|
|
@@ -283,79 +141,129 @@ def detect_voice_activity(
|
|
| 283 |
return {
|
| 284 |
"is_speech": False,
|
| 285 |
"confidence": 0.0,
|
|
|
|
|
|
|
| 286 |
"message": "Empty audio data"
|
| 287 |
}
|
| 288 |
|
| 289 |
try:
|
| 290 |
-
# Tiền xử lý
|
| 291 |
-
processed_audio =
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
# 1. Tính RMS energy
|
| 294 |
-
|
| 295 |
|
| 296 |
# 2. Tính zero-crossing rate
|
| 297 |
-
zero_crossings = np.sum(np.abs(np.diff(np.sign(processed_audio)))) / len(processed_audio)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
-
#
|
| 300 |
-
|
| 301 |
-
|
| 302 |
|
| 303 |
-
if len(processed_audio) >
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
frame_energy = np.sqrt(np.mean(frame ** 2))
|
| 308 |
-
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
energy_threshold = np.percentile(
|
| 313 |
-
speech_frames = sum(1 for e in
|
| 314 |
-
speech_ratio = speech_frames / len(
|
| 315 |
else:
|
| 316 |
speech_ratio = 0
|
| 317 |
else:
|
| 318 |
speech_ratio = 0
|
| 319 |
|
| 320 |
-
#
|
| 321 |
-
#
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
-
#
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
| 327 |
else:
|
| 328 |
zcr_score = 0.0
|
| 329 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
# Speech ratio score
|
| 331 |
speech_ratio_score = speech_ratio
|
| 332 |
|
| 333 |
-
#
|
| 334 |
-
|
| 335 |
-
confidence =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
-
#
|
| 338 |
is_speech = confidence > threshold
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
# Debug info
|
| 341 |
debug_info = {
|
| 342 |
-
"
|
| 343 |
-
"
|
| 344 |
-
"
|
| 345 |
-
"
|
| 346 |
-
"
|
| 347 |
-
"
|
| 348 |
-
"
|
| 349 |
-
"
|
| 350 |
-
"
|
|
|
|
|
|
|
| 351 |
}
|
| 352 |
|
| 353 |
-
print(f"VAD
|
| 354 |
|
| 355 |
return {
|
| 356 |
"is_speech": is_speech,
|
| 357 |
"confidence": float(confidence),
|
| 358 |
-
"
|
|
|
|
|
|
|
| 359 |
}
|
| 360 |
|
| 361 |
except Exception as e:
|
|
@@ -363,6 +271,8 @@ def detect_voice_activity(
|
|
| 363 |
return {
|
| 364 |
"is_speech": False,
|
| 365 |
"confidence": 0.0,
|
|
|
|
|
|
|
| 366 |
"message": f"Error: {str(e)}"
|
| 367 |
}
|
| 368 |
|
|
@@ -391,9 +301,6 @@ def transcribe_with_groq(audio_path: str, language: Optional[str] = None) -> str
|
|
| 391 |
"""
|
| 392 |
Transcribe audio sử dụng Groq Cloud API
|
| 393 |
"""
|
| 394 |
-
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 395 |
-
GROQ_MODEL = os.getenv("GROQ_MODEL", "whisper-large-v3-turbo")
|
| 396 |
-
|
| 397 |
if not GROQ_API_KEY:
|
| 398 |
print(">>> Groq API key nicht gefunden. Verwende lokales Modell.")
|
| 399 |
return transcribe_audio(audio_path, language)
|
|
@@ -452,28 +359,27 @@ def transcribe_audio(
|
|
| 452 |
print(">>> Audio leer.")
|
| 453 |
return ""
|
| 454 |
|
| 455 |
-
|
|
|
|
|
|
|
| 456 |
|
| 457 |
# Tiền xử lý
|
| 458 |
-
data =
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
duration = len(data) / sr
|
| 463 |
-
rms = np.sqrt(np.mean(data ** 2))
|
| 464 |
-
|
| 465 |
-
print(f">>> Audio nach Preprocessing - Dauer: {duration:.2f}s, RMS: {rms:.6f}")
|
| 466 |
|
| 467 |
-
#
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
|
|
|
|
|
|
| 471 |
|
| 472 |
# Giới hạn độ dài
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
data = data[:
|
| 476 |
-
print(f">>> Audio auf {max_duration_s}s gekürzt.")
|
| 477 |
|
| 478 |
# Lấy pipeline
|
| 479 |
asr = get_asr_pipeline()
|
|
@@ -487,13 +393,13 @@ def transcribe_audio(
|
|
| 487 |
|
| 488 |
# Transcribe
|
| 489 |
print(f">>> Transkribiere mit Whisper-{WHISPER_MODEL}...")
|
| 490 |
-
|
| 491 |
call_kwargs = {}
|
|
|
|
| 492 |
if lang:
|
| 493 |
call_kwargs["generate_kwargs"] = {
|
| 494 |
"language": lang,
|
| 495 |
"task": "transcribe",
|
| 496 |
-
"max_new_tokens":
|
| 497 |
"temperature": 0.0,
|
| 498 |
}
|
| 499 |
|
|
@@ -510,8 +416,6 @@ def transcribe_audio(
|
|
| 510 |
|
| 511 |
except Exception as e:
|
| 512 |
print(f">>> Transkriptionsfehler: {e}")
|
| 513 |
-
import traceback
|
| 514 |
-
traceback.print_exc()
|
| 515 |
return ""
|
| 516 |
|
| 517 |
# ========================================================
|
|
@@ -566,10 +470,12 @@ def synthesize_speech(text: str) -> Optional[Tuple[int, np.ndarray]]:
|
|
| 566 |
if max_val > 0:
|
| 567 |
audio = audio / max_val
|
| 568 |
|
|
|
|
|
|
|
|
|
|
| 569 |
# Convert to int16
|
| 570 |
audio_int16 = np.clip(audio * 32767, -32768, 32767).astype(np.int16)
|
| 571 |
|
| 572 |
-
print(f">>> TTS erfolgreich - Dauer: {len(audio_int16)/sr:.2f}s")
|
| 573 |
return (sr, audio_int16)
|
| 574 |
|
| 575 |
except Exception as e:
|
|
@@ -588,16 +494,11 @@ def fix_domain_terms(text: str) -> str:
|
|
| 588 |
|
| 589 |
# Common mis-transcriptions
|
| 590 |
correction_pairs = [
|
| 591 |
-
(r
|
| 592 |
-
(r
|
| 593 |
-
(r
|
| 594 |
-
(r
|
| 595 |
-
(r
|
| 596 |
-
(r'\bexmatrikulations?\b', 'exmatrikulation'),
|
| 597 |
-
(r'\banmeldungs?\b', 'anmeldung'),
|
| 598 |
-
(r'\bwiederholungs?\b', 'wiederholung'),
|
| 599 |
-
(r'\bnoten?\b', 'note'),
|
| 600 |
-
(r'\bsemesters?\b', 'semester'),
|
| 601 |
]
|
| 602 |
|
| 603 |
for pattern, replacement in correction_pairs:
|
|
@@ -605,56 +506,14 @@ def fix_domain_terms(text: str) -> str:
|
|
| 605 |
|
| 606 |
return text
|
| 607 |
|
| 608 |
-
# ========================================================
|
| 609 |
-
# TEST FUNCTIONS
|
| 610 |
-
# ========================================================
|
| 611 |
-
def test_audio_recording():
|
| 612 |
-
"""Test audio recording functionality"""
|
| 613 |
-
print("Testing audio recording...")
|
| 614 |
-
|
| 615 |
-
# Test 1: Simple recording
|
| 616 |
-
audio_data, sample_rate = record_audio(3.0)
|
| 617 |
-
if audio_data is not None:
|
| 618 |
-
print(f"Test 1 passed: Recorded {len(audio_data)/sample_rate:.2f}s audio")
|
| 619 |
-
|
| 620 |
-
# Save test file
|
| 621 |
-
test_file = "test_recording.wav"
|
| 622 |
-
sf.write(test_file, audio_data, sample_rate)
|
| 623 |
-
print(f"Saved test recording to {test_file}")
|
| 624 |
-
|
| 625 |
-
# Test transcription
|
| 626 |
-
text = transcribe_audio(test_file)
|
| 627 |
-
print(f"Transcription: {text}")
|
| 628 |
-
|
| 629 |
-
# Cleanup
|
| 630 |
-
if os.path.exists(test_file):
|
| 631 |
-
os.remove(test_file)
|
| 632 |
-
else:
|
| 633 |
-
print("Test 1 failed: Could not record audio")
|
| 634 |
-
|
| 635 |
-
# Test 2: VAD recording
|
| 636 |
-
print("\nTesting VAD recording...")
|
| 637 |
-
audio_data, sample_rate = record_audio_with_vad(max_duration=5.0, silence_duration=1.0)
|
| 638 |
-
if audio_data is not None:
|
| 639 |
-
print(f"Test 2 passed: VAD recording {len(audio_data)/sample_rate:.2f}s")
|
| 640 |
-
else:
|
| 641 |
-
print("Test 2 failed: VAD recording failed")
|
| 642 |
-
|
| 643 |
# ========================================================
|
| 644 |
# MAIN EXPORT
|
| 645 |
# ========================================================
|
| 646 |
__all__ = [
|
| 647 |
-
'record_audio',
|
| 648 |
-
'record_audio_with_vad',
|
| 649 |
'transcribe_audio',
|
| 650 |
'transcribe_with_groq',
|
| 651 |
'synthesize_speech',
|
| 652 |
'detect_voice_activity',
|
| 653 |
'normalize_audio',
|
| 654 |
-
'
|
| 655 |
-
|
| 656 |
-
]
|
| 657 |
-
|
| 658 |
-
if __name__ == "__main__":
|
| 659 |
-
# Run tests
|
| 660 |
-
test_audio_recording()
|
|
|
|
| 1 |
"""
|
| 2 |
+
speech_io.py - Enhanced Version with working VAD
|
| 3 |
|
| 4 |
Sprachbasierte Ein-/Ausgabe với:
|
|
|
|
| 5 |
- Speech-to-Text (STT) với Whisper
|
| 6 |
- Text-to-Speech (TTS)
|
| 7 |
+
- Voice Activity Detection (VAD) hoạt động
|
| 8 |
"""
|
| 9 |
|
| 10 |
import os
|
| 11 |
import time
|
|
|
|
|
|
|
|
|
|
| 12 |
from typing import Optional, Tuple, Dict, Any
|
| 13 |
import numpy as np
|
| 14 |
import soundfile as sf
|
| 15 |
from scipy.signal import butter, filtfilt, resample
|
| 16 |
import re
|
| 17 |
import difflib
|
|
|
|
| 18 |
|
| 19 |
# ========================================================
|
| 20 |
# CẤU HÌNH
|
|
|
|
| 24 |
ASR_MODEL_ID = f"openai/whisper-{WHISPER_MODEL}"
|
| 25 |
TTS_MODEL_ID = os.getenv("TTS_MODEL_ID", "facebook/mms-tts-deu")
|
| 26 |
|
| 27 |
+
# Groq Configuration
|
| 28 |
+
USE_GROQ = os.getenv("USE_GROQ", "false").lower() == "true"
|
| 29 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 30 |
+
GROQ_MODEL = os.getenv("GROQ_MODEL", "whisper-large-v3-turbo")
|
|
|
|
| 31 |
|
| 32 |
# VAD Configuration
|
| 33 |
ENABLE_VAD = os.getenv("ENABLE_VAD", "true").lower() == "true"
|
| 34 |
+
VAD_THRESHOLD = float(os.getenv("VAD_THRESHOLD", "0.3"))
|
| 35 |
+
VAD_MIN_DURATION = float(os.getenv("VAD_MIN_DURATION", "0.1"))
|
| 36 |
|
| 37 |
# Other Configs
|
| 38 |
ASR_DEFAULT_LANGUAGE = os.getenv("ASR_LANGUAGE", "de")
|
| 39 |
TTS_ENABLED = os.getenv("TTS_ENABLED", "1").lower() not in ("0", "false", "no")
|
| 40 |
ASR_MAX_DURATION_S = int(os.getenv("ASR_MAX_DURATION_S", "30"))
|
| 41 |
|
| 42 |
+
# Cache for models
|
| 43 |
_asr = None
|
| 44 |
_tts = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# ========================================================
|
| 47 |
# AUDIO PROCESSING UTILITIES
|
|
|
|
| 56 |
b, a = butter(order, normal_cutoff, btype='high', analog=False)
|
| 57 |
return filtfilt(b, a, data)
|
| 58 |
|
| 59 |
+
def apply_fade(audio, sr, fade_in_ms=10, fade_out_ms=10):
|
| 60 |
+
"""Áp dụng fade in/out để tránh pop"""
|
| 61 |
+
if len(audio) == 0:
|
| 62 |
+
return audio
|
| 63 |
+
|
| 64 |
+
fade_in_samples = int(sr * fade_in_ms / 1000)
|
| 65 |
+
fade_out_samples = int(sr * fade_out_ms / 1000)
|
| 66 |
+
|
| 67 |
+
# Đảm bảo có đủ samples
|
| 68 |
+
if len(audio) < fade_in_samples + fade_out_samples:
|
| 69 |
+
return audio
|
| 70 |
+
|
| 71 |
+
# Fade in
|
| 72 |
+
if fade_in_samples > 0:
|
| 73 |
+
fade_in_curve = np.linspace(0, 1, fade_in_samples)
|
| 74 |
+
audio[:fade_in_samples] *= fade_in_curve
|
| 75 |
+
|
| 76 |
+
# Fade out
|
| 77 |
+
if fade_out_samples > 0:
|
| 78 |
+
fade_out_curve = np.linspace(1, 0, fade_out_samples)
|
| 79 |
+
audio[-fade_out_samples:] *= fade_out_curve
|
| 80 |
+
|
| 81 |
+
return audio
|
| 82 |
+
|
| 83 |
def normalize_audio(audio_data: np.ndarray) -> np.ndarray:
|
| 84 |
"""Chuẩn hóa audio về [-1, 1]"""
|
| 85 |
if len(audio_data) == 0:
|
|
|
|
| 96 |
|
| 97 |
return audio_data
|
| 98 |
|
| 99 |
+
def preprocess_audio_for_vad(audio_data: np.ndarray, sample_rate: int) -> np.ndarray:
|
| 100 |
+
"""Tiền xử lý audio cho VAD"""
|
| 101 |
if len(audio_data) == 0:
|
| 102 |
return audio_data
|
| 103 |
|
|
|
|
| 108 |
# Normalize
|
| 109 |
audio_data = normalize_audio(audio_data)
|
| 110 |
|
| 111 |
+
# Highpass filter để loại bỏ noise tần số thấp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
try:
|
| 113 |
audio_data = butter_highpass_filter(audio_data, cutoff=80, fs=sample_rate)
|
| 114 |
except:
|
|
|
|
| 117 |
return audio_data
|
| 118 |
|
| 119 |
# ========================================================
|
| 120 |
+
# VOICE ACTIVITY DETECTION (VAD) - FIXED VERSION
|
| 121 |
# ========================================================
|
| 122 |
def detect_voice_activity(
|
| 123 |
audio_data: np.ndarray,
|
| 124 |
sample_rate: int,
|
| 125 |
+
threshold: float = 0.3,
|
| 126 |
+
min_duration: float = 0.1
|
| 127 |
) -> Dict[str, Any]:
|
| 128 |
"""
|
| 129 |
+
Phát hiện hoạt động giọng nói - Phiên bản đơn giản và hoạt động
|
| 130 |
|
| 131 |
Args:
|
| 132 |
audio_data: Mảng numpy chứa audio samples
|
| 133 |
sample_rate: Tần số lấy mẫu
|
| 134 |
threshold: Ngưỡng ph��t hiện (0-1)
|
| 135 |
+
min_duration: Thời gian tối thiểu để xác định là speech (giây)
|
| 136 |
|
| 137 |
Returns:
|
| 138 |
Dict với thông tin phát hiện
|
|
|
|
| 141 |
return {
|
| 142 |
"is_speech": False,
|
| 143 |
"confidence": 0.0,
|
| 144 |
+
"speech_segments": [],
|
| 145 |
+
"energy": 0.0,
|
| 146 |
"message": "Empty audio data"
|
| 147 |
}
|
| 148 |
|
| 149 |
try:
|
| 150 |
+
# Tiền xử lý audio
|
| 151 |
+
processed_audio = preprocess_audio_for_vad(audio_data, sample_rate)
|
| 152 |
+
|
| 153 |
+
# Tính toán các đặc trưng
|
| 154 |
+
duration = len(processed_audio) / sample_rate
|
| 155 |
|
| 156 |
# 1. Tính RMS energy
|
| 157 |
+
rms_energy = np.sqrt(np.mean(processed_audio ** 2))
|
| 158 |
|
| 159 |
# 2. Tính zero-crossing rate
|
| 160 |
+
zero_crossings = np.sum(np.abs(np.diff(np.sign(processed_audio)))) / (2 * len(processed_audio))
|
| 161 |
+
|
| 162 |
+
# 3. Tính spectral centroid (đơn giản)
|
| 163 |
+
# Sử dụng FFT để tính phân bố tần số
|
| 164 |
+
if len(processed_audio) >= 256:
|
| 165 |
+
fft_size = min(2048, len(processed_audio))
|
| 166 |
+
spectrum = np.abs(np.fft.rfft(processed_audio[:fft_size]))
|
| 167 |
+
frequencies = np.fft.rfftfreq(fft_size, 1/sample_rate)
|
| 168 |
+
if np.sum(spectrum) > 0:
|
| 169 |
+
spectral_centroid = np.sum(frequencies * spectrum) / np.sum(spectrum)
|
| 170 |
+
else:
|
| 171 |
+
spectral_centroid = 0
|
| 172 |
+
else:
|
| 173 |
+
spectral_centroid = 0
|
| 174 |
|
| 175 |
+
# 4. Frame-based analysis
|
| 176 |
+
frame_length = int(sample_rate * 0.03) # 30ms frame
|
| 177 |
+
hop_length = int(frame_length / 2)
|
| 178 |
|
| 179 |
+
if len(processed_audio) > frame_length:
|
| 180 |
+
num_frames = 1 + (len(processed_audio) - frame_length) // hop_length
|
| 181 |
+
frame_energies = []
|
| 182 |
+
|
| 183 |
+
for i in range(num_frames):
|
| 184 |
+
start = i * hop_length
|
| 185 |
+
end = start + frame_length
|
| 186 |
+
frame = processed_audio[start:end]
|
| 187 |
frame_energy = np.sqrt(np.mean(frame ** 2))
|
| 188 |
+
frame_energies.append(frame_energy)
|
| 189 |
|
| 190 |
+
# Tính speech ratio
|
| 191 |
+
if frame_energies:
|
| 192 |
+
energy_threshold = np.percentile(frame_energies, 30) + threshold * (np.max(frame_energies) - np.percentile(frame_energies, 30))
|
| 193 |
+
speech_frames = sum(1 for e in frame_energies if e > energy_threshold)
|
| 194 |
+
speech_ratio = speech_frames / len(frame_energies)
|
| 195 |
else:
|
| 196 |
speech_ratio = 0
|
| 197 |
else:
|
| 198 |
speech_ratio = 0
|
| 199 |
|
| 200 |
+
# 5. Kết hợp các đặc trưng để tính confidence
|
| 201 |
+
# Speech thường có:
|
| 202 |
+
# - RMS energy cao
|
| 203 |
+
# - Zero-crossing rate trung bình (không quá cao như noise, không quá thấp như silence)
|
| 204 |
+
# - Spectral centroid trong khoảng 100-3000 Hz cho giọng nói
|
| 205 |
+
# - Speech ratio cao
|
| 206 |
|
| 207 |
+
# Tính confidence score
|
| 208 |
+
energy_score = min(1.0, rms_energy * 10) # Scale energy
|
| 209 |
+
|
| 210 |
+
# Zero-crossing rate score: lý tưởng khoảng 0.1-0.3 cho speech
|
| 211 |
+
if 0.05 < zero_crossings < 0.4:
|
| 212 |
+
zcr_score = 1.0 - 2 * abs(zero_crossings - 0.2) # Peak ở 0.2
|
| 213 |
else:
|
| 214 |
zcr_score = 0.0
|
| 215 |
|
| 216 |
+
# Spectral centroid score: lý tưởng 100-3000 Hz
|
| 217 |
+
if 100 < spectral_centroid < 3000:
|
| 218 |
+
centroid_score = 1.0
|
| 219 |
+
elif 50 < spectral_centroid < 5000:
|
| 220 |
+
centroid_score = 0.5
|
| 221 |
+
else:
|
| 222 |
+
centroid_score = 0.0
|
| 223 |
+
|
| 224 |
# Speech ratio score
|
| 225 |
speech_ratio_score = speech_ratio
|
| 226 |
|
| 227 |
+
# Kết hợp các score
|
| 228 |
+
weights = [0.4, 0.2, 0.2, 0.2] # energy, zcr, centroid, speech_ratio
|
| 229 |
+
confidence = (
|
| 230 |
+
weights[0] * energy_score +
|
| 231 |
+
weights[1] * zcr_score +
|
| 232 |
+
weights[2] * centroid_score +
|
| 233 |
+
weights[3] * speech_ratio_score
|
| 234 |
+
)
|
| 235 |
|
| 236 |
+
# Áp dụng ngưỡng
|
| 237 |
is_speech = confidence > threshold
|
| 238 |
|
| 239 |
+
# Kiểm tra duration tối thiểu
|
| 240 |
+
if duration < min_duration:
|
| 241 |
+
is_speech = False
|
| 242 |
+
confidence = max(0, confidence - 0.2)
|
| 243 |
+
|
| 244 |
# Debug info
|
| 245 |
debug_info = {
|
| 246 |
+
"duration": duration,
|
| 247 |
+
"rms_energy": rms_energy,
|
| 248 |
+
"zero_crossings": zero_crossings,
|
| 249 |
+
"spectral_centroid": spectral_centroid,
|
| 250 |
+
"speech_ratio": speech_ratio,
|
| 251 |
+
"energy_score": energy_score,
|
| 252 |
+
"zcr_score": zcr_score,
|
| 253 |
+
"centroid_score": centroid_score,
|
| 254 |
+
"speech_ratio_score": speech_ratio_score,
|
| 255 |
+
"final_confidence": confidence,
|
| 256 |
+
"is_speech": is_speech
|
| 257 |
}
|
| 258 |
|
| 259 |
+
print(f"VAD Debug: {debug_info}")
|
| 260 |
|
| 261 |
return {
|
| 262 |
"is_speech": is_speech,
|
| 263 |
"confidence": float(confidence),
|
| 264 |
+
"speech_segments": [[0, duration]] if is_speech else [],
|
| 265 |
+
"energy": float(rms_energy),
|
| 266 |
+
"message": f"Speech: {is_speech}, Confidence: {confidence:.3f}"
|
| 267 |
}
|
| 268 |
|
| 269 |
except Exception as e:
|
|
|
|
| 271 |
return {
|
| 272 |
"is_speech": False,
|
| 273 |
"confidence": 0.0,
|
| 274 |
+
"speech_segments": [],
|
| 275 |
+
"energy": 0.0,
|
| 276 |
"message": f"Error: {str(e)}"
|
| 277 |
}
|
| 278 |
|
|
|
|
| 301 |
"""
|
| 302 |
Transcribe audio sử dụng Groq Cloud API
|
| 303 |
"""
|
|
|
|
|
|
|
|
|
|
| 304 |
if not GROQ_API_KEY:
|
| 305 |
print(">>> Groq API key nicht gefunden. Verwende lokales Modell.")
|
| 306 |
return transcribe_audio(audio_path, language)
|
|
|
|
| 359 |
print(">>> Audio leer.")
|
| 360 |
return ""
|
| 361 |
|
| 362 |
+
# Chuyển sang mono
|
| 363 |
+
if len(data.shape) > 1:
|
| 364 |
+
data = np.mean(data, axis=1)
|
| 365 |
|
| 366 |
# Tiền xử lý
|
| 367 |
+
data = data.astype(np.float32)
|
| 368 |
+
max_val = np.max(np.abs(data))
|
| 369 |
+
if max_val > 0:
|
| 370 |
+
data = data / max_val
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
+
# Resample về 16kHz nếu cần
|
| 373 |
+
TARGET_SR = 16000
|
| 374 |
+
if sr != TARGET_SR:
|
| 375 |
+
target_len = int(len(data) * TARGET_SR / sr)
|
| 376 |
+
data = resample(data, target_len)
|
| 377 |
+
sr = TARGET_SR
|
| 378 |
|
| 379 |
# Giới hạn độ dài
|
| 380 |
+
MAX_SAMPLES = sr * max_duration_s
|
| 381 |
+
if len(data) > MAX_SAMPLES:
|
| 382 |
+
data = data[:MAX_SAMPLES]
|
|
|
|
| 383 |
|
| 384 |
# Lấy pipeline
|
| 385 |
asr = get_asr_pipeline()
|
|
|
|
| 393 |
|
| 394 |
# Transcribe
|
| 395 |
print(f">>> Transkribiere mit Whisper-{WHISPER_MODEL}...")
|
|
|
|
| 396 |
call_kwargs = {}
|
| 397 |
+
|
| 398 |
if lang:
|
| 399 |
call_kwargs["generate_kwargs"] = {
|
| 400 |
"language": lang,
|
| 401 |
"task": "transcribe",
|
| 402 |
+
"max_new_tokens": 120,
|
| 403 |
"temperature": 0.0,
|
| 404 |
}
|
| 405 |
|
|
|
|
| 416 |
|
| 417 |
except Exception as e:
|
| 418 |
print(f">>> Transkriptionsfehler: {e}")
|
|
|
|
|
|
|
| 419 |
return ""
|
| 420 |
|
| 421 |
# ========================================================
|
|
|
|
| 470 |
if max_val > 0:
|
| 471 |
audio = audio / max_val
|
| 472 |
|
| 473 |
+
# Apply fade
|
| 474 |
+
audio = apply_fade(audio, sr)
|
| 475 |
+
|
| 476 |
# Convert to int16
|
| 477 |
audio_int16 = np.clip(audio * 32767, -32768, 32767).astype(np.int16)
|
| 478 |
|
|
|
|
| 479 |
return (sr, audio_int16)
|
| 480 |
|
| 481 |
except Exception as e:
|
|
|
|
| 494 |
|
| 495 |
# Common mis-transcriptions
|
| 496 |
correction_pairs = [
|
| 497 |
+
(r"\bbriefe\s*um\b", "prüfung"),
|
| 498 |
+
(r"\bbrieft\s*um\b", "prüfung"),
|
| 499 |
+
(r"\bbriefung\b", "prüfung"),
|
| 500 |
+
(r"\bpruefung\b", "prüfung"),
|
| 501 |
+
(r"\bhochschule\s*gesetz\b", "hochschulgesetz"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
]
|
| 503 |
|
| 504 |
for pattern, replacement in correction_pairs:
|
|
|
|
| 506 |
|
| 507 |
return text
|
| 508 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
# ========================================================
|
| 510 |
# MAIN EXPORT
|
| 511 |
# ========================================================
|
| 512 |
__all__ = [
|
|
|
|
|
|
|
| 513 |
'transcribe_audio',
|
| 514 |
'transcribe_with_groq',
|
| 515 |
'synthesize_speech',
|
| 516 |
'detect_voice_activity',
|
| 517 |
'normalize_audio',
|
| 518 |
+
'preprocess_audio_for_vad'
|
| 519 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|