File size: 8,608 Bytes
5d2bcc5 e4c0e08 d5c10e8 b083465 5d2bcc5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
import asyncio
import base64
import json
from pathlib import Path
import gradio as gr
import numpy as np
import openai
from dotenv import load_dotenv
from fastapi import FastAPI
from typing import Callable
from core.silero_vad import SileroVAD
from services.streaming_voice_service import VoskStreamingASR
from fastapi.responses import HTMLResponse, StreamingResponse
# Thêm vào imports hiện tại
from fastrtc import (
AdditionalOutputs,
AsyncStreamHandler,
Stream,
get_twilio_turn_credentials,
wait_for_item,
)
from gradio.utils import get_space
class OpenAIRealtimeService:
"""Dịch vụ OpenAI Realtime API cho streaming chất lượng cao"""
def __init__(self, api_key: str):
self.client = openai.AsyncOpenAI(api_key=api_key)
self.connection = None
self.is_active = False
async def start_session(self):
"""Bắt đầu session OpenAI Realtime"""
try:
self.connection = await self.client.beta.realtime.connect(
model="gpt-4o-mini-realtime-preview-2024-12-17"
)
# Cấu hình session
await self.connection.session.update(
session={
"turn_detection": {"type": "server_vad"},
"input_audio_transcription": {
"model": "whisper-1",
"language": "vi", # Hỗ trợ tiếng Việt
},
}
)
self.is_active = True
print("✅ OpenAI Realtime session started")
return True
except Exception as e:
print(f"❌ Lỗi khởi động OpenAI Realtime: {e}")
return False
async def process_audio_chunk(self, audio_chunk: np.ndarray, sample_rate: int = 24000):
"""Xử lý audio chunk với OpenAI Realtime API"""
if not self.connection or not self.is_active:
return None
try:
# Chuẩn hóa audio
if sample_rate != 24000:
audio_chunk = self._resample_audio(audio_chunk, sample_rate, 24000)
# Encode audio
audio_message = base64.b64encode(audio_chunk.tobytes()).decode("utf-8")
# Gửi đến OpenAI
await self.connection.input_audio_buffer.append(audio=audio_message)
except Exception as e:
print(f"❌ Lỗi xử lý audio với OpenAI: {e}")
async def get_responses(self):
"""Lấy responses từ OpenAI Realtime API"""
if not self.connection:
return
async for event in self.connection:
if event.type == "input_audio_buffer.speech_started":
yield {"type": "speech_started"}
elif event.type == "conversation.item.input_audio_transcription.completed":
yield {
"type": "user_transcription",
"content": event.transcript,
"role": "user"
}
elif event.type == "response.audio_transcript.done":
yield {
"type": "assistant_transcription",
"content": event.transcript,
"role": "assistant"
}
elif event.type == "response.audio.delta":
audio_data = np.frombuffer(
base64.b64decode(event.delta), dtype=np.int16
)
yield {
"type": "audio_delta",
"audio": audio_data,
"sample_rate": 24000
}
async def close(self):
"""Đóng kết nối"""
if self.connection:
await self.connection.close()
self.is_active = False
print("🛑 OpenAI Realtime session closed")
class HybridStreamingService:
"""Service kết hợp VOSK local và OpenAI Realtime"""
def __init__(self, groq_client, rag_system, tts_service, openai_key: str = None):
self.groq_client = groq_client
self.rag_system = rag_system
self.tts_service = tts_service
# Local ASR với VOSK
self.vosk_asr = VoskStreamingASR()
self.vad_processor = SileroVAD()
# OpenAI Realtime API
self.openai_service = None
if openai_key:
self.openai_service = OpenAIRealtimeService(openai_key)
self.current_mode = "local" # 'local' hoặc 'openai'
self.is_listening = False
async def start_listening(self, speech_callback: Callable, mode: str = "auto"):
"""Bắt đầu lắng nghe với mode lựa chọn"""
self.current_callback = speech_callback
if mode == "openai" and self.openai_service:
return await self._start_openai_mode()
else:
return self._start_local_mode()
async def _start_openai_mode(self):
"""Khởi động chế độ OpenAI Realtime"""
try:
success = await self.openai_service.start_session()
if success:
self.is_listening = True
self.current_mode = "openai"
# Khởi động background task để nhận responses
asyncio.create_task(self._openai_response_handler())
if self.current_callback:
self.current_callback({
'transcription': "Đã bắt đầu với OpenAI Realtime...",
'response': "",
'tts_audio': None,
'status': 'openai_listening'
})
return True
return False
except Exception as e:
print(f"❌ Lỗi khởi động OpenAI mode: {e}")
return False
def _start_local_mode(self):
"""Khởi động chế độ local VOSK"""
try:
if self.vosk_asr.start_stream() and self.vad_processor.start_stream(self._on_speech_detected):
self.is_listening = True
self.current_mode = "local"
# Khởi động worker threads
self._start_worker_threads()
if self.current_callback:
self.current_callback({
'transcription': "Đã bắt đầu với VOSK local...",
'response': "",
'tts_audio': None,
'status': 'local_listening'
})
return True
return False
except Exception as e:
print(f"❌ Lỗi khởi động local mode: {e}")
return False
async def _openai_response_handler(self):
"""Xử lý responses từ OpenAI Realtime"""
try:
async for response in self.openai_service.get_responses():
if response['type'] == 'user_transcription' and self.current_callback:
self.current_callback({
'transcription': response['content'],
'response': "Đang xử lý...",
'tts_audio': None,
'status': 'processing'
})
elif response['type'] == 'assistant_transcription' and self.current_callback:
self.current_callback({
'transcription': "", # Giữ transcription cũ
'response': response['content'],
'tts_audio': None,
'status': 'completed'
})
elif response['type'] == 'audio_delta' and self.current_callback:
# Xử lý audio real-time từ OpenAI
audio_path = self._save_temp_audio(response['audio'], response['sample_rate'])
self.current_callback({
'transcription': "",
'response': "",
'tts_audio': audio_path,
'status': 'audio_streaming'
})
except Exception as e:
print(f"❌ Lỗi OpenAI response handler: {e}") |