mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix: Improve ASR accuracy and eliminate phantom transcripts
- Fix audio length calculation to use WAV file metadata instead of PCM estimation - Implement comprehensive ASR logging system (CSV, JSON, TXT formats) - Disable audio file deletion for easier debugging - Add audio buffer clearing when VAD states reset - Implement echo suppression (100ms) to prevent speaker audio feedback - Add stale audio detection to skip leftover chunks after TTS - Clear ASR audio queue on VAD reset to prevent processing queued chunks - Add timestamp tracking for listen start events - Fix undefined send_initial_greeting function error │ │ These changes eliminate phantom transcripts like 'SHE', 'UP' that occurred when echo from the device's speaker was picked up by the microphone.
This commit is contained in:
parent
0fe4c2d0b3
commit
3371c45608
5 changed files with 2245 additions and 2234 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,150 +1,150 @@
|
||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
import random
|
import random
|
||||||
import asyncio
|
import asyncio
|
||||||
from core.utils.dialogue import Message
|
from core.utils.dialogue import Message
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message
|
from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message
|
||||||
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
||||||
from core.providers.tts.dto.dto import ContentType, SentenceType
|
from core.providers.tts.dto.dto import ContentType, SentenceType
|
||||||
from core.providers.tools.device_mcp import (
|
from core.providers.tools.device_mcp import (
|
||||||
MCPClient,
|
MCPClient,
|
||||||
send_mcp_initialize_message,
|
send_mcp_initialize_message,
|
||||||
send_mcp_tools_list_request,
|
send_mcp_tools_list_request,
|
||||||
)
|
)
|
||||||
from core.utils.wakeup_word import WakeupWordsConfig
|
from core.utils.wakeup_word import WakeupWordsConfig
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
WAKEUP_CONFIG = {
|
WAKEUP_CONFIG = {
|
||||||
"refresh_time": 5,
|
"refresh_time": 5,
|
||||||
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
|
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
|
||||||
}
|
}
|
||||||
|
|
||||||
# Create global wakeup words configuration manager
|
# Create global wakeup words configuration manager
|
||||||
wakeup_words_config = WakeupWordsConfig()
|
wakeup_words_config = WakeupWordsConfig()
|
||||||
|
|
||||||
# Lock to prevent concurrent calls to wakeupWordsResponse
|
# Lock to prevent concurrent calls to wakeupWordsResponse
|
||||||
_wakeup_response_lock = asyncio.Lock()
|
_wakeup_response_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
async def handleHelloMessage(conn, msg_json):
|
async def handleHelloMessage(conn, msg_json):
|
||||||
"""Handle hello message"""
|
"""Handle hello message"""
|
||||||
audio_params = msg_json.get("audio_params")
|
audio_params = msg_json.get("audio_params")
|
||||||
if audio_params:
|
if audio_params:
|
||||||
format = audio_params.get("format")
|
format = audio_params.get("format")
|
||||||
conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
|
conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
|
||||||
conn.audio_format = format
|
conn.audio_format = format
|
||||||
conn.welcome_msg["audio_params"] = audio_params
|
conn.welcome_msg["audio_params"] = audio_params
|
||||||
features = msg_json.get("features")
|
features = msg_json.get("features")
|
||||||
if features:
|
if features:
|
||||||
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
|
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
|
||||||
conn.features = features
|
conn.features = features
|
||||||
|
|
||||||
# Handle both list and dictionary formats for features
|
# Handle both list and dictionary formats for features
|
||||||
has_mcp = False
|
has_mcp = False
|
||||||
if isinstance(features, list):
|
if isinstance(features, list):
|
||||||
has_mcp = "mcp" in features
|
has_mcp = "mcp" in features
|
||||||
elif isinstance(features, dict):
|
elif isinstance(features, dict):
|
||||||
has_mcp = features.get("mcp", False)
|
has_mcp = features.get("mcp", False)
|
||||||
|
|
||||||
if has_mcp:
|
if has_mcp:
|
||||||
conn.logger.bind(tag=TAG).info("Client supports MCP")
|
conn.logger.bind(tag=TAG).info("Client supports MCP")
|
||||||
conn.mcp_client = MCPClient()
|
conn.mcp_client = MCPClient()
|
||||||
# Send initialization
|
# Send initialization
|
||||||
asyncio.create_task(send_mcp_initialize_message(conn))
|
asyncio.create_task(send_mcp_initialize_message(conn))
|
||||||
# Send mcp message to get tools list
|
# Send mcp message to get tools list
|
||||||
asyncio.create_task(send_mcp_tools_list_request(conn))
|
asyncio.create_task(send_mcp_tools_list_request(conn))
|
||||||
|
|
||||||
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
||||||
|
|
||||||
|
|
||||||
async def checkWakeupWords(conn, text):
|
async def checkWakeupWords(conn, text):
|
||||||
enable_wakeup_words_response_cache = conn.config[
|
enable_wakeup_words_response_cache = conn.config[
|
||||||
"enable_wakeup_words_response_cache"
|
"enable_wakeup_words_response_cache"
|
||||||
]
|
]
|
||||||
|
|
||||||
if not enable_wakeup_words_response_cache or not conn.tts:
|
if not enable_wakeup_words_response_cache or not conn.tts:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
_, filtered_text = remove_punctuation_and_length(text)
|
_, filtered_text = remove_punctuation_and_length(text)
|
||||||
if filtered_text not in conn.config.get("wakeup_words"):
|
if filtered_text not in conn.config.get("wakeup_words"):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
conn.just_woken_up = True
|
conn.just_woken_up = True
|
||||||
await send_stt_message(conn, text)
|
await send_stt_message(conn, text)
|
||||||
|
|
||||||
# Get current voice
|
# Get current voice
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
if not voice:
|
if not voice:
|
||||||
voice = "default"
|
voice = "default"
|
||||||
|
|
||||||
# Get wakeup words reply configuration
|
# Get wakeup words reply configuration
|
||||||
response = wakeup_words_config.get_wakeup_response(voice)
|
response = wakeup_words_config.get_wakeup_response(voice)
|
||||||
if not response or not response.get("file_path"):
|
if not response or not response.get("file_path"):
|
||||||
response = {
|
response = {
|
||||||
"voice": "default",
|
"voice": "default",
|
||||||
"file_path": "config/assets/wakeup_words.wav",
|
"file_path": "config/assets/wakeup_words.wav",
|
||||||
"time": 0,
|
"time": 0,
|
||||||
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
|
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
|
||||||
}
|
}
|
||||||
|
|
||||||
# Play wakeup words reply
|
# Play wakeup words reply
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
opus_packets, _ = audio_to_data(response.get("file_path"))
|
opus_packets, _ = audio_to_data(response.get("file_path"))
|
||||||
|
|
||||||
conn.logger.bind(tag=TAG).info(
|
conn.logger.bind(tag=TAG).info(
|
||||||
f"Playing wakeup words reply: {response.get('text')}")
|
f"Playing wakeup words reply: {response.get('text')}")
|
||||||
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
|
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
|
||||||
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
await sendAudioMessage(conn, SentenceType.LAST, [], None)
|
||||||
|
|
||||||
# Add to dialogue
|
# Add to dialogue
|
||||||
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
|
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
|
||||||
|
|
||||||
# Check if wakeup words reply needs to be updated
|
# Check if wakeup words reply needs to be updated
|
||||||
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
|
||||||
if not _wakeup_response_lock.locked():
|
if not _wakeup_response_lock.locked():
|
||||||
asyncio.create_task(wakeupWordsResponse(conn))
|
asyncio.create_task(wakeupWordsResponse(conn))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def wakeupWordsResponse(conn):
|
async def wakeupWordsResponse(conn):
|
||||||
if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
|
if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Try to acquire lock, return if cannot acquire
|
# Try to acquire lock, return if cannot acquire
|
||||||
if not await _wakeup_response_lock.acquire():
|
if not await _wakeup_response_lock.acquire():
|
||||||
return
|
return
|
||||||
|
|
||||||
# Generate wakeup words reply
|
# Generate wakeup words reply
|
||||||
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
|
||||||
question = (
|
question = (
|
||||||
"The user is currently saying ```"
|
"The user is currently saying ```"
|
||||||
+ wakeup_word
|
+ wakeup_word
|
||||||
+ "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n"
|
+ "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n"
|
||||||
+ "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content."
|
+ "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content."
|
||||||
)
|
)
|
||||||
|
|
||||||
result = conn.llm.response_no_stream(conn.config["prompt"], question)
|
result = conn.llm.response_no_stream(conn.config["prompt"], question)
|
||||||
if not result or len(result) == 0:
|
if not result or len(result) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Generate TTS audio
|
# Generate TTS audio
|
||||||
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
|
||||||
if not tts_result:
|
if not tts_result:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Get current voice
|
# Get current voice
|
||||||
voice = getattr(conn.tts, "voice", "default")
|
voice = getattr(conn.tts, "voice", "default")
|
||||||
|
|
||||||
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
|
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
|
||||||
file_path = wakeup_words_config.generate_file_path(voice)
|
file_path = wakeup_words_config.generate_file_path(voice)
|
||||||
with open(file_path, "wb") as f:
|
with open(file_path, "wb") as f:
|
||||||
f.write(wav_bytes)
|
f.write(wav_bytes)
|
||||||
# Update configuration
|
# Update configuration
|
||||||
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
wakeup_words_config.update_wakeup_response(voice, file_path, result)
|
||||||
finally:
|
finally:
|
||||||
# Ensure lock is released in any case
|
# Ensure lock is released in any case
|
||||||
if _wakeup_response_lock.locked():
|
if _wakeup_response_lock.locked():
|
||||||
_wakeup_response_lock.release()
|
_wakeup_response_lock.release()
|
||||||
|
|
|
||||||
|
|
@ -1,186 +1,188 @@
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
from core.handle.abortHandle import handleAbortMessage
|
from core.handle.abortHandle import handleAbortMessage
|
||||||
from core.handle.helloHandle import handleHelloMessage
|
from core.handle.helloHandle import handleHelloMessage
|
||||||
from core.providers.tools.device_mcp import handle_mcp_message
|
from core.providers.tools.device_mcp import handle_mcp_message
|
||||||
from core.utils.util import remove_punctuation_and_length, filter_sensitive_info
|
from core.utils.util import remove_punctuation_and_length, filter_sensitive_info
|
||||||
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
|
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
|
||||||
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
|
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
|
||||||
from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus
|
from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus
|
||||||
from core.handle.reportHandle import enqueue_asr_report
|
from core.handle.reportHandle import enqueue_asr_report
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handleTextMessage(conn, message):
|
async def handleTextMessage(conn, message):
|
||||||
"""Handle text messages"""
|
"""Handle text messages"""
|
||||||
try:
|
try:
|
||||||
msg_json = json.loads(message)
|
msg_json = json.loads(message)
|
||||||
if isinstance(msg_json, int):
|
if isinstance(msg_json, int):
|
||||||
conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
|
conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
|
||||||
await conn.websocket.send(message)
|
await conn.websocket.send(message)
|
||||||
return
|
return
|
||||||
if msg_json["type"] == "hello":
|
if msg_json["type"] == "hello":
|
||||||
conn.logger.bind(tag=TAG).info(
|
conn.logger.bind(tag=TAG).info(
|
||||||
f"Received hello message: {message}")
|
f"Received hello message: {message}")
|
||||||
await handleHelloMessage(conn, msg_json)
|
await handleHelloMessage(conn, msg_json)
|
||||||
elif msg_json["type"] == "abort":
|
elif msg_json["type"] == "abort":
|
||||||
conn.logger.bind(tag=TAG).info(
|
conn.logger.bind(tag=TAG).info(
|
||||||
f"Received abort message: {message}")
|
f"Received abort message: {message}")
|
||||||
await handleAbortMessage(conn)
|
await handleAbortMessage(conn)
|
||||||
elif msg_json["type"] == "listen":
|
elif msg_json["type"] == "listen":
|
||||||
conn.logger.bind(tag=TAG).info(
|
conn.logger.bind(tag=TAG).info(
|
||||||
f"Received listen message: {message}")
|
f"Received listen message: {message}")
|
||||||
if "mode" in msg_json:
|
if "mode" in msg_json:
|
||||||
conn.client_listen_mode = msg_json["mode"]
|
conn.client_listen_mode = msg_json["mode"]
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"Client audio capture mode: {conn.client_listen_mode}"
|
f"Client audio capture mode: {conn.client_listen_mode}"
|
||||||
)
|
)
|
||||||
if msg_json["state"] == "start":
|
if msg_json["state"] == "start":
|
||||||
# Reset VAD states to clear any leftover audio from previous session
|
# Reset VAD states to clear any leftover audio from previous session
|
||||||
conn.reset_vad_states()
|
conn.reset_vad_states()
|
||||||
# Mark that we just started listening to prevent processing stale audio
|
# Mark that we just started listening to prevent processing stale audio
|
||||||
conn.just_started_listening = True
|
conn.just_started_listening = True
|
||||||
# Add initial connection flag to prevent false positive on first audio
|
# Set a timestamp for when we started listening
|
||||||
if not hasattr(conn, "initial_connection_handled"):
|
conn.listen_start_time = time.time()
|
||||||
conn.initial_connection_handled = False
|
# Add initial connection flag to prevent false positive on first audio
|
||||||
conn.initial_connection_time = asyncio.get_event_loop().time()
|
if not hasattr(conn, "initial_connection_handled"):
|
||||||
conn.client_have_voice = True
|
conn.initial_connection_handled = False
|
||||||
conn.client_voice_stop = False
|
conn.initial_connection_time = asyncio.get_event_loop().time()
|
||||||
elif msg_json["state"] == "stop":
|
conn.client_have_voice = True
|
||||||
conn.client_have_voice = True
|
conn.client_voice_stop = False
|
||||||
conn.client_voice_stop = True
|
elif msg_json["state"] == "stop":
|
||||||
if len(conn.asr_audio) > 0:
|
conn.client_have_voice = True
|
||||||
await handleAudioMessage(conn, b"")
|
conn.client_voice_stop = True
|
||||||
elif msg_json["state"] == "detect":
|
if len(conn.asr_audio) > 0:
|
||||||
conn.client_have_voice = False
|
await handleAudioMessage(conn, b"")
|
||||||
conn.asr_audio.clear()
|
elif msg_json["state"] == "detect":
|
||||||
if "text" in msg_json:
|
conn.client_have_voice = False
|
||||||
conn.last_activity_time = time.time() * 1000
|
conn.asr_audio.clear()
|
||||||
original_text = msg_json["text"] # Preserve original text
|
if "text" in msg_json:
|
||||||
filtered_len, filtered_text = remove_punctuation_and_length(
|
conn.last_activity_time = time.time() * 1000
|
||||||
original_text
|
original_text = msg_json["text"] # Preserve original text
|
||||||
)
|
filtered_len, filtered_text = remove_punctuation_and_length(
|
||||||
|
original_text
|
||||||
# Identify if it's a wake-up word
|
)
|
||||||
is_wakeup_words = filtered_text in conn.config.get(
|
|
||||||
"wakeup_words")
|
# Identify if it's a wake-up word
|
||||||
# Whether wake-up word reply is enabled
|
is_wakeup_words = filtered_text in conn.config.get(
|
||||||
enable_greeting = conn.config.get("enable_greeting", True)
|
"wakeup_words")
|
||||||
|
# Whether wake-up word reply is enabled
|
||||||
if is_wakeup_words and not enable_greeting:
|
enable_greeting = conn.config.get("enable_greeting", True)
|
||||||
# If it's a wake-up word and wake-up word reply is disabled, no need to respond
|
|
||||||
await send_stt_message(conn, original_text)
|
if is_wakeup_words and not enable_greeting:
|
||||||
await send_tts_message(conn, "stop", None)
|
# If it's a wake-up word and wake-up word reply is disabled, no need to respond
|
||||||
conn.client_is_speaking = False
|
await send_stt_message(conn, original_text)
|
||||||
elif is_wakeup_words:
|
await send_tts_message(conn, "stop", None)
|
||||||
conn.just_woken_up = True
|
conn.client_is_speaking = False
|
||||||
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
elif is_wakeup_words:
|
||||||
enqueue_asr_report(conn, "Hey, hello there", [])
|
conn.just_woken_up = True
|
||||||
await startToChat(conn, "Hey, hello there")
|
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
||||||
else:
|
enqueue_asr_report(conn, "Hey, hello there", [])
|
||||||
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
await startToChat(conn, "Hey, hello there")
|
||||||
enqueue_asr_report(conn, original_text, [])
|
else:
|
||||||
# Otherwise, need LLM to respond to text content
|
# Report plain text data (reuse ASR reporting function, but provide no audio data)
|
||||||
await startToChat(conn, original_text)
|
enqueue_asr_report(conn, original_text, [])
|
||||||
elif msg_json["type"] == "iot":
|
# Otherwise, need LLM to respond to text content
|
||||||
conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
|
await startToChat(conn, original_text)
|
||||||
if "descriptors" in msg_json:
|
elif msg_json["type"] == "iot":
|
||||||
asyncio.create_task(handleIotDescriptors(
|
conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
|
||||||
conn, msg_json["descriptors"]))
|
if "descriptors" in msg_json:
|
||||||
if "states" in msg_json:
|
asyncio.create_task(handleIotDescriptors(
|
||||||
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
|
conn, msg_json["descriptors"]))
|
||||||
elif msg_json["type"] == "mcp":
|
if "states" in msg_json:
|
||||||
conn.logger.bind(tag=TAG).info(
|
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
|
||||||
f"Received mcp message: {message[:100]}")
|
elif msg_json["type"] == "mcp":
|
||||||
if "payload" in msg_json:
|
conn.logger.bind(tag=TAG).info(
|
||||||
asyncio.create_task(
|
f"Received mcp message: {message[:100]}")
|
||||||
handle_mcp_message(conn, conn.mcp_client,
|
if "payload" in msg_json:
|
||||||
msg_json["payload"])
|
asyncio.create_task(
|
||||||
)
|
handle_mcp_message(conn, conn.mcp_client,
|
||||||
elif msg_json["type"] == "server":
|
msg_json["payload"])
|
||||||
# Filter sensitive information when logging
|
)
|
||||||
conn.logger.bind(tag=TAG).info(
|
elif msg_json["type"] == "server":
|
||||||
f"Received server message: {filter_sensitive_info(msg_json)}"
|
# Filter sensitive information when logging
|
||||||
)
|
conn.logger.bind(tag=TAG).info(
|
||||||
# If configuration is read from API, need to verify secret
|
f"Received server message: {filter_sensitive_info(msg_json)}"
|
||||||
if not conn.read_config_from_api:
|
)
|
||||||
return
|
# If configuration is read from API, need to verify secret
|
||||||
# Get secret from post request
|
if not conn.read_config_from_api:
|
||||||
post_secret = msg_json.get("content", {}).get("secret", "")
|
return
|
||||||
secret = conn.config["manager-api"].get("secret", "")
|
# Get secret from post request
|
||||||
# If secret doesn't match, return
|
post_secret = msg_json.get("content", {}).get("secret", "")
|
||||||
if post_secret != secret:
|
secret = conn.config["manager-api"].get("secret", "")
|
||||||
await conn.websocket.send(
|
# If secret doesn't match, return
|
||||||
json.dumps(
|
if post_secret != secret:
|
||||||
{
|
await conn.websocket.send(
|
||||||
"type": "server",
|
json.dumps(
|
||||||
"status": "error",
|
{
|
||||||
"message": "Server secret verification failed",
|
"type": "server",
|
||||||
}
|
"status": "error",
|
||||||
)
|
"message": "Server secret verification failed",
|
||||||
)
|
}
|
||||||
return
|
)
|
||||||
# Dynamically update configuration
|
)
|
||||||
if msg_json["action"] == "update_config":
|
return
|
||||||
try:
|
# Dynamically update configuration
|
||||||
# Update WebSocketServer configuration
|
if msg_json["action"] == "update_config":
|
||||||
if not conn.server:
|
try:
|
||||||
await conn.websocket.send(
|
# Update WebSocketServer configuration
|
||||||
json.dumps(
|
if not conn.server:
|
||||||
{
|
await conn.websocket.send(
|
||||||
"type": "server",
|
json.dumps(
|
||||||
"status": "error",
|
{
|
||||||
"message": "Cannot get server instance",
|
"type": "server",
|
||||||
"content": {"action": "update_config"},
|
"status": "error",
|
||||||
}
|
"message": "Cannot get server instance",
|
||||||
)
|
"content": {"action": "update_config"},
|
||||||
)
|
}
|
||||||
return
|
)
|
||||||
|
)
|
||||||
if not await conn.server.update_config():
|
return
|
||||||
await conn.websocket.send(
|
|
||||||
json.dumps(
|
if not await conn.server.update_config():
|
||||||
{
|
await conn.websocket.send(
|
||||||
"type": "server",
|
json.dumps(
|
||||||
"status": "error",
|
{
|
||||||
"message": "Failed to update server configuration",
|
"type": "server",
|
||||||
"content": {"action": "update_config"},
|
"status": "error",
|
||||||
}
|
"message": "Failed to update server configuration",
|
||||||
)
|
"content": {"action": "update_config"},
|
||||||
)
|
}
|
||||||
return
|
)
|
||||||
|
)
|
||||||
# Send success response
|
return
|
||||||
await conn.websocket.send(
|
|
||||||
json.dumps(
|
# Send success response
|
||||||
{
|
await conn.websocket.send(
|
||||||
"type": "server",
|
json.dumps(
|
||||||
"status": "success",
|
{
|
||||||
"message": "Configuration updated successfully",
|
"type": "server",
|
||||||
"content": {"action": "update_config"},
|
"status": "success",
|
||||||
}
|
"message": "Configuration updated successfully",
|
||||||
)
|
"content": {"action": "update_config"},
|
||||||
)
|
}
|
||||||
except Exception as e:
|
)
|
||||||
conn.logger.bind(tag=TAG).error(
|
)
|
||||||
f"Failed to update configuration: {str(e)}")
|
except Exception as e:
|
||||||
await conn.websocket.send(
|
conn.logger.bind(tag=TAG).error(
|
||||||
json.dumps(
|
f"Failed to update configuration: {str(e)}")
|
||||||
{
|
await conn.websocket.send(
|
||||||
"type": "server",
|
json.dumps(
|
||||||
"status": "error",
|
{
|
||||||
"message": f"Failed to update configuration: {str(e)}",
|
"type": "server",
|
||||||
"content": {"action": "update_config"},
|
"status": "error",
|
||||||
}
|
"message": f"Failed to update configuration: {str(e)}",
|
||||||
)
|
"content": {"action": "update_config"},
|
||||||
)
|
}
|
||||||
# Restart server
|
)
|
||||||
elif msg_json["action"] == "restart":
|
)
|
||||||
await conn.handle_restart(msg_json)
|
# Restart server
|
||||||
else:
|
elif msg_json["action"] == "restart":
|
||||||
conn.logger.bind(tag=TAG).error(
|
await conn.handle_restart(msg_json)
|
||||||
f"Received unknown type message: {message}")
|
else:
|
||||||
except json.JSONDecodeError:
|
conn.logger.bind(tag=TAG).error(
|
||||||
await conn.websocket.send(message)
|
f"Received unknown type message: {message}")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
await conn.websocket.send(message)
|
||||||
|
|
|
||||||
|
|
@ -1,376 +1,385 @@
|
||||||
import os
|
import os
|
||||||
import wave
|
import wave
|
||||||
import uuid
|
import uuid
|
||||||
import queue
|
import queue
|
||||||
import asyncio
|
import asyncio
|
||||||
import traceback
|
import traceback
|
||||||
import threading
|
import threading
|
||||||
import opuslib_next
|
import opuslib_next
|
||||||
import json
|
import json
|
||||||
import io
|
import io
|
||||||
import time
|
import time
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
import csv
|
import csv
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from typing import Optional, Tuple, List, Dict, Any
|
from typing import Optional, Tuple, List, Dict, Any
|
||||||
from core.handle.receiveAudioHandle import startToChat
|
from core.handle.receiveAudioHandle import startToChat
|
||||||
from core.handle.reportHandle import enqueue_asr_report
|
from core.handle.reportHandle import enqueue_asr_report
|
||||||
from core.utils.util import remove_punctuation_and_length
|
from core.utils.util import remove_punctuation_and_length
|
||||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
class ASRProviderBase(ABC):
|
class ASRProviderBase(ABC):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Open audio channels
|
# Open audio channels
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
conn.asr_priority_thread = threading.Thread(
|
conn.asr_priority_thread = threading.Thread(
|
||||||
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
||||||
)
|
)
|
||||||
conn.asr_priority_thread.start()
|
conn.asr_priority_thread.start()
|
||||||
|
|
||||||
# Process ASR audio in order
|
# Process ASR audio in order
|
||||||
def asr_text_priority_thread(self, conn):
|
def asr_text_priority_thread(self, conn):
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = conn.asr_audio_queue.get(timeout=1)
|
message = conn.asr_audio_queue.get(timeout=1)
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
handleAudioMessage(conn, message),
|
handleAudioMessage(conn, message),
|
||||||
conn.loop,
|
conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
|
f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Receive audio
|
# Receive audio
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
|
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
|
||||||
have_voice = audio_have_voice
|
have_voice = audio_have_voice
|
||||||
else:
|
else:
|
||||||
have_voice = conn.client_have_voice
|
have_voice = conn.client_have_voice
|
||||||
|
|
||||||
# Always add audio to pre-buffer (rolling buffer)
|
# Echo suppression: Ignore audio for a brief period after starting to listen
|
||||||
conn.audio_pre_buffer.append(audio)
|
if hasattr(conn, 'listen_start_time'):
|
||||||
|
time_since_listen_start = time.time() - conn.listen_start_time
|
||||||
# If voice is detected and we're not already collecting
|
if time_since_listen_start < 0.1: # Ignore first 300ms of audio (echo period)
|
||||||
if have_voice and not conn.client_have_voice:
|
if have_voice:
|
||||||
# Clear the just_started_listening flag when actual voice is detected
|
logger.bind(tag=TAG).debug(f"Ignoring potential echo audio ({time_since_listen_start:.2f}s after listen start)")
|
||||||
if hasattr(conn, 'just_started_listening'):
|
have_voice = False
|
||||||
conn.just_started_listening = False
|
|
||||||
# Add pre-buffered audio to the beginning of ASR audio
|
# Always add audio to pre-buffer (rolling buffer)
|
||||||
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
|
conn.audio_pre_buffer.append(audio)
|
||||||
conn.audio_pre_buffer.clear()
|
|
||||||
|
# If voice is detected and we're not already collecting
|
||||||
conn.asr_audio.append(audio)
|
if have_voice and not conn.client_have_voice:
|
||||||
if not have_voice and not conn.client_have_voice:
|
# Clear the just_started_listening flag when actual voice is detected
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
if hasattr(conn, 'just_started_listening'):
|
||||||
return
|
conn.just_started_listening = False
|
||||||
|
# Add pre-buffered audio to the beginning of ASR audio
|
||||||
if conn.client_voice_stop:
|
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
|
||||||
# Check if we just started listening - if so, skip this audio
|
conn.audio_pre_buffer.clear()
|
||||||
if hasattr(conn, 'just_started_listening') and conn.just_started_listening:
|
|
||||||
logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start")
|
conn.asr_audio.append(audio)
|
||||||
conn.just_started_listening = False
|
if not have_voice and not conn.client_have_voice:
|
||||||
conn.asr_audio.clear()
|
conn.asr_audio = conn.asr_audio[-10:]
|
||||||
conn.reset_vad_states()
|
return
|
||||||
return
|
|
||||||
|
if conn.client_voice_stop:
|
||||||
asr_audio_task = conn.asr_audio.copy()
|
# Check if we just started listening - if so, skip this audio
|
||||||
conn.asr_audio.clear()
|
if hasattr(conn, 'just_started_listening') and conn.just_started_listening:
|
||||||
conn.reset_vad_states()
|
logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start")
|
||||||
|
conn.just_started_listening = False
|
||||||
if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds)
|
conn.asr_audio.clear()
|
||||||
logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks")
|
conn.reset_vad_states()
|
||||||
await self.handle_voice_stop(conn, asr_audio_task)
|
return
|
||||||
|
|
||||||
# Handle voice stop
|
asr_audio_task = conn.asr_audio.copy()
|
||||||
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
conn.asr_audio.clear()
|
||||||
"""Parallel processing of ASR and voiceprint recognition"""
|
conn.reset_vad_states()
|
||||||
try:
|
|
||||||
total_start_time = time.monotonic()
|
if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds)
|
||||||
|
logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks")
|
||||||
# Prepare audio data
|
await self.handle_voice_stop(conn, asr_audio_task)
|
||||||
if conn.audio_format == "pcm":
|
|
||||||
pcm_data = asr_audio_task
|
# Handle voice stop
|
||||||
else:
|
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
||||||
pcm_data = self.decode_opus(asr_audio_task)
|
"""Parallel processing of ASR and voiceprint recognition"""
|
||||||
|
try:
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
total_start_time = time.monotonic()
|
||||||
|
|
||||||
# Pre-prepare WAV data
|
# Prepare audio data
|
||||||
wav_data = None
|
if conn.audio_format == "pcm":
|
||||||
# Use connection's voiceprint provider
|
pcm_data = asr_audio_task
|
||||||
if conn.voiceprint_provider and combined_pcm_data:
|
else:
|
||||||
wav_data = self._pcm_to_wav(combined_pcm_data)
|
pcm_data = self.decode_opus(asr_audio_task)
|
||||||
|
|
||||||
# Define ASR task
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
def run_asr():
|
# Pre-prepare WAV data
|
||||||
start_time = time.monotonic()
|
wav_data = None
|
||||||
try:
|
# Use connection's voiceprint provider
|
||||||
loop = asyncio.new_event_loop()
|
if conn.voiceprint_provider and combined_pcm_data:
|
||||||
asyncio.set_event_loop(loop)
|
wav_data = self._pcm_to_wav(combined_pcm_data)
|
||||||
try:
|
|
||||||
result = loop.run_until_complete(
|
# Define ASR task
|
||||||
self.speech_to_text(
|
|
||||||
asr_audio_task, conn.session_id, conn.audio_format)
|
def run_asr():
|
||||||
)
|
start_time = time.monotonic()
|
||||||
end_time = time.monotonic()
|
try:
|
||||||
logger.bind(tag=TAG).info(
|
loop = asyncio.new_event_loop()
|
||||||
f"ASR time: {end_time - start_time:.3f}s")
|
asyncio.set_event_loop(loop)
|
||||||
return result
|
try:
|
||||||
finally:
|
result = loop.run_until_complete(
|
||||||
loop.close()
|
self.speech_to_text(
|
||||||
except Exception as e:
|
asr_audio_task, conn.session_id, conn.audio_format)
|
||||||
end_time = time.monotonic()
|
)
|
||||||
logger.bind(tag=TAG).error(f"ASR failed: {e}")
|
end_time = time.monotonic()
|
||||||
return ("", None)
|
logger.bind(tag=TAG).info(
|
||||||
|
f"ASR time: {end_time - start_time:.3f}s")
|
||||||
# Define voiceprint recognition task
|
return result
|
||||||
def run_voiceprint():
|
finally:
|
||||||
if not wav_data:
|
loop.close()
|
||||||
return None
|
except Exception as e:
|
||||||
try:
|
end_time = time.monotonic()
|
||||||
loop = asyncio.new_event_loop()
|
logger.bind(tag=TAG).error(f"ASR failed: {e}")
|
||||||
asyncio.set_event_loop(loop)
|
return ("", None)
|
||||||
try:
|
|
||||||
# Use connection's voiceprint provider
|
# Define voiceprint recognition task
|
||||||
result = loop.run_until_complete(
|
def run_voiceprint():
|
||||||
conn.voiceprint_provider.identify_speaker(
|
if not wav_data:
|
||||||
wav_data, conn.session_id)
|
return None
|
||||||
)
|
try:
|
||||||
return result
|
loop = asyncio.new_event_loop()
|
||||||
finally:
|
asyncio.set_event_loop(loop)
|
||||||
loop.close()
|
try:
|
||||||
except Exception as e:
|
# Use connection's voiceprint provider
|
||||||
logger.bind(tag=TAG).error(
|
result = loop.run_until_complete(
|
||||||
f"Voiceprint recognition failed: {e}")
|
conn.voiceprint_provider.identify_speaker(
|
||||||
return None
|
wav_data, conn.session_id)
|
||||||
|
)
|
||||||
# Run in parallel using thread pool executor
|
return result
|
||||||
parallel_start_time = time.monotonic()
|
finally:
|
||||||
|
loop.close()
|
||||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
|
except Exception as e:
|
||||||
asr_future = thread_executor.submit(run_asr)
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Voiceprint recognition failed: {e}")
|
||||||
if conn.voiceprint_provider and wav_data:
|
return None
|
||||||
voiceprint_future = thread_executor.submit(run_voiceprint)
|
|
||||||
|
# Run in parallel using thread pool executor
|
||||||
# Wait for both threads to complete
|
parallel_start_time = time.monotonic()
|
||||||
asr_result = asr_future.result(timeout=15)
|
|
||||||
voiceprint_result = voiceprint_future.result(timeout=15)
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
|
||||||
|
asr_future = thread_executor.submit(run_asr)
|
||||||
results = {"asr": asr_result,
|
|
||||||
"voiceprint": voiceprint_result}
|
if conn.voiceprint_provider and wav_data:
|
||||||
else:
|
voiceprint_future = thread_executor.submit(run_voiceprint)
|
||||||
asr_result = asr_future.result(timeout=15)
|
|
||||||
results = {"asr": asr_result, "voiceprint": None}
|
# Wait for both threads to complete
|
||||||
|
asr_result = asr_future.result(timeout=15)
|
||||||
# Process results
|
voiceprint_result = voiceprint_future.result(timeout=15)
|
||||||
raw_text, file_path = results.get("asr", ("", None))
|
|
||||||
speaker_name = results.get("voiceprint", None)
|
results = {"asr": asr_result,
|
||||||
|
"voiceprint": voiceprint_result}
|
||||||
# Log recognition results
|
else:
|
||||||
if raw_text:
|
asr_result = asr_future.result(timeout=15)
|
||||||
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
|
results = {"asr": asr_result, "voiceprint": None}
|
||||||
if speaker_name:
|
|
||||||
logger.bind(tag=TAG).info(
|
# Process results
|
||||||
f"Identified speaker: {speaker_name}")
|
raw_text, file_path = results.get("asr", ("", None))
|
||||||
|
speaker_name = results.get("voiceprint", None)
|
||||||
# Performance monitoring
|
|
||||||
total_time = time.monotonic() - total_start_time
|
# Log recognition results
|
||||||
logger.bind(tag=TAG).info(
|
if raw_text:
|
||||||
f"Total processing time: {total_time:.3f}s")
|
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
|
||||||
|
if speaker_name:
|
||||||
# Check text length
|
logger.bind(tag=TAG).info(
|
||||||
text_len, _ = remove_punctuation_and_length(raw_text)
|
f"Identified speaker: {speaker_name}")
|
||||||
self.stop_ws_connection()
|
|
||||||
|
# Performance monitoring
|
||||||
if text_len > 0:
|
total_time = time.monotonic() - total_start_time
|
||||||
# Build JSON string with speaker information
|
logger.bind(tag=TAG).info(
|
||||||
enhanced_text = self._build_enhanced_text(
|
f"Total processing time: {total_time:.3f}s")
|
||||||
raw_text, speaker_name)
|
|
||||||
|
# Check text length
|
||||||
# Use custom module for reporting
|
text_len, _ = remove_punctuation_and_length(raw_text)
|
||||||
await startToChat(conn, enhanced_text)
|
self.stop_ws_connection()
|
||||||
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
|
||||||
|
if text_len > 0:
|
||||||
except Exception as e:
|
# Build JSON string with speaker information
|
||||||
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
|
enhanced_text = self._build_enhanced_text(
|
||||||
import traceback
|
raw_text, speaker_name)
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"Exception details: {traceback.format_exc()}")
|
# Use custom module for reporting
|
||||||
|
await startToChat(conn, enhanced_text)
|
||||||
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
||||||
"""Build text with speaker information"""
|
|
||||||
if speaker_name and speaker_name.strip():
|
except Exception as e:
|
||||||
return json.dumps({
|
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
|
||||||
"speaker": speaker_name,
|
import traceback
|
||||||
"content": text
|
logger.bind(tag=TAG).debug(
|
||||||
}, ensure_ascii=False)
|
f"Exception details: {traceback.format_exc()}")
|
||||||
else:
|
|
||||||
return text
|
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
||||||
|
"""Build text with speaker information"""
|
||||||
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
|
if speaker_name and speaker_name.strip():
|
||||||
"""Convert PCM data to WAV format"""
|
return json.dumps({
|
||||||
if len(pcm_data) == 0:
|
"speaker": speaker_name,
|
||||||
logger.bind(tag=TAG).warning(
|
"content": text
|
||||||
"PCM data is empty, cannot convert to WAV")
|
}, ensure_ascii=False)
|
||||||
return b""
|
else:
|
||||||
|
return text
|
||||||
# Ensure data length is even (16-bit audio)
|
|
||||||
if len(pcm_data) % 2 != 0:
|
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
|
||||||
pcm_data = pcm_data[:-1]
|
"""Convert PCM data to WAV format"""
|
||||||
|
if len(pcm_data) == 0:
|
||||||
# Create WAV file header
|
logger.bind(tag=TAG).warning(
|
||||||
wav_buffer = io.BytesIO()
|
"PCM data is empty, cannot convert to WAV")
|
||||||
try:
|
return b""
|
||||||
with wave.open(wav_buffer, 'wb') as wav_file:
|
|
||||||
wav_file.setnchannels(1) # Mono
|
# Ensure data length is even (16-bit audio)
|
||||||
wav_file.setsampwidth(2) # 16-bit
|
if len(pcm_data) % 2 != 0:
|
||||||
wav_file.setframerate(16000) # 16kHz sample rate
|
pcm_data = pcm_data[:-1]
|
||||||
wav_file.writeframes(pcm_data)
|
|
||||||
|
# Create WAV file header
|
||||||
wav_buffer.seek(0)
|
wav_buffer = io.BytesIO()
|
||||||
wav_data = wav_buffer.read()
|
try:
|
||||||
|
with wave.open(wav_buffer, 'wb') as wav_file:
|
||||||
return wav_data
|
wav_file.setnchannels(1) # Mono
|
||||||
except Exception as e:
|
wav_file.setsampwidth(2) # 16-bit
|
||||||
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
|
wav_file.setframerate(16000) # 16kHz sample rate
|
||||||
return b""
|
wav_file.writeframes(pcm_data)
|
||||||
|
|
||||||
def stop_ws_connection(self):
|
wav_buffer.seek(0)
|
||||||
pass
|
wav_data = wav_buffer.read()
|
||||||
|
|
||||||
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
return wav_data
|
||||||
"""Save PCM data as WAV file"""
|
except Exception as e:
|
||||||
module_name = __name__.split(".")[-1]
|
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
|
||||||
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
|
return b""
|
||||||
file_path = os.path.join(self.output_dir, file_name)
|
|
||||||
|
def stop_ws_connection(self):
|
||||||
with wave.open(file_path, "wb") as wf:
|
pass
|
||||||
wf.setnchannels(1)
|
|
||||||
wf.setsampwidth(2) # 2 bytes = 16-bit
|
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
||||||
wf.setframerate(16000)
|
"""Save PCM data as WAV file"""
|
||||||
wf.writeframes(b"".join(pcm_data))
|
module_name = __name__.split(".")[-1]
|
||||||
|
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
|
||||||
return file_path
|
file_path = os.path.join(self.output_dir, file_name)
|
||||||
|
|
||||||
def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str):
|
with wave.open(file_path, "wb") as wf:
|
||||||
"""Log audio file information to CSV file"""
|
wf.setnchannels(1)
|
||||||
try:
|
wf.setsampwidth(2) # 2 bytes = 16-bit
|
||||||
# Create logs directory at the same level as output_dir
|
wf.setframerate(16000)
|
||||||
log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs")
|
wf.writeframes(b"".join(pcm_data))
|
||||||
os.makedirs(log_dir, exist_ok=True)
|
|
||||||
|
return file_path
|
||||||
# Create both CSV and JSON log files for easy inspection
|
|
||||||
csv_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.csv")
|
def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str):
|
||||||
json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json")
|
"""Log audio file information to CSV file"""
|
||||||
|
try:
|
||||||
# Write to CSV file
|
# Create logs directory at the same level as output_dir
|
||||||
csv_exists = os.path.exists(csv_log_file)
|
log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs")
|
||||||
with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile:
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript']
|
|
||||||
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
# Create both CSV and JSON log files for easy inspection
|
||||||
|
csv_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.csv")
|
||||||
if not csv_exists:
|
json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json")
|
||||||
writer.writeheader()
|
|
||||||
|
# Write to CSV file
|
||||||
writer.writerow({
|
csv_exists = os.path.exists(csv_log_file)
|
||||||
'timestamp': datetime.now().isoformat(),
|
with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile:
|
||||||
'filename': os.path.basename(file_path),
|
fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript']
|
||||||
'file_path': file_path,
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
||||||
'audio_length_seconds': round(audio_length_seconds, 2),
|
|
||||||
'transcript': transcript
|
if not csv_exists:
|
||||||
})
|
writer.writeheader()
|
||||||
|
|
||||||
# Also write to JSON file for easier parsing
|
writer.writerow({
|
||||||
log_entry = {
|
'timestamp': datetime.now().isoformat(),
|
||||||
'timestamp': datetime.now().isoformat(),
|
'filename': os.path.basename(file_path),
|
||||||
'filename': os.path.basename(file_path),
|
'file_path': file_path,
|
||||||
'file_path': file_path,
|
'audio_length_seconds': round(audio_length_seconds, 2),
|
||||||
'audio_length_seconds': round(audio_length_seconds, 2),
|
'transcript': transcript
|
||||||
'transcript': transcript
|
})
|
||||||
}
|
|
||||||
|
# Also write to JSON file for easier parsing
|
||||||
# Read existing JSON logs or create new list
|
log_entry = {
|
||||||
json_logs = []
|
'timestamp': datetime.now().isoformat(),
|
||||||
if os.path.exists(json_log_file):
|
'filename': os.path.basename(file_path),
|
||||||
try:
|
'file_path': file_path,
|
||||||
with open(json_log_file, 'r', encoding='utf-8') as f:
|
'audio_length_seconds': round(audio_length_seconds, 2),
|
||||||
json_logs = json.load(f)
|
'transcript': transcript
|
||||||
except:
|
}
|
||||||
json_logs = []
|
|
||||||
|
# Read existing JSON logs or create new list
|
||||||
json_logs.append(log_entry)
|
json_logs = []
|
||||||
|
if os.path.exists(json_log_file):
|
||||||
# Write updated JSON logs
|
try:
|
||||||
with open(json_log_file, 'w', encoding='utf-8') as f:
|
with open(json_log_file, 'r', encoding='utf-8') as f:
|
||||||
json.dump(json_logs, f, ensure_ascii=False, indent=2)
|
json_logs = json.load(f)
|
||||||
|
except:
|
||||||
# Also create a simple text log for quick inspection
|
json_logs = []
|
||||||
txt_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.txt")
|
|
||||||
with open(txt_log_file, 'a', encoding='utf-8') as f:
|
json_logs.append(log_entry)
|
||||||
f.write(f"\n{'='*80}\n")
|
|
||||||
f.write(f"Timestamp: {datetime.now().isoformat()}\n")
|
# Write updated JSON logs
|
||||||
f.write(f"Filename: {os.path.basename(file_path)}\n")
|
with open(json_log_file, 'w', encoding='utf-8') as f:
|
||||||
f.write(f"Full Path: {file_path}\n")
|
json.dump(json_logs, f, ensure_ascii=False, indent=2)
|
||||||
f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n")
|
|
||||||
f.write(f"Transcript: {transcript}\n")
|
# Also create a simple text log for quick inspection
|
||||||
f.write(f"{'='*80}\n")
|
txt_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.txt")
|
||||||
|
with open(txt_log_file, 'a', encoding='utf-8') as f:
|
||||||
logger.bind(tag=TAG).info(
|
f.write(f"\n{'='*80}\n")
|
||||||
f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, "
|
f.write(f"Timestamp: {datetime.now().isoformat()}\n")
|
||||||
f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..."
|
f.write(f"Filename: {os.path.basename(file_path)}\n")
|
||||||
)
|
f.write(f"Full Path: {file_path}\n")
|
||||||
except Exception as e:
|
f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n")
|
||||||
logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}")
|
f.write(f"Transcript: {transcript}\n")
|
||||||
|
f.write(f"{'='*80}\n")
|
||||||
@abstractmethod
|
|
||||||
async def speech_to_text(
|
# Logging disabled - comment out the log message
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
# logger.bind(tag=TAG).info(
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
# f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, "
|
||||||
"""Convert speech data to text"""
|
# f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..."
|
||||||
pass
|
# )
|
||||||
|
except Exception as e:
|
||||||
@staticmethod
|
logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}")
|
||||||
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
|
|
||||||
"""Decode Opus audio data to PCM data"""
|
@abstractmethod
|
||||||
try:
|
async def speech_to_text(
|
||||||
decoder = opuslib_next.Decoder(16000, 1)
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
pcm_data = []
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
|
"""Convert speech data to text"""
|
||||||
|
pass
|
||||||
for i, opus_packet in enumerate(opus_data):
|
|
||||||
try:
|
@staticmethod
|
||||||
if not opus_packet or len(opus_packet) == 0:
|
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
|
||||||
continue
|
"""Decode Opus audio data to PCM data"""
|
||||||
|
try:
|
||||||
pcm_frame = decoder.decode(opus_packet, buffer_size)
|
decoder = opuslib_next.Decoder(16000, 1)
|
||||||
if pcm_frame and len(pcm_frame) > 0:
|
pcm_data = []
|
||||||
pcm_data.append(pcm_frame)
|
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
|
||||||
|
|
||||||
except opuslib_next.OpusError as e:
|
for i, opus_packet in enumerate(opus_data):
|
||||||
logger.bind(tag=TAG).warning(
|
try:
|
||||||
f"Opus decode error, skipping packet {i}: {e}")
|
if not opus_packet or len(opus_packet) == 0:
|
||||||
except Exception as e:
|
continue
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"Audio processing error, packet {i}: {e}")
|
pcm_frame = decoder.decode(opus_packet, buffer_size)
|
||||||
|
if pcm_frame and len(pcm_frame) > 0:
|
||||||
return pcm_data
|
pcm_data.append(pcm_frame)
|
||||||
|
|
||||||
except Exception as e:
|
except opuslib_next.OpusError as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).warning(
|
||||||
f"Error occurred during audio decoding: {e}")
|
f"Opus decode error, skipping packet {i}: {e}")
|
||||||
return []
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Audio processing error, packet {i}: {e}")
|
||||||
|
|
||||||
|
return pcm_data
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"Error occurred during audio decoding: {e}")
|
||||||
|
return []
|
||||||
|
|
|
||||||
|
|
@ -1,384 +1,384 @@
|
||||||
import time
|
import time
|
||||||
import wave
|
import wave
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import io
|
import io
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from typing import Optional, Tuple, List
|
from typing import Optional, Tuple, List
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import sherpa_onnx
|
import sherpa_onnx
|
||||||
|
|
||||||
from modelscope.hub.file_download import model_file_download
|
from modelscope.hub.file_download import model_file_download
|
||||||
try:
|
try:
|
||||||
from huggingface_hub import hf_hub_download
|
from huggingface_hub import hf_hub_download
|
||||||
HF_AVAILABLE = True
|
HF_AVAILABLE = True
|
||||||
except ImportError:
|
except ImportError:
|
||||||
HF_AVAILABLE = False
|
HF_AVAILABLE = False
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import tarfile
|
import tarfile
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
# Capture standard output
|
# Capture standard output
|
||||||
class CaptureOutput:
|
class CaptureOutput:
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
self._output = io.StringIO()
|
self._output = io.StringIO()
|
||||||
self._original_stdout = sys.stdout
|
self._original_stdout = sys.stdout
|
||||||
sys.stdout = self._output
|
sys.stdout = self._output
|
||||||
|
|
||||||
def __exit__(self, exc_type, exc_value, traceback):
|
def __exit__(self, exc_type, exc_value, traceback):
|
||||||
sys.stdout = self._original_stdout
|
sys.stdout = self._original_stdout
|
||||||
self.output = self._output.getvalue()
|
self.output = self._output.getvalue()
|
||||||
self._output.close()
|
self._output.close()
|
||||||
|
|
||||||
# Output captured content through logger
|
# Output captured content through logger
|
||||||
if self.output:
|
if self.output:
|
||||||
logger.bind(tag=TAG).info(self.output.strip())
|
logger.bind(tag=TAG).info(self.output.strip())
|
||||||
|
|
||||||
|
|
||||||
class ASRProvider(ASRProviderBase):
|
class ASRProvider(ASRProviderBase):
|
||||||
def __init__(self, config: dict, delete_audio_file: bool):
|
def __init__(self, config: dict, delete_audio_file: bool):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.interface_type = InterfaceType.LOCAL
|
self.interface_type = InterfaceType.LOCAL
|
||||||
self.model_dir = config.get("model_dir")
|
self.model_dir = config.get("model_dir")
|
||||||
self.output_dir = config.get("output_dir")
|
self.output_dir = config.get("output_dir")
|
||||||
self.model_type = config.get(
|
self.model_type = config.get(
|
||||||
"model_type", "sense_voice") # Support paraformer
|
"model_type", "sense_voice") # Support paraformer
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
|
|
||||||
# Ensure output directory exists
|
# Ensure output directory exists
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
# Initialize model file paths based on model type
|
# Initialize model file paths based on model type
|
||||||
model_files = self._get_model_files_for_type()
|
model_files = self._get_model_files_for_type()
|
||||||
|
|
||||||
# Download and check model files
|
# Download and check model files
|
||||||
try:
|
try:
|
||||||
# Determine model source and ID based on model directory name
|
# Determine model source and ID based on model directory name
|
||||||
model_info = self._get_model_id_from_dir()
|
model_info = self._get_model_id_from_dir()
|
||||||
|
|
||||||
# Check if we need to download the entire model from GitHub
|
# Check if we need to download the entire model from GitHub
|
||||||
if model_info["source"] == "github":
|
if model_info["source"] == "github":
|
||||||
# For GitHub models, check if any files are missing and download the whole archive
|
# For GitHub models, check if any files are missing and download the whole archive
|
||||||
missing_files = [f for f in model_files.values() if not os.path.isfile(f)]
|
missing_files = [f for f in model_files.values() if not os.path.isfile(f)]
|
||||||
if missing_files:
|
if missing_files:
|
||||||
logger.bind(tag=TAG).info("Downloading complete model from GitHub...")
|
logger.bind(tag=TAG).info("Downloading complete model from GitHub...")
|
||||||
self._download_from_github(model_info["url"], self.model_dir)
|
self._download_from_github(model_info["url"], self.model_dir)
|
||||||
else:
|
else:
|
||||||
# For individual file downloads (HuggingFace/ModelScope)
|
# For individual file downloads (HuggingFace/ModelScope)
|
||||||
for file_name, file_path in model_files.items():
|
for file_name, file_path in model_files.items():
|
||||||
if not os.path.isfile(file_path):
|
if not os.path.isfile(file_path):
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"Downloading model file: {file_name}")
|
f"Downloading model file: {file_name}")
|
||||||
|
|
||||||
if model_info["source"] == "huggingface" and HF_AVAILABLE:
|
if model_info["source"] == "huggingface" and HF_AVAILABLE:
|
||||||
# Use Hugging Face Hub
|
# Use Hugging Face Hub
|
||||||
try:
|
try:
|
||||||
hf_hub_download(
|
hf_hub_download(
|
||||||
repo_id=model_info["model_id"],
|
repo_id=model_info["model_id"],
|
||||||
filename=file_name,
|
filename=file_name,
|
||||||
local_dir=self.model_dir,
|
local_dir=self.model_dir,
|
||||||
local_dir_use_symlinks=False
|
local_dir_use_symlinks=False
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
f"HuggingFace download failed: {e}, trying ModelScope...")
|
f"HuggingFace download failed: {e}, trying ModelScope...")
|
||||||
# Fallback to ModelScope
|
# Fallback to ModelScope
|
||||||
model_file_download(
|
model_file_download(
|
||||||
model_id=model_info["model_id"],
|
model_id=model_info["model_id"],
|
||||||
file_path=file_name,
|
file_path=file_name,
|
||||||
local_dir=self.model_dir,
|
local_dir=self.model_dir,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Use ModelScope
|
# Use ModelScope
|
||||||
model_file_download(
|
model_file_download(
|
||||||
model_id=model_info["model_id"],
|
model_id=model_info["model_id"],
|
||||||
file_path=file_name,
|
file_path=file_name,
|
||||||
local_dir=self.model_dir,
|
local_dir=self.model_dir,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Verify all files exist after download
|
# Verify all files exist after download
|
||||||
for file_name, file_path in model_files.items():
|
for file_name, file_path in model_files.items():
|
||||||
if not os.path.isfile(file_path):
|
if not os.path.isfile(file_path):
|
||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
f"Model file not found after download: {file_path}")
|
f"Model file not found after download: {file_path}")
|
||||||
|
|
||||||
# Set model paths based on type
|
# Set model paths based on type
|
||||||
if self.model_type == "whisper":
|
if self.model_type == "whisper":
|
||||||
self.encoder_path = list(model_files.values())[0] # encoder
|
self.encoder_path = list(model_files.values())[0] # encoder
|
||||||
self.decoder_path = list(model_files.values())[1] # decoder
|
self.decoder_path = list(model_files.values())[1] # decoder
|
||||||
self.tokens_path = list(model_files.values())[2] # tokens
|
self.tokens_path = list(model_files.values())[2] # tokens
|
||||||
elif self.model_type == "zipformer":
|
elif self.model_type == "zipformer":
|
||||||
# Handle different zipformer file naming patterns
|
# Handle different zipformer file naming patterns
|
||||||
model_name = os.path.basename(self.model_dir)
|
model_name = os.path.basename(self.model_dir)
|
||||||
if "gigaspeech" in model_name:
|
if "gigaspeech" in model_name:
|
||||||
self.encoder_path = model_files["encoder-epoch-30-avg-1.onnx"]
|
self.encoder_path = model_files["encoder-epoch-30-avg-1.onnx"]
|
||||||
self.decoder_path = model_files["decoder-epoch-30-avg-1.onnx"]
|
self.decoder_path = model_files["decoder-epoch-30-avg-1.onnx"]
|
||||||
self.joiner_path = model_files["joiner-epoch-30-avg-1.onnx"]
|
self.joiner_path = model_files["joiner-epoch-30-avg-1.onnx"]
|
||||||
else:
|
else:
|
||||||
self.encoder_path = model_files["encoder-epoch-99-avg-1.onnx"]
|
self.encoder_path = model_files["encoder-epoch-99-avg-1.onnx"]
|
||||||
self.decoder_path = model_files["decoder-epoch-99-avg-1.onnx"]
|
self.decoder_path = model_files["decoder-epoch-99-avg-1.onnx"]
|
||||||
self.joiner_path = model_files["joiner-epoch-99-avg-1.onnx"]
|
self.joiner_path = model_files["joiner-epoch-99-avg-1.onnx"]
|
||||||
self.tokens_path = model_files["tokens.txt"]
|
self.tokens_path = model_files["tokens.txt"]
|
||||||
else:
|
else:
|
||||||
self.model_path = model_files["model.int8.onnx"]
|
self.model_path = model_files["model.int8.onnx"]
|
||||||
self.tokens_path = model_files["tokens.txt"]
|
self.tokens_path = model_files["tokens.txt"]
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"Model file processing failed: {str(e)}")
|
f"Model file processing failed: {str(e)}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
# Initialize the model
|
# Initialize the model
|
||||||
self._initialize_model()
|
self._initialize_model()
|
||||||
|
|
||||||
def _get_model_id_from_dir(self) -> str:
|
def _get_model_id_from_dir(self) -> str:
|
||||||
"""Determine ModelScope model ID based on model directory name"""
|
"""Determine ModelScope model ID based on model directory name"""
|
||||||
dir_name = os.path.basename(self.model_dir)
|
dir_name = os.path.basename(self.model_dir)
|
||||||
|
|
||||||
# Map directory names to model sources (ModelScope and HuggingFace)
|
# Map directory names to model sources (ModelScope and HuggingFace)
|
||||||
model_mapping = {
|
model_mapping = {
|
||||||
# Multilingual models
|
# Multilingual models
|
||||||
"sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": {
|
"sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": {
|
||||||
"source": "modelscope",
|
"source": "modelscope",
|
||||||
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
|
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
|
||||||
},
|
},
|
||||||
|
|
||||||
# English-only Whisper models (HuggingFace - more reliable)
|
# English-only Whisper models (HuggingFace - more reliable)
|
||||||
"sherpa-onnx-whisper-tiny.en": {
|
"sherpa-onnx-whisper-tiny.en": {
|
||||||
"source": "huggingface",
|
"source": "huggingface",
|
||||||
"model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en"
|
"model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en"
|
||||||
},
|
},
|
||||||
"sherpa-onnx-whisper-base.en": {
|
"sherpa-onnx-whisper-base.en": {
|
||||||
"source": "huggingface",
|
"source": "huggingface",
|
||||||
"model_id": "csukuangfj/sherpa-onnx-whisper-base.en"
|
"model_id": "csukuangfj/sherpa-onnx-whisper-base.en"
|
||||||
},
|
},
|
||||||
"sherpa-onnx-whisper-small.en": {
|
"sherpa-onnx-whisper-small.en": {
|
||||||
"source": "huggingface",
|
"source": "huggingface",
|
||||||
"model_id": "csukuangfj/sherpa-onnx-whisper-small.en"
|
"model_id": "csukuangfj/sherpa-onnx-whisper-small.en"
|
||||||
},
|
},
|
||||||
"sherpa-onnx-whisper-medium.en": {
|
"sherpa-onnx-whisper-medium.en": {
|
||||||
"source": "huggingface",
|
"source": "huggingface",
|
||||||
"model_id": "csukuangfj/sherpa-onnx-whisper-medium.en"
|
"model_id": "csukuangfj/sherpa-onnx-whisper-medium.en"
|
||||||
},
|
},
|
||||||
|
|
||||||
# English-only Zipformer models (HuggingFace)
|
# English-only Zipformer models (HuggingFace)
|
||||||
"sherpa-onnx-zipformer-en-2023-04-01": {
|
"sherpa-onnx-zipformer-en-2023-04-01": {
|
||||||
"source": "huggingface",
|
"source": "huggingface",
|
||||||
"model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01"
|
"model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01"
|
||||||
},
|
},
|
||||||
"sherpa-onnx-zipformer-gigaspeech-2023-12-12": {
|
"sherpa-onnx-zipformer-gigaspeech-2023-12-12": {
|
||||||
"source": "github",
|
"source": "github",
|
||||||
"model_id": "sherpa-onnx-zipformer-gigaspeech-2023-12-12",
|
"model_id": "sherpa-onnx-zipformer-gigaspeech-2023-12-12",
|
||||||
"url": "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2"
|
"url": "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-zipformer-gigaspeech-2023-12-12.tar.bz2"
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
return model_mapping.get(dir_name, {
|
return model_mapping.get(dir_name, {
|
||||||
"source": "modelscope",
|
"source": "modelscope",
|
||||||
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
|
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
|
||||||
})
|
})
|
||||||
|
|
||||||
def _get_model_files_for_type(self) -> dict:
|
def _get_model_files_for_type(self) -> dict:
|
||||||
"""Get required model files based on model type"""
|
"""Get required model files based on model type"""
|
||||||
if self.model_type == "whisper":
|
if self.model_type == "whisper":
|
||||||
# Dynamic file names based on model directory
|
# Dynamic file names based on model directory
|
||||||
model_name = os.path.basename(self.model_dir)
|
model_name = os.path.basename(self.model_dir)
|
||||||
if "tiny.en" in model_name:
|
if "tiny.en" in model_name:
|
||||||
prefix = "tiny.en"
|
prefix = "tiny.en"
|
||||||
elif "base.en" in model_name:
|
elif "base.en" in model_name:
|
||||||
prefix = "base.en"
|
prefix = "base.en"
|
||||||
elif "small.en" in model_name:
|
elif "small.en" in model_name:
|
||||||
prefix = "small.en"
|
prefix = "small.en"
|
||||||
elif "medium.en" in model_name:
|
elif "medium.en" in model_name:
|
||||||
prefix = "medium.en"
|
prefix = "medium.en"
|
||||||
else:
|
else:
|
||||||
prefix = "tiny.en" # default
|
prefix = "tiny.en" # default
|
||||||
|
|
||||||
return {
|
return {
|
||||||
f"{prefix}-encoder.onnx": os.path.join(self.model_dir, f"{prefix}-encoder.onnx"),
|
f"{prefix}-encoder.onnx": os.path.join(self.model_dir, f"{prefix}-encoder.onnx"),
|
||||||
f"{prefix}-decoder.onnx": os.path.join(self.model_dir, f"{prefix}-decoder.onnx"),
|
f"{prefix}-decoder.onnx": os.path.join(self.model_dir, f"{prefix}-decoder.onnx"),
|
||||||
f"{prefix}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"),
|
f"{prefix}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"),
|
||||||
}
|
}
|
||||||
elif self.model_type == "zipformer":
|
elif self.model_type == "zipformer":
|
||||||
# Check for different zipformer file naming patterns
|
# Check for different zipformer file naming patterns
|
||||||
model_name = os.path.basename(self.model_dir)
|
model_name = os.path.basename(self.model_dir)
|
||||||
if "gigaspeech" in model_name:
|
if "gigaspeech" in model_name:
|
||||||
return {
|
return {
|
||||||
"encoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-30-avg-1.onnx"),
|
"encoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-30-avg-1.onnx"),
|
||||||
"decoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-30-avg-1.onnx"),
|
"decoder-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-30-avg-1.onnx"),
|
||||||
"joiner-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-30-avg-1.onnx"),
|
"joiner-epoch-30-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-30-avg-1.onnx"),
|
||||||
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
return {
|
return {
|
||||||
"encoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-99-avg-1.onnx"),
|
"encoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "encoder-epoch-99-avg-1.onnx"),
|
||||||
"decoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-99-avg-1.onnx"),
|
"decoder-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "decoder-epoch-99-avg-1.onnx"),
|
||||||
"joiner-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-99-avg-1.onnx"),
|
"joiner-epoch-99-avg-1.onnx": os.path.join(self.model_dir, "joiner-epoch-99-avg-1.onnx"),
|
||||||
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
||||||
}
|
}
|
||||||
else: # sense_voice or paraformer
|
else: # sense_voice or paraformer
|
||||||
return {
|
return {
|
||||||
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
|
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
|
||||||
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
|
||||||
}
|
}
|
||||||
|
|
||||||
def _download_from_github(self, url: str, model_dir: str):
|
def _download_from_github(self, url: str, model_dir: str):
|
||||||
"""Download and extract model from GitHub releases"""
|
"""Download and extract model from GitHub releases"""
|
||||||
try:
|
try:
|
||||||
# Create parent directory
|
# Create parent directory
|
||||||
parent_dir = os.path.dirname(model_dir)
|
parent_dir = os.path.dirname(model_dir)
|
||||||
os.makedirs(parent_dir, exist_ok=True)
|
os.makedirs(parent_dir, exist_ok=True)
|
||||||
|
|
||||||
# Download the tar.bz2 file to a temporary location
|
# Download the tar.bz2 file to a temporary location
|
||||||
tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2")
|
tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2")
|
||||||
logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}")
|
logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}")
|
||||||
|
|
||||||
urllib.request.urlretrieve(url, tar_filename)
|
urllib.request.urlretrieve(url, tar_filename)
|
||||||
|
|
||||||
# Extract the tar.bz2 file
|
# Extract the tar.bz2 file
|
||||||
logger.bind(tag=TAG).info("Extracting model files...")
|
logger.bind(tag=TAG).info("Extracting model files...")
|
||||||
with tarfile.open(tar_filename, 'r:bz2') as tar:
|
with tarfile.open(tar_filename, 'r:bz2') as tar:
|
||||||
# Extract to parent directory
|
# Extract to parent directory
|
||||||
tar.extractall(parent_dir)
|
tar.extractall(parent_dir)
|
||||||
|
|
||||||
# Clean up the tar file
|
# Clean up the tar file
|
||||||
os.remove(tar_filename)
|
os.remove(tar_filename)
|
||||||
|
|
||||||
# Verify the extracted directory exists
|
# Verify the extracted directory exists
|
||||||
if os.path.exists(model_dir):
|
if os.path.exists(model_dir):
|
||||||
logger.bind(tag=TAG).info("GitHub model download completed successfully")
|
logger.bind(tag=TAG).info("GitHub model download completed successfully")
|
||||||
else:
|
else:
|
||||||
raise FileNotFoundError(f"Extracted model directory not found: {model_dir}")
|
raise FileNotFoundError(f"Extracted model directory not found: {model_dir}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"GitHub download failed: {e}")
|
logger.bind(tag=TAG).error(f"GitHub download failed: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def _initialize_model(self):
|
def _initialize_model(self):
|
||||||
"""Initialize the appropriate model based on type"""
|
"""Initialize the appropriate model based on type"""
|
||||||
with CaptureOutput():
|
with CaptureOutput():
|
||||||
if self.model_type == "paraformer":
|
if self.model_type == "paraformer":
|
||||||
self.model = sherpa_onnx.OfflineRecognizer.from_paraformer(
|
self.model = sherpa_onnx.OfflineRecognizer.from_paraformer(
|
||||||
paraformer=self.model_path,
|
paraformer=self.model_path,
|
||||||
tokens=self.tokens_path,
|
tokens=self.tokens_path,
|
||||||
num_threads=2,
|
num_threads=2,
|
||||||
decoding_method="greedy_search",
|
decoding_method="greedy_search",
|
||||||
debug=False,
|
debug=False,
|
||||||
)
|
)
|
||||||
elif self.model_type == "whisper":
|
elif self.model_type == "whisper":
|
||||||
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
|
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
|
||||||
encoder=self.encoder_path,
|
encoder=self.encoder_path,
|
||||||
decoder=self.decoder_path,
|
decoder=self.decoder_path,
|
||||||
tokens=self.tokens_path,
|
tokens=self.tokens_path,
|
||||||
num_threads=2,
|
num_threads=2,
|
||||||
decoding_method="greedy_search",
|
decoding_method="greedy_search",
|
||||||
debug=False,
|
debug=False,
|
||||||
)
|
)
|
||||||
elif self.model_type == "zipformer":
|
elif self.model_type == "zipformer":
|
||||||
self.model = sherpa_onnx.OfflineRecognizer.from_transducer(
|
self.model = sherpa_onnx.OfflineRecognizer.from_transducer(
|
||||||
encoder=self.encoder_path,
|
encoder=self.encoder_path,
|
||||||
decoder=self.decoder_path,
|
decoder=self.decoder_path,
|
||||||
joiner=self.joiner_path,
|
joiner=self.joiner_path,
|
||||||
tokens=self.tokens_path,
|
tokens=self.tokens_path,
|
||||||
num_threads=2,
|
num_threads=2,
|
||||||
decoding_method="greedy_search",
|
decoding_method="greedy_search",
|
||||||
debug=False,
|
debug=False,
|
||||||
)
|
)
|
||||||
else: # sense_voice
|
else: # sense_voice
|
||||||
self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
|
self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
|
||||||
model=self.model_path,
|
model=self.model_path,
|
||||||
tokens=self.tokens_path,
|
tokens=self.tokens_path,
|
||||||
num_threads=2,
|
num_threads=2,
|
||||||
decoding_method="greedy_search",
|
decoding_method="greedy_search",
|
||||||
debug=False,
|
debug=False,
|
||||||
use_itn=True,
|
use_itn=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
|
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
wave_filename:
|
wave_filename:
|
||||||
Path to a wave file. It should be single channel and each sample should
|
Path to a wave file. It should be single channel and each sample should
|
||||||
be 16-bit. Its sample rate does not need to be 16kHz.
|
be 16-bit. Its sample rate does not need to be 16kHz.
|
||||||
Returns:
|
Returns:
|
||||||
Return a tuple containing:
|
Return a tuple containing:
|
||||||
- A 1-D array of dtype np.float32 containing the samples, which are
|
- A 1-D array of dtype np.float32 containing the samples, which are
|
||||||
normalized to the range [-1, 1].
|
normalized to the range [-1, 1].
|
||||||
- sample rate of the wave file
|
- sample rate of the wave file
|
||||||
"""
|
"""
|
||||||
|
|
||||||
with wave.open(wave_filename) as f:
|
with wave.open(wave_filename) as f:
|
||||||
assert f.getnchannels() == 1, f.getnchannels()
|
assert f.getnchannels() == 1, f.getnchannels()
|
||||||
assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
|
assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
|
||||||
num_samples = f.getnframes()
|
num_samples = f.getnframes()
|
||||||
samples = f.readframes(num_samples)
|
samples = f.readframes(num_samples)
|
||||||
samples_int16 = np.frombuffer(samples, dtype=np.int16)
|
samples_int16 = np.frombuffer(samples, dtype=np.int16)
|
||||||
samples_float32 = samples_int16.astype(np.float32)
|
samples_float32 = samples_int16.astype(np.float32)
|
||||||
|
|
||||||
samples_float32 = samples_float32 / 32768
|
samples_float32 = samples_float32 / 32768
|
||||||
return samples_float32, f.getframerate()
|
return samples_float32, f.getframerate()
|
||||||
|
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""Main processing logic for speech to text"""
|
"""Main processing logic for speech to text"""
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# Save audio file
|
# Save audio file
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
if audio_format == "pcm":
|
if audio_format == "pcm":
|
||||||
pcm_data = opus_data
|
pcm_data = opus_data
|
||||||
else:
|
else:
|
||||||
pcm_data = self.decode_opus(opus_data)
|
pcm_data = self.decode_opus(opus_data)
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
|
f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Speech recognition
|
# Speech recognition
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
s = self.model.create_stream()
|
s = self.model.create_stream()
|
||||||
samples, sample_rate = self.read_wave(file_path)
|
samples, sample_rate = self.read_wave(file_path)
|
||||||
s.accept_waveform(sample_rate, samples)
|
s.accept_waveform(sample_rate, samples)
|
||||||
self.model.decode_stream(s)
|
self.model.decode_stream(s)
|
||||||
text = s.result.text
|
text = s.result.text
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
|
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Calculate audio length from WAV file
|
# Calculate audio length from WAV file
|
||||||
with wave.open(file_path, 'rb') as wav_file:
|
with wave.open(file_path, 'rb') as wav_file:
|
||||||
frames = wav_file.getnframes()
|
frames = wav_file.getnframes()
|
||||||
rate = wav_file.getframerate()
|
rate = wav_file.getframerate()
|
||||||
audio_length_seconds = frames / float(rate)
|
audio_length_seconds = frames / float(rate)
|
||||||
|
|
||||||
# Log the transcript information
|
# Log the transcript information - TEMPORARILY DISABLED
|
||||||
self.log_audio_transcript(file_path, audio_length_seconds, text)
|
# self.log_audio_transcript(file_path, audio_length_seconds, text)
|
||||||
|
|
||||||
return text, file_path
|
return text, file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"Speech recognition failed: {e}", exc_info=True)
|
f"Speech recognition failed: {e}", exc_info=True)
|
||||||
return "", file_path
|
return "", file_path
|
||||||
finally:
|
finally:
|
||||||
# File cleanup logic - DISABLED to preserve audio files
|
# File cleanup logic - DISABLED to preserve audio files
|
||||||
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
if self.delete_audio_file and file_path and os.path.exists(file_path):
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"Audio file preserved (deletion disabled): {file_path}")
|
f"Audio file preserved (deletion disabled): {file_path}")
|
||||||
# Commented out deletion code to preserve audio files
|
# Commented out deletion code to preserve audio files
|
||||||
# try:
|
try:
|
||||||
# os.remove(file_path)
|
os.remove(file_path)
|
||||||
# logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
# f"Deleted temporary audio file: {file_path}")
|
f"Deleted temporary audio file: {file_path}")
|
||||||
# except Exception as e:
|
except Exception as e:
|
||||||
# logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
# f"File deletion failed: {file_path} | Error: {e}")
|
f"File deletion failed: {file_path} | Error: {e}")
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue