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:
rahulpscraftech360 2025-08-18 13:09:04 +05:30
parent 0fe4c2d0b3
commit 3371c45608
5 changed files with 2245 additions and 2234 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,150 +1,150 @@
import time
import json
import random
import asyncio
from core.utils.dialogue import Message
from core.utils.util import audio_to_data
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.providers.tts.dto.dto import ContentType, SentenceType
from core.providers.tools.device_mcp import (
MCPClient,
send_mcp_initialize_message,
send_mcp_tools_list_request,
)
from core.utils.wakeup_word import WakeupWordsConfig
TAG = __name__
WAKEUP_CONFIG = {
"refresh_time": 5,
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
}
# Create global wakeup words configuration manager
wakeup_words_config = WakeupWordsConfig()
# Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json):
"""Handle hello message"""
audio_params = msg_json.get("audio_params")
if audio_params:
format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
conn.audio_format = format
conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features")
if features:
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
conn.features = features
# Handle both list and dictionary formats for features
has_mcp = False
if isinstance(features, list):
has_mcp = "mcp" in features
elif isinstance(features, dict):
has_mcp = features.get("mcp", False)
if has_mcp:
conn.logger.bind(tag=TAG).info("Client supports MCP")
conn.mcp_client = MCPClient()
# Send initialization
asyncio.create_task(send_mcp_initialize_message(conn))
# Send mcp message to get tools list
asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg))
async def checkWakeupWords(conn, text):
enable_wakeup_words_response_cache = conn.config[
"enable_wakeup_words_response_cache"
]
if not enable_wakeup_words_response_cache or not conn.tts:
return False
_, filtered_text = remove_punctuation_and_length(text)
if filtered_text not in conn.config.get("wakeup_words"):
return False
conn.just_woken_up = True
await send_stt_message(conn, text)
# Get current voice
voice = getattr(conn.tts, "voice", "default")
if not voice:
voice = "default"
# Get wakeup words reply configuration
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
"voice": "default",
"file_path": "config/assets/wakeup_words.wav",
"time": 0,
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
}
# Play wakeup words reply
conn.client_abort = False
opus_packets, _ = audio_to_data(response.get("file_path"))
conn.logger.bind(tag=TAG).info(
f"Playing wakeup words reply: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
# Add to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# Check if wakeup words reply needs to be updated
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
return True
async def wakeupWordsResponse(conn):
if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
return
try:
# Try to acquire lock, return if cannot acquire
if not await _wakeup_response_lock.acquire():
return
# Generate wakeup words reply
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
question = (
"The user is currently saying ```"
+ 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"
+ "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)
if not result or len(result) == 0:
return
# Generate TTS audio
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
# Get current voice
voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f:
f.write(wav_bytes)
# Update configuration
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
# Ensure lock is released in any case
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()
import time
import json
import random
import asyncio
from core.utils.dialogue import Message
from core.utils.util import audio_to_data
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.providers.tts.dto.dto import ContentType, SentenceType
from core.providers.tools.device_mcp import (
MCPClient,
send_mcp_initialize_message,
send_mcp_tools_list_request,
)
from core.utils.wakeup_word import WakeupWordsConfig
TAG = __name__
WAKEUP_CONFIG = {
"refresh_time": 5,
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
}
# Create global wakeup words configuration manager
wakeup_words_config = WakeupWordsConfig()
# Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json):
"""Handle hello message"""
audio_params = msg_json.get("audio_params")
if audio_params:
format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
conn.audio_format = format
conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features")
if features:
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
conn.features = features
# Handle both list and dictionary formats for features
has_mcp = False
if isinstance(features, list):
has_mcp = "mcp" in features
elif isinstance(features, dict):
has_mcp = features.get("mcp", False)
if has_mcp:
conn.logger.bind(tag=TAG).info("Client supports MCP")
conn.mcp_client = MCPClient()
# Send initialization
asyncio.create_task(send_mcp_initialize_message(conn))
# Send mcp message to get tools list
asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg))
async def checkWakeupWords(conn, text):
enable_wakeup_words_response_cache = conn.config[
"enable_wakeup_words_response_cache"
]
if not enable_wakeup_words_response_cache or not conn.tts:
return False
_, filtered_text = remove_punctuation_and_length(text)
if filtered_text not in conn.config.get("wakeup_words"):
return False
conn.just_woken_up = True
await send_stt_message(conn, text)
# Get current voice
voice = getattr(conn.tts, "voice", "default")
if not voice:
voice = "default"
# Get wakeup words reply configuration
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
"voice": "default",
"file_path": "config/assets/wakeup_words.wav",
"time": 0,
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
}
# Play wakeup words reply
conn.client_abort = False
opus_packets, _ = audio_to_data(response.get("file_path"))
conn.logger.bind(tag=TAG).info(
f"Playing wakeup words reply: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
# Add to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# Check if wakeup words reply needs to be updated
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
return True
async def wakeupWordsResponse(conn):
if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
return
try:
# Try to acquire lock, return if cannot acquire
if not await _wakeup_response_lock.acquire():
return
# Generate wakeup words reply
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
question = (
"The user is currently saying ```"
+ 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"
+ "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)
if not result or len(result) == 0:
return
# Generate TTS audio
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
# Get current voice
voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f:
f.write(wav_bytes)
# Update configuration
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
# Ensure lock is released in any case
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()

View file

@ -1,186 +1,188 @@
import json
import time
from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage
from core.providers.tools.device_mcp import handle_mcp_message
from core.utils.util import remove_punctuation_and_length, filter_sensitive_info
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus
from core.handle.reportHandle import enqueue_asr_report
import asyncio
TAG = __name__
async def handleTextMessage(conn, message):
"""Handle text messages"""
try:
msg_json = json.loads(message)
if isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
await conn.websocket.send(message)
return
if msg_json["type"] == "hello":
conn.logger.bind(tag=TAG).info(
f"Received hello message: {message}")
await handleHelloMessage(conn, msg_json)
elif msg_json["type"] == "abort":
conn.logger.bind(tag=TAG).info(
f"Received abort message: {message}")
await handleAbortMessage(conn)
elif msg_json["type"] == "listen":
conn.logger.bind(tag=TAG).info(
f"Received listen message: {message}")
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug(
f"Client audio capture mode: {conn.client_listen_mode}"
)
if msg_json["state"] == "start":
# Reset VAD states to clear any leftover audio from previous session
conn.reset_vad_states()
# Mark that we just started listening to prevent processing stale audio
conn.just_started_listening = True
# Add initial connection flag to prevent false positive on first audio
if not hasattr(conn, "initial_connection_handled"):
conn.initial_connection_handled = False
conn.initial_connection_time = asyncio.get_event_loop().time()
conn.client_have_voice = True
conn.client_voice_stop = False
elif msg_json["state"] == "stop":
conn.client_have_voice = True
conn.client_voice_stop = True
if len(conn.asr_audio) > 0:
await handleAudioMessage(conn, b"")
elif msg_json["state"] == "detect":
conn.client_have_voice = False
conn.asr_audio.clear()
if "text" in msg_json:
conn.last_activity_time = time.time() * 1000
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")
# Whether wake-up word reply is enabled
enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting:
# 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)
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
elif is_wakeup_words:
conn.just_woken_up = True
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, "Hey, hello there", [])
await startToChat(conn, "Hey, hello there")
else:
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, original_text, [])
# Otherwise, need LLM to respond to text content
await startToChat(conn, original_text)
elif msg_json["type"] == "iot":
conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
if "descriptors" in msg_json:
asyncio.create_task(handleIotDescriptors(
conn, msg_json["descriptors"]))
if "states" in msg_json:
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
elif msg_json["type"] == "mcp":
conn.logger.bind(tag=TAG).info(
f"Received mcp message: {message[:100]}")
if "payload" in msg_json:
asyncio.create_task(
handle_mcp_message(conn, conn.mcp_client,
msg_json["payload"])
)
elif msg_json["type"] == "server":
# Filter sensitive information when logging
conn.logger.bind(tag=TAG).info(
f"Received server message: {filter_sensitive_info(msg_json)}"
)
# If configuration is read from API, need to verify secret
if not conn.read_config_from_api:
return
# Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "")
# If secret doesn't match, return
if post_secret != secret:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Server secret verification failed",
}
)
)
return
# Dynamically update configuration
if msg_json["action"] == "update_config":
try:
# Update WebSocketServer configuration
if not conn.server:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Cannot get server instance",
"content": {"action": "update_config"},
}
)
)
return
if not await conn.server.update_config():
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Failed to update server configuration",
"content": {"action": "update_config"},
}
)
)
return
# Send success response
await conn.websocket.send(
json.dumps(
{
"type": "server",
"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)}")
await conn.websocket.send(
json.dumps(
{
"type": "server",
"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)
else:
conn.logger.bind(tag=TAG).error(
f"Received unknown type message: {message}")
except json.JSONDecodeError:
await conn.websocket.send(message)
import json
import time
from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage
from core.providers.tools.device_mcp import handle_mcp_message
from core.utils.util import remove_punctuation_and_length, filter_sensitive_info
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
from core.providers.tools.device_iot import handleIotDescriptors, handleIotStatus
from core.handle.reportHandle import enqueue_asr_report
import asyncio
TAG = __name__
async def handleTextMessage(conn, message):
"""Handle text messages"""
try:
msg_json = json.loads(message)
if isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
await conn.websocket.send(message)
return
if msg_json["type"] == "hello":
conn.logger.bind(tag=TAG).info(
f"Received hello message: {message}")
await handleHelloMessage(conn, msg_json)
elif msg_json["type"] == "abort":
conn.logger.bind(tag=TAG).info(
f"Received abort message: {message}")
await handleAbortMessage(conn)
elif msg_json["type"] == "listen":
conn.logger.bind(tag=TAG).info(
f"Received listen message: {message}")
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug(
f"Client audio capture mode: {conn.client_listen_mode}"
)
if msg_json["state"] == "start":
# Reset VAD states to clear any leftover audio from previous session
conn.reset_vad_states()
# Mark that we just started listening to prevent processing stale audio
conn.just_started_listening = True
# Set a timestamp for when we started listening
conn.listen_start_time = time.time()
# Add initial connection flag to prevent false positive on first audio
if not hasattr(conn, "initial_connection_handled"):
conn.initial_connection_handled = False
conn.initial_connection_time = asyncio.get_event_loop().time()
conn.client_have_voice = True
conn.client_voice_stop = False
elif msg_json["state"] == "stop":
conn.client_have_voice = True
conn.client_voice_stop = True
if len(conn.asr_audio) > 0:
await handleAudioMessage(conn, b"")
elif msg_json["state"] == "detect":
conn.client_have_voice = False
conn.asr_audio.clear()
if "text" in msg_json:
conn.last_activity_time = time.time() * 1000
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")
# Whether wake-up word reply is enabled
enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting:
# 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)
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
elif is_wakeup_words:
conn.just_woken_up = True
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, "Hey, hello there", [])
await startToChat(conn, "Hey, hello there")
else:
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, original_text, [])
# Otherwise, need LLM to respond to text content
await startToChat(conn, original_text)
elif msg_json["type"] == "iot":
conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
if "descriptors" in msg_json:
asyncio.create_task(handleIotDescriptors(
conn, msg_json["descriptors"]))
if "states" in msg_json:
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
elif msg_json["type"] == "mcp":
conn.logger.bind(tag=TAG).info(
f"Received mcp message: {message[:100]}")
if "payload" in msg_json:
asyncio.create_task(
handle_mcp_message(conn, conn.mcp_client,
msg_json["payload"])
)
elif msg_json["type"] == "server":
# Filter sensitive information when logging
conn.logger.bind(tag=TAG).info(
f"Received server message: {filter_sensitive_info(msg_json)}"
)
# If configuration is read from API, need to verify secret
if not conn.read_config_from_api:
return
# Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "")
# If secret doesn't match, return
if post_secret != secret:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Server secret verification failed",
}
)
)
return
# Dynamically update configuration
if msg_json["action"] == "update_config":
try:
# Update WebSocketServer configuration
if not conn.server:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Cannot get server instance",
"content": {"action": "update_config"},
}
)
)
return
if not await conn.server.update_config():
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "Failed to update server configuration",
"content": {"action": "update_config"},
}
)
)
return
# Send success response
await conn.websocket.send(
json.dumps(
{
"type": "server",
"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)}")
await conn.websocket.send(
json.dumps(
{
"type": "server",
"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)
else:
conn.logger.bind(tag=TAG).error(
f"Received unknown type message: {message}")
except json.JSONDecodeError:
await conn.websocket.send(message)

View file

@ -1,376 +1,385 @@
import os
import wave
import uuid
import queue
import asyncio
import traceback
import threading
import opuslib_next
import json
import io
import time
import concurrent.futures
import csv
from datetime import datetime
from abc import ABC, abstractmethod
from config.logger import setup_logging
from typing import Optional, Tuple, List, Dict, Any
from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report
from core.utils.util import remove_punctuation_and_length
from core.handle.receiveAudioHandle import handleAudioMessage
TAG = __name__
logger = setup_logging()
class ASRProviderBase(ABC):
def __init__(self):
pass
# Open audio channels
async def open_audio_channels(self, conn):
conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True
)
conn.asr_priority_thread.start()
# Process ASR audio in order
def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set():
try:
message = conn.asr_audio_queue.get(timeout=1)
future = asyncio.run_coroutine_threadsafe(
handleAudioMessage(conn, message),
conn.loop,
)
future.result()
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
continue
# Receive audio
async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
have_voice = audio_have_voice
else:
have_voice = conn.client_have_voice
# Always add audio to pre-buffer (rolling buffer)
conn.audio_pre_buffer.append(audio)
# If voice is detected and we're not already collecting
if have_voice and not conn.client_have_voice:
# Clear the just_started_listening flag when actual voice is detected
if hasattr(conn, 'just_started_listening'):
conn.just_started_listening = False
# Add pre-buffered audio to the beginning of ASR audio
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
conn.audio_pre_buffer.clear()
conn.asr_audio.append(audio)
if not have_voice and not conn.client_have_voice:
conn.asr_audio = conn.asr_audio[-10:]
return
if conn.client_voice_stop:
# Check if we just started listening - if so, skip this audio
if hasattr(conn, 'just_started_listening') and conn.just_started_listening:
logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start")
conn.just_started_listening = False
conn.asr_audio.clear()
conn.reset_vad_states()
return
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
conn.reset_vad_states()
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")
await self.handle_voice_stop(conn, asr_audio_task)
# Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
"""Parallel processing of ASR and voiceprint recognition"""
try:
total_start_time = time.monotonic()
# Prepare audio data
if conn.audio_format == "pcm":
pcm_data = asr_audio_task
else:
pcm_data = self.decode_opus(asr_audio_task)
combined_pcm_data = b"".join(pcm_data)
# Pre-prepare WAV data
wav_data = None
# Use connection's voiceprint provider
if conn.voiceprint_provider and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
# Define ASR task
def run_asr():
start_time = time.monotonic()
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
self.speech_to_text(
asr_audio_task, conn.session_id, conn.audio_format)
)
end_time = time.monotonic()
logger.bind(tag=TAG).info(
f"ASR time: {end_time - start_time:.3f}s")
return result
finally:
loop.close()
except Exception as e:
end_time = time.monotonic()
logger.bind(tag=TAG).error(f"ASR failed: {e}")
return ("", None)
# Define voiceprint recognition task
def run_voiceprint():
if not wav_data:
return None
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# Use connection's voiceprint provider
result = loop.run_until_complete(
conn.voiceprint_provider.identify_speaker(
wav_data, conn.session_id)
)
return result
finally:
loop.close()
except Exception as e:
logger.bind(tag=TAG).error(
f"Voiceprint recognition failed: {e}")
return None
# Run in parallel using thread pool executor
parallel_start_time = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
asr_future = thread_executor.submit(run_asr)
if conn.voiceprint_provider and wav_data:
voiceprint_future = thread_executor.submit(run_voiceprint)
# Wait for both threads to complete
asr_result = asr_future.result(timeout=15)
voiceprint_result = voiceprint_future.result(timeout=15)
results = {"asr": asr_result,
"voiceprint": voiceprint_result}
else:
asr_result = asr_future.result(timeout=15)
results = {"asr": asr_result, "voiceprint": None}
# Process results
raw_text, file_path = results.get("asr", ("", None))
speaker_name = results.get("voiceprint", None)
# Log recognition results
if raw_text:
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
if speaker_name:
logger.bind(tag=TAG).info(
f"Identified speaker: {speaker_name}")
# Performance monitoring
total_time = time.monotonic() - total_start_time
logger.bind(tag=TAG).info(
f"Total processing time: {total_time:.3f}s")
# Check text length
text_len, _ = remove_punctuation_and_length(raw_text)
self.stop_ws_connection()
if text_len > 0:
# Build JSON string with speaker information
enhanced_text = self._build_enhanced_text(
raw_text, speaker_name)
# Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(
f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
"""Build text with speaker information"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
"content": text
}, ensure_ascii=False)
else:
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""Convert PCM data to WAV format"""
if len(pcm_data) == 0:
logger.bind(tag=TAG).warning(
"PCM data is empty, cannot convert to WAV")
return b""
# Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
# Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
wav_data = wav_buffer.read()
return wav_data
except Exception as e:
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self):
pass
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""Save PCM data as WAV file"""
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name)
with wave.open(file_path, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2) # 2 bytes = 16-bit
wf.setframerate(16000)
wf.writeframes(b"".join(pcm_data))
return file_path
def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str):
"""Log audio file information to CSV file"""
try:
# Create logs directory at the same level as output_dir
log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs")
os.makedirs(log_dir, exist_ok=True)
# 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")
json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json")
# Write to CSV file
csv_exists = os.path.exists(csv_log_file)
with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile:
fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not csv_exists:
writer.writeheader()
writer.writerow({
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
})
# Also write to JSON file for easier parsing
log_entry = {
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
}
# Read existing JSON logs or create new list
json_logs = []
if os.path.exists(json_log_file):
try:
with open(json_log_file, 'r', encoding='utf-8') as f:
json_logs = json.load(f)
except:
json_logs = []
json_logs.append(log_entry)
# Write updated JSON logs
with open(json_log_file, 'w', encoding='utf-8') as f:
json.dump(json_logs, f, ensure_ascii=False, indent=2)
# Also create a simple text log for quick inspection
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:
f.write(f"\n{'='*80}\n")
f.write(f"Timestamp: {datetime.now().isoformat()}\n")
f.write(f"Filename: {os.path.basename(file_path)}\n")
f.write(f"Full Path: {file_path}\n")
f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n")
f.write(f"Transcript: {transcript}\n")
f.write(f"{'='*80}\n")
logger.bind(tag=TAG).info(
f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, "
f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..."
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}")
@abstractmethod
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text"""
pass
@staticmethod
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
"""Decode Opus audio data to PCM data"""
try:
decoder = opuslib_next.Decoder(16000, 1)
pcm_data = []
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for i, opus_packet in enumerate(opus_data):
try:
if not opus_packet or len(opus_packet) == 0:
continue
pcm_frame = decoder.decode(opus_packet, buffer_size)
if pcm_frame and len(pcm_frame) > 0:
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
logger.bind(tag=TAG).warning(
f"Opus decode error, skipping packet {i}: {e}")
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 []
import os
import wave
import uuid
import queue
import asyncio
import traceback
import threading
import opuslib_next
import json
import io
import time
import concurrent.futures
import csv
from datetime import datetime
from abc import ABC, abstractmethod
from config.logger import setup_logging
from typing import Optional, Tuple, List, Dict, Any
from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report
from core.utils.util import remove_punctuation_and_length
from core.handle.receiveAudioHandle import handleAudioMessage
TAG = __name__
logger = setup_logging()
class ASRProviderBase(ABC):
def __init__(self):
pass
# Open audio channels
async def open_audio_channels(self, conn):
conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True
)
conn.asr_priority_thread.start()
# Process ASR audio in order
def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set():
try:
message = conn.asr_audio_queue.get(timeout=1)
future = asyncio.run_coroutine_threadsafe(
handleAudioMessage(conn, message),
conn.loop,
)
future.result()
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
continue
# Receive audio
async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
have_voice = audio_have_voice
else:
have_voice = conn.client_have_voice
# Echo suppression: Ignore audio for a brief period after starting to listen
if hasattr(conn, 'listen_start_time'):
time_since_listen_start = time.time() - conn.listen_start_time
if time_since_listen_start < 0.1: # Ignore first 300ms of audio (echo period)
if have_voice:
logger.bind(tag=TAG).debug(f"Ignoring potential echo audio ({time_since_listen_start:.2f}s after listen start)")
have_voice = False
# Always add audio to pre-buffer (rolling buffer)
conn.audio_pre_buffer.append(audio)
# If voice is detected and we're not already collecting
if have_voice and not conn.client_have_voice:
# Clear the just_started_listening flag when actual voice is detected
if hasattr(conn, 'just_started_listening'):
conn.just_started_listening = False
# Add pre-buffered audio to the beginning of ASR audio
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
conn.audio_pre_buffer.clear()
conn.asr_audio.append(audio)
if not have_voice and not conn.client_have_voice:
conn.asr_audio = conn.asr_audio[-10:]
return
if conn.client_voice_stop:
# Check if we just started listening - if so, skip this audio
if hasattr(conn, 'just_started_listening') and conn.just_started_listening:
logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start")
conn.just_started_listening = False
conn.asr_audio.clear()
conn.reset_vad_states()
return
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
conn.reset_vad_states()
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")
await self.handle_voice_stop(conn, asr_audio_task)
# Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
"""Parallel processing of ASR and voiceprint recognition"""
try:
total_start_time = time.monotonic()
# Prepare audio data
if conn.audio_format == "pcm":
pcm_data = asr_audio_task
else:
pcm_data = self.decode_opus(asr_audio_task)
combined_pcm_data = b"".join(pcm_data)
# Pre-prepare WAV data
wav_data = None
# Use connection's voiceprint provider
if conn.voiceprint_provider and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
# Define ASR task
def run_asr():
start_time = time.monotonic()
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
self.speech_to_text(
asr_audio_task, conn.session_id, conn.audio_format)
)
end_time = time.monotonic()
logger.bind(tag=TAG).info(
f"ASR time: {end_time - start_time:.3f}s")
return result
finally:
loop.close()
except Exception as e:
end_time = time.monotonic()
logger.bind(tag=TAG).error(f"ASR failed: {e}")
return ("", None)
# Define voiceprint recognition task
def run_voiceprint():
if not wav_data:
return None
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# Use connection's voiceprint provider
result = loop.run_until_complete(
conn.voiceprint_provider.identify_speaker(
wav_data, conn.session_id)
)
return result
finally:
loop.close()
except Exception as e:
logger.bind(tag=TAG).error(
f"Voiceprint recognition failed: {e}")
return None
# Run in parallel using thread pool executor
parallel_start_time = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
asr_future = thread_executor.submit(run_asr)
if conn.voiceprint_provider and wav_data:
voiceprint_future = thread_executor.submit(run_voiceprint)
# Wait for both threads to complete
asr_result = asr_future.result(timeout=15)
voiceprint_result = voiceprint_future.result(timeout=15)
results = {"asr": asr_result,
"voiceprint": voiceprint_result}
else:
asr_result = asr_future.result(timeout=15)
results = {"asr": asr_result, "voiceprint": None}
# Process results
raw_text, file_path = results.get("asr", ("", None))
speaker_name = results.get("voiceprint", None)
# Log recognition results
if raw_text:
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
if speaker_name:
logger.bind(tag=TAG).info(
f"Identified speaker: {speaker_name}")
# Performance monitoring
total_time = time.monotonic() - total_start_time
logger.bind(tag=TAG).info(
f"Total processing time: {total_time:.3f}s")
# Check text length
text_len, _ = remove_punctuation_and_length(raw_text)
self.stop_ws_connection()
if text_len > 0:
# Build JSON string with speaker information
enhanced_text = self._build_enhanced_text(
raw_text, speaker_name)
# Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(
f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
"""Build text with speaker information"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
"content": text
}, ensure_ascii=False)
else:
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""Convert PCM data to WAV format"""
if len(pcm_data) == 0:
logger.bind(tag=TAG).warning(
"PCM data is empty, cannot convert to WAV")
return b""
# Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
# Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
wav_data = wav_buffer.read()
return wav_data
except Exception as e:
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self):
pass
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""Save PCM data as WAV file"""
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name)
with wave.open(file_path, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2) # 2 bytes = 16-bit
wf.setframerate(16000)
wf.writeframes(b"".join(pcm_data))
return file_path
def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str):
"""Log audio file information to CSV file"""
try:
# Create logs directory at the same level as output_dir
log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs")
os.makedirs(log_dir, exist_ok=True)
# 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")
json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json")
# Write to CSV file
csv_exists = os.path.exists(csv_log_file)
with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile:
fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not csv_exists:
writer.writeheader()
writer.writerow({
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
})
# Also write to JSON file for easier parsing
log_entry = {
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
}
# Read existing JSON logs or create new list
json_logs = []
if os.path.exists(json_log_file):
try:
with open(json_log_file, 'r', encoding='utf-8') as f:
json_logs = json.load(f)
except:
json_logs = []
json_logs.append(log_entry)
# Write updated JSON logs
with open(json_log_file, 'w', encoding='utf-8') as f:
json.dump(json_logs, f, ensure_ascii=False, indent=2)
# Also create a simple text log for quick inspection
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:
f.write(f"\n{'='*80}\n")
f.write(f"Timestamp: {datetime.now().isoformat()}\n")
f.write(f"Filename: {os.path.basename(file_path)}\n")
f.write(f"Full Path: {file_path}\n")
f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n")
f.write(f"Transcript: {transcript}\n")
f.write(f"{'='*80}\n")
# Logging disabled - comment out the log message
# logger.bind(tag=TAG).info(
# f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, "
# f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..."
# )
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}")
@abstractmethod
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text"""
pass
@staticmethod
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
"""Decode Opus audio data to PCM data"""
try:
decoder = opuslib_next.Decoder(16000, 1)
pcm_data = []
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for i, opus_packet in enumerate(opus_data):
try:
if not opus_packet or len(opus_packet) == 0:
continue
pcm_frame = decoder.decode(opus_packet, buffer_size)
if pcm_frame and len(pcm_frame) > 0:
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
logger.bind(tag=TAG).warning(
f"Opus decode error, skipping packet {i}: {e}")
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 []

