mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
timezone is changed of chathistory in dashboard
This commit is contained in:
parent
255a403f87
commit
6f6921912d
5 changed files with 1221 additions and 383 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,204 +1,3 @@
|
|||
# from core.handle.sendAudioHandle import send_stt_message
|
||||
# from core.handle.intentHandler import handle_user_intent
|
||||
# from core.utils.output_counter import check_device_output_limit
|
||||
# from core.handle.abortHandle import handleAbortMessage
|
||||
# import time
|
||||
# import asyncio
|
||||
# import json
|
||||
# from core.handle.sendAudioHandle import SentenceType
|
||||
# from core.utils.util import audio_to_data
|
||||
|
||||
# TAG = __name__
|
||||
|
||||
|
||||
# async def handleAudioMessage(conn, audio):
|
||||
# # Log that we received audio (only log periodically to avoid spam)
|
||||
# if not hasattr(conn, '_audio_log_counter'):
|
||||
# conn._audio_log_counter = 0
|
||||
# conn._audio_log_counter += 1
|
||||
|
||||
# if conn._audio_log_counter % 200 == 0: # Log every 200th packet (reduced from 50)
|
||||
# conn.logger.bind(tag=TAG).debug(f"Received audio packet #{conn._audio_log_counter}, size: {len(audio)} bytes")
|
||||
|
||||
# # Skip VAD/ASR processing when server is speaking (streaming audio to client)
|
||||
# # This prevents interruptions during TTS playback
|
||||
# if conn.client_is_speaking:
|
||||
# # conn.logger.bind(tag=TAG).debug("Server is speaking - skipping audio processing to prevent interruption")
|
||||
# return
|
||||
|
||||
# # Whether the current segment has someone speaking
|
||||
# have_voice = conn.vad.is_vad(conn, audio)
|
||||
|
||||
# # Track when voice recording starts in auto VAD mode (for 10-second timeout)
|
||||
# if have_voice and not hasattr(conn, 'vad_recording_start_time'):
|
||||
# conn.vad_recording_start_time = time.time()
|
||||
# conn.logger.bind(tag=TAG).debug(f"VAD recording started at: {conn.vad_recording_start_time}")
|
||||
# elif have_voice and hasattr(conn, 'vad_recording_start_time'):
|
||||
# conn.logger.bind(tag=TAG).debug(f"VAD recording continues, started at: {conn.vad_recording_start_time}")
|
||||
|
||||
# # Check if this is the initial connection period (ignore first 1 second of audio)
|
||||
# if have_voice and hasattr(conn, "initial_connection_handled") and not conn.initial_connection_handled:
|
||||
# current_time = asyncio.get_event_loop().time()
|
||||
# if current_time - conn.initial_connection_time < 1.0: # Ignore first 1 second
|
||||
# have_voice = False
|
||||
# conn.asr_audio.clear() # Clear any accumulated audio
|
||||
# return
|
||||
# else:
|
||||
# conn.initial_connection_handled = True
|
||||
|
||||
# # If the device was just woken up, briefly ignore VAD detection
|
||||
# if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
|
||||
# have_voice = False
|
||||
# # Set a brief delay before resuming VAD detection
|
||||
# conn.asr_audio.clear()
|
||||
# if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
|
||||
# conn.vad_resume_task = asyncio.create_task(
|
||||
# resume_vad_detection(conn))
|
||||
# return
|
||||
|
||||
# if have_voice:
|
||||
# if conn.client_is_speaking:
|
||||
# await handleAbortMessage(conn)
|
||||
# # Device long-term idle detection, used for say goodbye
|
||||
# await no_voice_close_connect(conn, have_voice)
|
||||
# # Receive audio
|
||||
# await conn.asr.receive_audio(conn, audio, have_voice)
|
||||
|
||||
|
||||
# async def resume_vad_detection(conn):
|
||||
# # Wait 2 seconds before resuming VAD detection
|
||||
# await asyncio.sleep(1)
|
||||
# conn.just_woken_up = False
|
||||
|
||||
|
||||
# async def startToChat(conn, text):
|
||||
# # Check if input is in JSON format (containing speaker information)
|
||||
# speaker_name = None
|
||||
# actual_text = text
|
||||
|
||||
# try:
|
||||
# # Try to parse JSON format input
|
||||
# if text.strip().startswith('{') and text.strip().endswith('}'):
|
||||
# data = json.loads(text)
|
||||
# if 'speaker' in data and 'content' in data:
|
||||
# speaker_name = data['speaker']
|
||||
# actual_text = data['content']
|
||||
# conn.logger.bind(tag=TAG).info(
|
||||
# f"Parsed speaker information: {speaker_name}")
|
||||
|
||||
# # Use JSON format text directly, do not parse
|
||||
# actual_text = text
|
||||
# except (json.JSONDecodeError, KeyError):
|
||||
# # If parsing fails, continue using original text
|
||||
# pass
|
||||
|
||||
# # Save speaker information to connection object
|
||||
# if speaker_name:
|
||||
# conn.current_speaker = speaker_name
|
||||
# else:
|
||||
# conn.current_speaker = None
|
||||
|
||||
# if conn.need_bind:
|
||||
# await check_bind_device(conn)
|
||||
# return
|
||||
|
||||
# # If the daily output word count exceeds the limit
|
||||
# if conn.max_output_size > 0:
|
||||
# if check_device_output_limit(
|
||||
# conn.headers.get("device-id"), conn.max_output_size
|
||||
# ):
|
||||
# await max_out_size(conn)
|
||||
# return
|
||||
# if conn.client_is_speaking:
|
||||
# await handleAbortMessage(conn)
|
||||
|
||||
# # First perform intent analysis, using actual text content
|
||||
# intent_handled = await handle_user_intent(conn, actual_text)
|
||||
|
||||
# if intent_handled:
|
||||
# # If intent has been handled, no longer proceed with chat
|
||||
# return
|
||||
|
||||
# # Intent not handled, continue with regular chat flow, using actual text content
|
||||
# await send_stt_message(conn, actual_text)
|
||||
# conn.executor.submit(conn.chat, actual_text)
|
||||
|
||||
|
||||
# async def no_voice_close_connect(conn, have_voice):
|
||||
# if have_voice:
|
||||
# conn.last_activity_time = time.time() * 1000
|
||||
# return
|
||||
# # Only perform timeout check when timestamp has been initialized
|
||||
# if conn.last_activity_time > 0.0:
|
||||
# no_voice_time = time.time() * 1000 - conn.last_activity_time
|
||||
# close_connection_no_voice_time = int(
|
||||
# conn.config.get("close_connection_no_voice_time", 120)
|
||||
# )
|
||||
# if (
|
||||
# not conn.close_after_chat
|
||||
# and no_voice_time > 1000 * close_connection_no_voice_time
|
||||
# ):
|
||||
# conn.close_after_chat = True
|
||||
# conn.client_abort = False
|
||||
# end_prompt = conn.config.get("end_prompt", {})
|
||||
# if end_prompt and end_prompt.get("enable", True) is False:
|
||||
# conn.logger.bind(tag=TAG).info(
|
||||
# "End conversation, no need to send ending prompt")
|
||||
# await conn.close()
|
||||
# return
|
||||
# prompt = end_prompt.get("prompt")
|
||||
# if not prompt:
|
||||
# prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
|
||||
# await startToChat(conn, prompt)
|
||||
|
||||
|
||||
# async def max_out_size(conn):
|
||||
# text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
|
||||
# await send_stt_message(conn, text)
|
||||
# file_path = "config/assets/max_output_size.wav"
|
||||
# opus_packets, _ = audio_to_data(file_path)
|
||||
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
|
||||
# conn.close_after_chat = True
|
||||
|
||||
|
||||
# async def check_bind_device(conn):
|
||||
# if conn.bind_code:
|
||||
# # Ensure bind_code is a 6-digit number
|
||||
# if len(conn.bind_code) != 6:
|
||||
# conn.logger.bind(tag=TAG).error(
|
||||
# f"Invalid binding code format: {conn.bind_code}")
|
||||
# text = "Binding code format error, please check configuration."
|
||||
# await send_stt_message(conn, text)
|
||||
# return
|
||||
|
||||
# text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
|
||||
# await send_stt_message(conn, text)
|
||||
|
||||
# # Play notification sound
|
||||
# music_path = "config/assets/bind_code.wav"
|
||||
# opus_packets, _ = audio_to_data(music_path)
|
||||
# conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
|
||||
|
||||
# # Play digits one by one
|
||||
# for i in range(6): # Ensure only 6 digits are played
|
||||
# try:
|
||||
# digit = conn.bind_code[i]
|
||||
# num_path = f"config/assets/bind_code/{digit}.wav"
|
||||
# num_packets, _ = audio_to_data(num_path)
|
||||
# conn.tts.tts_audio_queue.put(
|
||||
# (SentenceType.MIDDLE, num_packets, None))
|
||||
# except Exception as e:
|
||||
# conn.logger.bind(tag=TAG).error(
|
||||
# f"Failed to play digit audio: {e}")
|
||||
# continue
|
||||
# conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
|
||||
# else:
|
||||
# text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
|
||||
# await send_stt_message(conn, text)
|
||||
# music_path = "config/assets/bind_not_found.wav"
|
||||
# opus_packets, _ = audio_to_data(music_path)
|
||||
# conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
|
||||
|
||||
from core.handle.sendAudioHandle import send_stt_message
|
||||
from core.handle.intentHandler import handle_user_intent
|
||||
from core.utils.output_counter import check_device_output_limit
|
||||
|
|
@ -228,7 +27,7 @@ async def handleAudioMessage(conn, audio):
|
|||
return
|
||||
|
||||
# Whether the current segment has someone speaking
|
||||
have_voice = await conn.vad.is_vad(conn, audio)
|
||||
have_voice = conn.vad.is_vad(conn, audio)
|
||||
|
||||
# Track when voice recording starts in auto VAD mode (for 10-second timeout)
|
||||
# Only set the timer once per recording session when transitioning from no-voice to voice
|
||||
|
|
|
|||
|
|
@ -39,11 +39,9 @@ class ASRProviderBase(ABC):
|
|||
|
||||
# Process ASR audio in order
|
||||
def asr_text_priority_thread(self, conn):
|
||||
logger.bind(tag=TAG).info("ASR audio processing thread started")
|
||||
while not conn.stop_event.is_set():
|
||||
try:
|
||||
message = conn.asr_audio_queue.get(timeout=1)
|
||||
logger.bind(tag=TAG).debug(f"ASR thread processing audio: {len(message)} bytes")
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
handleAudioMessage(conn, message),
|
||||
conn.loop,
|
||||
|
|
@ -397,46 +395,6 @@ class ASRProviderBase(ABC):
|
|||
"""Convert speech data to text"""
|
||||
pass
|
||||
|
||||
async def start_streaming_session(self, conn, session_id: str) -> bool:
|
||||
"""Start a streaming ASR session for real-time transcription.
|
||||
|
||||
Args:
|
||||
conn: Connection object
|
||||
session_id: Unique session identifier
|
||||
|
||||
Returns:
|
||||
True if session started successfully, False otherwise
|
||||
"""
|
||||
logger.bind(tag=TAG).warning("Streaming not implemented for this ASR provider")
|
||||
return False
|
||||
|
||||
async def stream_audio_chunk(self, conn, audio_chunk: bytes, session_id: str) -> Optional[str]:
|
||||
"""Stream an audio chunk to the active ASR session.
|
||||
|
||||
Args:
|
||||
conn: Connection object
|
||||
audio_chunk: PCM audio data to stream
|
||||
session_id: Session identifier
|
||||
|
||||
Returns:
|
||||
Latest partial transcript if available, None otherwise
|
||||
"""
|
||||
logger.bind(tag=TAG).warning("Audio streaming not implemented for this ASR provider")
|
||||
return None
|
||||
|
||||
async def end_streaming_session(self, conn, session_id: str) -> Tuple[str, Optional[str]]:
|
||||
"""End the streaming ASR session and get final transcript.
|
||||
|
||||
Args:
|
||||
conn: Connection object
|
||||
session_id: Session identifier
|
||||
|
||||
Returns:
|
||||
Tuple of (final_transcript, file_path)
|
||||
"""
|
||||
logger.bind(tag=TAG).warning("Streaming session end not implemented for this ASR provider")
|
||||
return "", None
|
||||
|
||||
@staticmethod
|
||||
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
|
||||
"""Decode Opus audio data to PCM data"""
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from typing import Optional
|
|||
class VADProviderBase(ABC):
|
||||
|
||||
@abstractmethod
|
||||
async def is_vad(self, conn, data) -> bool:
|
||||
def is_vad(self, conn, data) -> bool:
|
||||
"""Detect voice activity in audio data"""
|
||||
pass
|
||||
|
||||
|
|
|
|||
|
|
@ -266,11 +266,11 @@ class VADProvider(VADProviderBase):
|
|||
"""Reset the VAD provider internal states."""
|
||||
self.analyzer.reset()
|
||||
|
||||
async def is_vad(self, conn, opus_packet) -> bool:
|
||||
"""Detect voice activity in Opus audio packet and stream to ASR.
|
||||
def is_vad(self, conn, opus_packet) -> bool:
|
||||
"""Detect voice activity in Opus audio packet.
|
||||
|
||||
This method handles VAD detection and streaming to ASR in real-time,
|
||||
replacing the old buffer-based approach.
|
||||
This method maintains compatibility with the existing interface while
|
||||
using the new production-ready VAD analyzer internally.
|
||||
|
||||
Args:
|
||||
conn: Connection object with client state
|
||||
|
|
@ -288,99 +288,23 @@ class VADProvider(VADProviderBase):
|
|||
|
||||
# Log VAD state for debugging (only log state changes)
|
||||
if not hasattr(self, '_last_logged_state') or self._last_logged_state != vad_state:
|
||||
logger.bind(tag=TAG).info(f"[VAD-STATE] VAD state changed to: {vad_state.name} for {conn.session_id}")
|
||||
logger.bind(tag=TAG).info(f"VAD state: {vad_state.name}")
|
||||
self._last_logged_state = vad_state
|
||||
|
||||
# Update connection state based on VAD state
|
||||
# Include STOPPING state because it still contains speech that should be processed
|
||||
current_have_voice = vad_state in [VADState.SPEAKING, VADState.STARTING, VADState.STOPPING]
|
||||
current_have_voice = vad_state in [VADState.SPEAKING, VADState.STARTING]
|
||||
|
||||
# Handle streaming session management based on VAD state
|
||||
if vad_state == VADState.STARTING and not getattr(conn, 'asr_streaming_active', False):
|
||||
# Start streaming session when voice begins
|
||||
logger.bind(tag=TAG).info(f"[VAD-START] Voice activity detected - starting ASR streaming session for {conn.session_id}")
|
||||
if hasattr(conn, 'asr_provider'):
|
||||
logger.bind(tag=TAG).debug(f"[VAD-START] ASR provider found: {type(conn.asr_provider).__name__}")
|
||||
success = await conn.asr_provider.start_streaming_session(conn, conn.session_id)
|
||||
if success:
|
||||
conn.asr_streaming_active = True
|
||||
conn.asr_stream_start_time = time.time()
|
||||
logger.bind(tag=TAG).info(f"[VAD-START] ASR streaming session started successfully for {conn.session_id}")
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"[VAD-START] Failed to start ASR streaming session for {conn.session_id}")
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"[VAD-START] No ASR provider found on connection {conn.session_id}")
|
||||
# Handle silence detection for sentence end
|
||||
if conn.client_have_voice and not current_have_voice:
|
||||
if vad_state == VADState.QUIET:
|
||||
stop_duration = time.time() * 1000 - conn.last_activity_time
|
||||
if stop_duration >= self.silence_threshold_ms:
|
||||
conn.client_voice_stop = True
|
||||
logger.bind(tag=TAG).info(f"Voice stopped after {stop_duration}ms silence")
|
||||
|
||||
# Stream audio during voice activity
|
||||
streaming_active = getattr(conn, 'asr_streaming_active', False)
|
||||
logger.bind(tag=TAG).info(f"[VAD-STREAM] Audio streaming check - streaming_active={streaming_active}, current_have_voice={current_have_voice}, vad_state={vad_state.name}")
|
||||
|
||||
if streaming_active and current_have_voice:
|
||||
if hasattr(conn, 'asr_provider'):
|
||||
# Stream the PCM audio chunk to ASR
|
||||
logger.bind(tag=TAG).info(f"[VAD-STREAM] Streaming {len(pcm_frame)} bytes to ASR for {conn.session_id}")
|
||||
partial_result = await conn.asr_provider.stream_audio_chunk(conn, pcm_frame, conn.session_id)
|
||||
if partial_result:
|
||||
logger.bind(tag=TAG).info(f"[VAD-STREAM] Partial transcript from ASR: '{partial_result}'")
|
||||
conn.latest_partial_transcript = partial_result
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"[VAD-STREAM] ASR provider not found on connection {conn.session_id}")
|
||||
elif streaming_active:
|
||||
logger.bind(tag=TAG).debug(f"[VAD-STREAM] Streaming session active but no voice detected (state: {vad_state}) for {conn.session_id}")
|
||||
elif current_have_voice:
|
||||
logger.bind(tag=TAG).debug(f"[VAD-STREAM] Voice detected but no streaming session active for {conn.session_id}")
|
||||
|
||||
# Handle end of voice activity
|
||||
if vad_state == VADState.QUIET and getattr(conn, 'asr_streaming_active', False):
|
||||
# Check if enough silence has passed to end the session
|
||||
if not hasattr(conn, 'silence_start_time'):
|
||||
conn.silence_start_time = time.time()
|
||||
logger.bind(tag=TAG).debug(f"[VAD-END] Starting silence timer for {conn.session_id}")
|
||||
|
||||
silence_duration_ms = (time.time() - conn.silence_start_time) * 1000
|
||||
if silence_duration_ms >= self.silence_threshold_ms:
|
||||
logger.bind(tag=TAG).info(f"[VAD-END] Voice ended after {silence_duration_ms:.0f}ms silence - ending ASR streaming session for {conn.session_id}")
|
||||
|
||||
if hasattr(conn, 'asr_provider'):
|
||||
# End the streaming session and get final transcript
|
||||
logger.bind(tag=TAG).debug(f"[VAD-END] Calling end_streaming_session for {conn.session_id}")
|
||||
final_transcript, file_path = await conn.asr_provider.end_streaming_session(conn, conn.session_id)
|
||||
|
||||
if final_transcript.strip():
|
||||
logger.bind(tag=TAG).info(f"[VAD-END] Final transcript received: '{final_transcript}'")
|
||||
|
||||
# Process the final transcript (same as old system)
|
||||
from core.handle.receiveAudioHandle import startToChat
|
||||
logger.bind(tag=TAG).info(f"[VAD-END] Sending transcript to chat handler for {conn.session_id}")
|
||||
await startToChat(conn, final_transcript)
|
||||
else:
|
||||
logger.bind(tag=TAG).warning(f"[VAD-END] No speech detected in streaming session for {conn.session_id}")
|
||||
else:
|
||||
logger.bind(tag=TAG).error(f"[VAD-END] No ASR provider found for {conn.session_id}")
|
||||
|
||||
# Reset streaming state
|
||||
conn.asr_streaming_active = False
|
||||
if hasattr(conn, 'silence_start_time'):
|
||||
delattr(conn, 'silence_start_time')
|
||||
if hasattr(conn, 'asr_stream_start_time'):
|
||||
delattr(conn, 'asr_stream_start_time')
|
||||
if hasattr(conn, 'latest_partial_transcript'):
|
||||
delattr(conn, 'latest_partial_transcript')
|
||||
logger.bind(tag=TAG).info(f"[VAD-END] Streaming state reset for {conn.session_id}")
|
||||
else:
|
||||
logger.bind(tag=TAG).debug(f"[VAD-END] Silence duration {silence_duration_ms:.0f}ms < threshold {self.silence_threshold_ms}ms for {conn.session_id}")
|
||||
else:
|
||||
# Reset silence timer if voice is detected again
|
||||
if hasattr(conn, 'silence_start_time'):
|
||||
logger.bind(tag=TAG).debug(f"[VAD-END] Resetting silence timer for {conn.session_id}")
|
||||
delattr(conn, 'silence_start_time')
|
||||
|
||||
# Update legacy connection state for compatibility
|
||||
if current_have_voice:
|
||||
conn.client_have_voice = True
|
||||
conn.last_activity_time = time.time() * 1000
|
||||
else:
|
||||
conn.client_have_voice = False
|
||||
|
||||
# Update last voice state for compatibility
|
||||
if hasattr(conn, 'last_is_voice'):
|
||||
|
|
@ -393,6 +317,4 @@ class VADProvider(VADProviderBase):
|
|||
return False
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
|
||||
import traceback
|
||||
logger.bind(tag=TAG).debug(f"Traceback: {traceback.format_exc()}")
|
||||
return False
|
||||
Loading…
Reference in a new issue