View file

@ -1,384 +1,384 @@
import time
import wave
import os
import sys
import io
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.dto.dto import InterfaceType
from core.providers.asr.base import ASRProviderBase
import numpy as np
import sherpa_onnx
from modelscope.hub.file_download import model_file_download
try:
from huggingface_hub import hf_hub_download
HF_AVAILABLE = True
except ImportError:
HF_AVAILABLE = False
import requests
import tarfile
import urllib.request
TAG = __name__
logger = setup_logging()
# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
self._original_stdout = sys.stdout
sys.stdout = self._output
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout = self._original_stdout
self.output = self._output.getvalue()
self._output.close()
# Output captured content through logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")
self.model_type = config.get(
"model_type", "sense_voice") # Support paraformer
self.delete_audio_file = delete_audio_file
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# Initialize model file paths based on model type
model_files = self._get_model_files_for_type()
# Download and check model files
try:
# Determine model source and ID based on model directory name
model_info = self._get_model_id_from_dir()
# Check if we need to download the entire model from GitHub
if model_info["source"] == "github":
# 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)]
if missing_files:
logger.bind(tag=TAG).info("Downloading complete model from GitHub...")
self._download_from_github(model_info["url"], self.model_dir)
else:
# For individual file downloads (HuggingFace/ModelScope)
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
logger.bind(tag=TAG).info(
f"Downloading model file: {file_name}")
if model_info["source"] == "huggingface" and HF_AVAILABLE:
# Use Hugging Face Hub
try:
hf_hub_download(
repo_id=model_info["model_id"],
filename=file_name,
local_dir=self.model_dir,
local_dir_use_symlinks=False
)
except Exception as e:
logger.bind(tag=TAG).warning(
f"HuggingFace download failed: {e}, trying ModelScope...")
# Fallback to ModelScope
model_file_download(
model_id=model_info["model_id"],
file_path=file_name,
local_dir=self.model_dir,
)
else:
# Use ModelScope
model_file_download(
model_id=model_info["model_id"],
file_path=file_name,
local_dir=self.model_dir,
)
# Verify all files exist after download
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
raise FileNotFoundError(
f"Model file not found after download: {file_path}")
# Set model paths based on type
if self.model_type == "whisper":
self.encoder_path = list(model_files.values())[0] # encoder
self.decoder_path = list(model_files.values())[1] # decoder
self.tokens_path = list(model_files.values())[2] # tokens
elif self.model_type == "zipformer":
# Handle different zipformer file naming patterns
model_name = os.path.basename(self.model_dir)
if "gigaspeech" in model_name:
self.encoder_path = model_files["encoder-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"]
else:
self.encoder_path = model_files["encoder-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.tokens_path = model_files["tokens.txt"]
else:
self.model_path = model_files["model.int8.onnx"]
self.tokens_path = model_files["tokens.txt"]
except Exception as e:
logger.bind(tag=TAG).error(
f"Model file processing failed: {str(e)}")
raise
# Initialize the model
self._initialize_model()
def _get_model_id_from_dir(self) -> str:
"""Determine ModelScope model ID based on model directory name"""
dir_name = os.path.basename(self.model_dir)
# Map directory names to model sources (ModelScope and HuggingFace)
model_mapping = {
# Multilingual models
"sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": {
"source": "modelscope",
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
},
# English-only Whisper models (HuggingFace - more reliable)
"sherpa-onnx-whisper-tiny.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en"
},
"sherpa-onnx-whisper-base.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-base.en"
},
"sherpa-onnx-whisper-small.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-small.en"
},
"sherpa-onnx-whisper-medium.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-medium.en"
},
# English-only Zipformer models (HuggingFace)
"sherpa-onnx-zipformer-en-2023-04-01": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01"
},
"sherpa-onnx-zipformer-gigaspeech-2023-12-12": {
"source": "github",
"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"
},
}
return model_mapping.get(dir_name, {
"source": "modelscope",
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
})
def _get_model_files_for_type(self) -> dict:
"""Get required model files based on model type"""
if self.model_type == "whisper":
# Dynamic file names based on model directory
model_name = os.path.basename(self.model_dir)
if "tiny.en" in model_name:
prefix = "tiny.en"
elif "base.en" in model_name:
prefix = "base.en"
elif "small.en" in model_name:
prefix = "small.en"
elif "medium.en" in model_name:
prefix = "medium.en"
else:
prefix = "tiny.en" # default
return {
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}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"),
}
elif self.model_type == "zipformer":
# Check for different zipformer file naming patterns
model_name = os.path.basename(self.model_dir)
if "gigaspeech" in model_name:
return {
"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"),
"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"),
}
else:
return {
"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"),
"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"),
}
else: # sense_voice or paraformer
return {
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
}
def _download_from_github(self, url: str, model_dir: str):
"""Download and extract model from GitHub releases"""
try:
# Create parent directory
parent_dir = os.path.dirname(model_dir)
os.makedirs(parent_dir, exist_ok=True)
# Download the tar.bz2 file to a temporary location
tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2")
logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}")
urllib.request.urlretrieve(url, tar_filename)
# Extract the tar.bz2 file
logger.bind(tag=TAG).info("Extracting model files...")
with tarfile.open(tar_filename, 'r:bz2') as tar:
# Extract to parent directory
tar.extractall(parent_dir)
# Clean up the tar file
os.remove(tar_filename)
# Verify the extracted directory exists
if os.path.exists(model_dir):
logger.bind(tag=TAG).info("GitHub model download completed successfully")
else:
raise FileNotFoundError(f"Extracted model directory not found: {model_dir}")
except Exception as e:
logger.bind(tag=TAG).error(f"GitHub download failed: {e}")
raise
def _initialize_model(self):
"""Initialize the appropriate model based on type"""
with CaptureOutput():
if self.model_type == "paraformer":
self.model = sherpa_onnx.OfflineRecognizer.from_paraformer(
paraformer=self.model_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
elif self.model_type == "whisper":
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
encoder=self.encoder_path,
decoder=self.decoder_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
elif self.model_type == "zipformer":
self.model = sherpa_onnx.OfflineRecognizer.from_transducer(
encoder=self.encoder_path,
decoder=self.decoder_path,
joiner=self.joiner_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
else: # sense_voice
self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
model=self.model_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
use_itn=True,
)
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
"""
Args:
wave_filename:
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.
Returns:
Return a tuple containing:
- A 1-D array of dtype np.float32 containing the samples, which are
normalized to the range [-1, 1].
- sample rate of the wave file
"""
with wave.open(wave_filename) as f:
assert f.getnchannels() == 1, f.getnchannels()
assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
num_samples = f.getnframes()
samples = f.readframes(num_samples)
samples_int16 = np.frombuffer(samples, dtype=np.int16)
samples_float32 = samples_int16.astype(np.float32)
samples_float32 = samples_float32 / 32768
return samples_float32, f.getframerate()
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Main processing logic for speech to text"""
file_path = None
try:
# Save audio file
start_time = time.time()
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
)
# Speech recognition
start_time = time.time()
s = self.model.create_stream()
samples, sample_rate = self.read_wave(file_path)
s.accept_waveform(sample_rate, samples)
self.model.decode_stream(s)
text = s.result.text
logger.bind(tag=TAG).debug(
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
# Calculate audio length from WAV file
with wave.open(file_path, 'rb') as wav_file:
frames = wav_file.getnframes()
rate = wav_file.getframerate()
audio_length_seconds = frames / float(rate)
# Log the transcript information
self.log_audio_transcript(file_path, audio_length_seconds, text)
return text, file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# File cleanup logic - DISABLED to preserve audio files
if self.delete_audio_file and file_path and os.path.exists(file_path):
logger.bind(tag=TAG).info(
f"Audio file preserved (deletion disabled): {file_path}")
# Commented out deletion code to preserve audio files
# try:
# os.remove(file_path)
# logger.bind(tag=TAG).debug(
# f"Deleted temporary audio file: {file_path}")
# except Exception as e:
# logger.bind(tag=TAG).error(
# f"File deletion failed: {file_path} | Error: {e}")
import time
import wave
import os
import sys
import io
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.providers.asr.dto.dto import InterfaceType
from core.providers.asr.base import ASRProviderBase
import numpy as np
import sherpa_onnx
from modelscope.hub.file_download import model_file_download
try:
from huggingface_hub import hf_hub_download
HF_AVAILABLE = True
except ImportError:
HF_AVAILABLE = False
import requests
import tarfile
import urllib.request
TAG = __name__
logger = setup_logging()
# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
self._original_stdout = sys.stdout
sys.stdout = self._output
def __exit__(self, exc_type, exc_value, traceback):
sys.stdout = self._original_stdout
self.output = self._output.getvalue()
self._output.close()
# Output captured content through logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")
self.model_type = config.get(
"model_type", "sense_voice") # Support paraformer
self.delete_audio_file = delete_audio_file
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# Initialize model file paths based on model type
model_files = self._get_model_files_for_type()
# Download and check model files
try:
# Determine model source and ID based on model directory name
model_info = self._get_model_id_from_dir()
# Check if we need to download the entire model from GitHub
if model_info["source"] == "github":
# 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)]
if missing_files:
logger.bind(tag=TAG).info("Downloading complete model from GitHub...")
self._download_from_github(model_info["url"], self.model_dir)
else:
# For individual file downloads (HuggingFace/ModelScope)
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
logger.bind(tag=TAG).info(
f"Downloading model file: {file_name}")
if model_info["source"] == "huggingface" and HF_AVAILABLE:
# Use Hugging Face Hub
try:
hf_hub_download(
repo_id=model_info["model_id"],
filename=file_name,
local_dir=self.model_dir,
local_dir_use_symlinks=False
)
except Exception as e:
logger.bind(tag=TAG).warning(
f"HuggingFace download failed: {e}, trying ModelScope...")
# Fallback to ModelScope
model_file_download(
model_id=model_info["model_id"],
file_path=file_name,
local_dir=self.model_dir,
)
else:
# Use ModelScope
model_file_download(
model_id=model_info["model_id"],
file_path=file_name,
local_dir=self.model_dir,
)
# Verify all files exist after download
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
raise FileNotFoundError(
f"Model file not found after download: {file_path}")
# Set model paths based on type
if self.model_type == "whisper":
self.encoder_path = list(model_files.values())[0] # encoder
self.decoder_path = list(model_files.values())[1] # decoder
self.tokens_path = list(model_files.values())[2] # tokens
elif self.model_type == "zipformer":
# Handle different zipformer file naming patterns
model_name = os.path.basename(self.model_dir)
if "gigaspeech" in model_name:
self.encoder_path = model_files["encoder-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"]
else:
self.encoder_path = model_files["encoder-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.tokens_path = model_files["tokens.txt"]
else:
self.model_path = model_files["model.int8.onnx"]
self.tokens_path = model_files["tokens.txt"]
except Exception as e:
logger.bind(tag=TAG).error(
f"Model file processing failed: {str(e)}")
raise
# Initialize the model
self._initialize_model()
def _get_model_id_from_dir(self) -> str:
"""Determine ModelScope model ID based on model directory name"""
dir_name = os.path.basename(self.model_dir)
# Map directory names to model sources (ModelScope and HuggingFace)
model_mapping = {
# Multilingual models
"sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17": {
"source": "modelscope",
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
},
# English-only Whisper models (HuggingFace - more reliable)
"sherpa-onnx-whisper-tiny.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-tiny.en"
},
"sherpa-onnx-whisper-base.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-base.en"
},
"sherpa-onnx-whisper-small.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-small.en"
},
"sherpa-onnx-whisper-medium.en": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-whisper-medium.en"
},
# English-only Zipformer models (HuggingFace)
"sherpa-onnx-zipformer-en-2023-04-01": {
"source": "huggingface",
"model_id": "csukuangfj/sherpa-onnx-zipformer-en-2023-04-01"
},
"sherpa-onnx-zipformer-gigaspeech-2023-12-12": {
"source": "github",
"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"
},
}
return model_mapping.get(dir_name, {
"source": "modelscope",
"model_id": "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
})
def _get_model_files_for_type(self) -> dict:
"""Get required model files based on model type"""
if self.model_type == "whisper":
# Dynamic file names based on model directory
model_name = os.path.basename(self.model_dir)
if "tiny.en" in model_name:
prefix = "tiny.en"
elif "base.en" in model_name:
prefix = "base.en"
elif "small.en" in model_name:
prefix = "small.en"
elif "medium.en" in model_name:
prefix = "medium.en"
else:
prefix = "tiny.en" # default
return {
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}-tokens.txt": os.path.join(self.model_dir, f"{prefix}-tokens.txt"),
}
elif self.model_type == "zipformer":
# Check for different zipformer file naming patterns
model_name = os.path.basename(self.model_dir)
if "gigaspeech" in model_name:
return {
"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"),
"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"),
}
else:
return {
"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"),
"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"),
}
else: # sense_voice or paraformer
return {
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
}
def _download_from_github(self, url: str, model_dir: str):
"""Download and extract model from GitHub releases"""
try:
# Create parent directory
parent_dir = os.path.dirname(model_dir)
os.makedirs(parent_dir, exist_ok=True)
# Download the tar.bz2 file to a temporary location
tar_filename = os.path.join(parent_dir, "temp_model.tar.bz2")
logger.bind(tag=TAG).info(f"Downloading from GitHub: {url}")
urllib.request.urlretrieve(url, tar_filename)
# Extract the tar.bz2 file
logger.bind(tag=TAG).info("Extracting model files...")
with tarfile.open(tar_filename, 'r:bz2') as tar:
# Extract to parent directory
tar.extractall(parent_dir)
# Clean up the tar file
os.remove(tar_filename)
# Verify the extracted directory exists
if os.path.exists(model_dir):
logger.bind(tag=TAG).info("GitHub model download completed successfully")
else:
raise FileNotFoundError(f"Extracted model directory not found: {model_dir}")
except Exception as e:
logger.bind(tag=TAG).error(f"GitHub download failed: {e}")
raise
def _initialize_model(self):
"""Initialize the appropriate model based on type"""
with CaptureOutput():
if self.model_type == "paraformer":
self.model = sherpa_onnx.OfflineRecognizer.from_paraformer(
paraformer=self.model_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
elif self.model_type == "whisper":
self.model = sherpa_onnx.OfflineRecognizer.from_whisper(
encoder=self.encoder_path,
decoder=self.decoder_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
elif self.model_type == "zipformer":
self.model = sherpa_onnx.OfflineRecognizer.from_transducer(
encoder=self.encoder_path,
decoder=self.decoder_path,
joiner=self.joiner_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
)
else: # sense_voice
self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice(
model=self.model_path,
tokens=self.tokens_path,
num_threads=2,
decoding_method="greedy_search",
debug=False,
use_itn=True,
)
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
"""
Args:
wave_filename:
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.
Returns:
Return a tuple containing:
- A 1-D array of dtype np.float32 containing the samples, which are
normalized to the range [-1, 1].
- sample rate of the wave file
"""
with wave.open(wave_filename) as f:
assert f.getnchannels() == 1, f.getnchannels()
assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes
num_samples = f.getnframes()
samples = f.readframes(num_samples)
samples_int16 = np.frombuffer(samples, dtype=np.int16)
samples_float32 = samples_int16.astype(np.float32)
samples_float32 = samples_float32 / 32768
return samples_float32, f.getframerate()
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Main processing logic for speech to text"""
file_path = None
try:
# Save audio file
start_time = time.time()
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
)
# Speech recognition
start_time = time.time()
s = self.model.create_stream()
samples, sample_rate = self.read_wave(file_path)
s.accept_waveform(sample_rate, samples)
self.model.decode_stream(s)
text = s.result.text
logger.bind(tag=TAG).debug(
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
# Calculate audio length from WAV file
with wave.open(file_path, 'rb') as wav_file:
frames = wav_file.getnframes()
rate = wav_file.getframerate()
audio_length_seconds = frames / float(rate)
# Log the transcript information - TEMPORARILY DISABLED
# self.log_audio_transcript(file_path, audio_length_seconds, text)
return text, file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# File cleanup logic - DISABLED to preserve audio files
if self.delete_audio_file and file_path and os.path.exists(file_path):
logger.bind(tag=TAG).info(
f"Audio file preserved (deletion disabled): {file_path}")
# Commented out deletion code to preserve audio files
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(
f"File deletion failed: {file_path} | Error: {e}")