From 255a403f8723876b4688afbb8596b3f2226dc693 Mon Sep 17 00:00:00 2001 From: karthikeyareddy183 Date: Fri, 12 Sep 2025 11:35:50 +0530 Subject: [PATCH] vad is not sending audio --- .../modules/security/config/WebMvcConfig.java | 4 +- .../src/main/resources/application-dev.yml | 2 +- ...02509081740_add_semantic_search_config.sql | 17 + main/manager-web/src/apis/module/agent.js | 27 +- .../src/components/ChatHistoryDialog.vue | 30 +- main/mqtt-gateway/config/mqtt.json | 4 +- main/xiaozhi-server/client.py | 8 +- main/xiaozhi-server/config.yaml | 59 +- main/xiaozhi-server/core/connection.py | 1253 +---------------- .../core/handle/receiveAudioHandle.py | 2 +- .../xiaozhi-server/core/providers/asr/base.py | 42 + .../core/providers/asr/google_speech_v2.py | 556 ++++++++ .../xiaozhi-server/core/providers/vad/base.py | 2 +- .../core/providers/vad/silero_onnx.py | 104 +- .../music/English/metadata.json | 566 +++++--- .../plugins_func/functions/play_story.py | 836 ----------- main/xiaozhi-server/requirements.txt | 4 +- main/xiaozhi-server/test_google_speech_v2.py | 234 +++ 18 files changed, 1478 insertions(+), 2272 deletions(-) create mode 100644 main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql create mode 100644 main/xiaozhi-server/core/providers/asr/google_speech_v2.py create mode 100644 main/xiaozhi-server/test_google_speech_v2.py diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java index 02538caf7..f650d9b28 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java @@ -63,8 +63,8 @@ public class WebMvcConfig implements WebMvcConfigurer { // 忽略未知属性 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // 设置时区 - mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); + // 设置时区 (IST - India Standard Time) + mapper.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // 配置Java8日期时间序列化 JavaTimeModule javaTimeModule = new JavaTimeModule(); diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 9bc3631c6..81251bfeb 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -22,7 +22,7 @@ spring: # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK driver-class-name: com.mysql.cj.jdbc.Driver # Railway MySQL Configuration - Updated for Railway database - url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true + url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Kolkata&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true username: root password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA diff --git a/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql b/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql new file mode 100644 index 000000000..c0da10028 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql @@ -0,0 +1,17 @@ +-- Add semantic search configuration for improved music search functionality +-- 添加语义搜索配置以改进音乐搜索功能 + +-- Delete existing semantic search params if they exist +delete from sys_params where id in (701, 702, 703, 704, 705, 706, 707); + +-- Insert semantic search configuration parameters +INSERT INTO sys_params +(id, param_code, param_value, value_type, param_type, remark, creator, create_date, updater, update_date) +VALUES +(701, 'semantic_search.enabled', 'true', 'boolean', 1, 'Enable semantic music search using vector embeddings', NULL, NULL, NULL, NULL), +(702, 'semantic_search.qdrant_url', 'https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io', 'string', 1, 'Qdrant vector database URL for music embeddings', NULL, NULL, NULL, NULL), +(703, 'semantic_search.qdrant_api_key', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk', 'string', 1, 'Qdrant API key for authentication', NULL, NULL, NULL, NULL), +(704, 'semantic_search.collection_name', 'xiaozhi_music', 'string', 1, 'Vector collection name for music embeddings', NULL, NULL, NULL, NULL), +(705, 'semantic_search.embedding_model', 'all-MiniLM-L6-v2', 'string', 1, 'Sentence transformer model for generating embeddings', NULL, NULL, NULL, NULL), +(706, 'semantic_search.search_limit', '5', 'number', 1, 'Maximum number of search results to return', NULL, NULL, NULL, NULL), +(707, 'semantic_search.min_score_threshold', '0.5', 'number', 1, 'Minimum similarity score threshold (0.0-1.0)', NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-web/src/apis/module/agent.js b/main/manager-web/src/apis/module/agent.js index d6ea74583..daa156efb 100644 --- a/main/manager-web/src/apis/module/agent.js +++ b/main/manager-web/src/apis/module/agent.js @@ -3,8 +3,29 @@ import RequestService from '../httpRequest'; export default { - // 获取智能体列表 - getAgentList(callback) { + // 获取智能体列表 (Admin - shows all agents from all users) + getAgentList(params, callback) { + // Support both old callback-only format and new params format + if (typeof params === 'function') { + callback = params; + params = { page: 1, limit: 1000 }; // Default pagination for all agents + } + RequestService.sendRequest() + .url(`${getServiceUrl()}/agent/all`) + .method('GET') + .data(params) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .networkFail(() => { + RequestService.reAjaxFun(() => { + this.getAgentList(params, callback); + }); + }).send(); + }, + // 获取用户自己的智能体列表 (User - shows only current user's agents) + getUserAgentList(callback) { RequestService.sendRequest() .url(`${getServiceUrl()}/agent/list`) .method('GET') @@ -14,7 +35,7 @@ export default { }) .networkFail(() => { RequestService.reAjaxFun(() => { - this.getAgentList(callback); + this.getUserAgentList(callback); }); }).send(); }, diff --git a/main/manager-web/src/components/ChatHistoryDialog.vue b/main/manager-web/src/components/ChatHistoryDialog.vue index 6afdf8796..8a4e441df 100644 --- a/main/manager-web/src/components/ChatHistoryDialog.vue +++ b/main/manager-web/src/components/ChatHistoryDialog.vue @@ -96,7 +96,7 @@ export default { const result = []; const TIME_INTERVAL = 60 * 1000; // 1分钟的时间间隔(毫秒) - // 添加第一条消息的时间标记 + // 添加第一条消息的时间标记 (converted to IST) if (this.messages[0]) { result.push({ type: 'time', @@ -118,7 +118,7 @@ export default { if (nextTime - currentTime > TIME_INTERVAL) { result.push({ type: 'time', - content: this.formatTime(this.messages[i + 1].createdAt), + content: this.formatTime(this.messages[i + 1].createdAt), // converted to IST id: `time-${Date.now()}-${Math.random().toString(36).substr(2, 9)}` }); } @@ -220,24 +220,36 @@ export default { }, 200); }, formatTime(timestamp) { + // Backend sends timestamps already in IST format, no timezone conversion needed const date = new Date(timestamp); const now = new Date(); + + // Create today and yesterday date objects for comparison const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const yesterday = new Date(today); yesterday.setDate(yesterday.getDate() - 1); - - const hours = date.getHours().toString().padStart(2, '0'); + + // Create message date object for comparison (without time) + const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + + // Format time in 12-hour format + const hours = date.getHours(); const minutes = date.getMinutes().toString().padStart(2, '0'); + const ampm = hours >= 12 ? 'PM' : 'AM'; + const displayHours = hours % 12 || 12; // Convert to 12-hour format + const timeStr = `${displayHours}:${minutes} ${ampm}`; - if (date >= today) { - return `Today ${hours}:${minutes}`; - } else if (date >= yesterday) { - return `Yesterday ${hours}:${minutes}`; + // Compare dates and return appropriate format + if (messageDate.getTime() === today.getTime()) { + return `Today ${timeStr}`; + } else if (messageDate.getTime() === yesterday.getTime()) { + return `Yesterday ${timeStr}`; } else { + // For older dates, show full date and time const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); - return `${year}-${month}-${day} ${hours}:${minutes}`; + return `${year}-${month}-${day} ${timeStr}`; } }, getAudioIconClass(message) { diff --git a/main/mqtt-gateway/config/mqtt.json b/main/mqtt-gateway/config/mqtt.json index 1f92fef87..db254e9fd 100644 --- a/main/mqtt-gateway/config/mqtt.json +++ b/main/mqtt-gateway/config/mqtt.json @@ -1,12 +1,12 @@ { "production": { "chat_servers": [ - "ws://64.227.170.31:8000/toy/v1/" + "ws://192.168.1.166:8000/toy/v1/" ] }, "development": { "chat_servers": [ - "ws://64.227.170.31:8000/toy/v1/" + "ws://192.168.1.166:8000/toy/v1/" ], "mac_addresss": [ ] diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index b1ff71f76..2c248c697 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -19,10 +19,10 @@ import opuslib # --- Configuration --- -SERVER_IP = "192.168.1.179" # !!! UPDATE with your server's local IP address !!! -OTA_PORT = 8002 -MQTT_BROKER_HOST = "192.168.1.179" # MQTT gateway IP - +SERVER_IP = "192.168.1.166" # !!! UPDATE with your server's local IP address !!! +OTA_PORT = 8003 +MQTT_BROKER_HOST = "192.168.1.166" # MQTT gateway IP + MQTT_BROKER_PORT = 1883 # DEVICE_MAC is now dynamically generated for uniqueness diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 18e410d3b..e6b29ab6d 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -404,6 +404,43 @@ ASR: # Language parameter, 1537 for Mandarin, specific reference: https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b dev_pid: 1537 output_dir: tmp/ + GoogleSpeechV2: + # Google Cloud Speech-to-Text v2 with Chirp 2 model + # Chirp 2 is Google's next-generation universal speech model with improved accuracy + # Setup instructions: + # 1. Enable Speech-to-Text API v2 in Google Cloud Console: https://console.cloud.google.com/apis/library/speech.googleapis.com + # 2. Create a service account: https://console.cloud.google.com/iam-admin/serviceaccounts + # 3. Download JSON credentials and set the path below + # Pricing: https://cloud.google.com/speech-to-text/v2/pricing + type: google_speech_v2 + # Google Cloud project ID + project_id: gen-lang-client-0652043794 + # Processing location for Chirp 2 (available in: us-central1, europe-west4, asia-southeast1) + # Note: API resource uses 'global' but processing happens in this region + location: us-central1 + # Path to service account credentials JSON file + credentials_path: "C:\\Users\\Acer\\Cheeko-esp32-server\\main\\xiaozhi-server\\gen-lang-client-0652043794-e5f4175261a8.json" + # Model to use (chirp_2 for best accuracy, latest_long for standard) + model: chirp_2 + # Language codes - Chirp 2 supports multiple languages simultaneously + # Examples: ["en-US"], ["zh-CN"], ["en-US", "zh-CN"] for multilingual + language_codes: + - en-US + # Audio encoding (LINEAR16 for PCM, OGG_OPUS for Opus) + encoding: LINEAR16 + # Sample rate in Hz (16000 recommended) + sample_rate_hertz: 16000 + # Enable automatic punctuation + enable_automatic_punctuation: true + # Enable word-level timestamps + enable_word_time_offsets: false + # Enable word confidence scores + enable_word_confidence: false + # Enable spoken punctuation (e.g., "period", "comma") + enable_spoken_punctuation: false + # Enable spoken emojis (e.g., "smiley face") + enable_spoken_emojis: false + output_dir: tmp/ VAD: SileroVAD: @@ -865,4 +902,24 @@ TTS: # Supports voice cloning, can upload your own audio, fill in voice parameter, when voice parameter is empty, uses default voice access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL" voice: "OUeAo1mhq6IBExi" - output_dir: tmp/ \ No newline at end of file + output_dir: tmp/ + +# ##################################################################################### +# ##############################Semantic Search Configuration########################### +# Semantic search for improved music matching using vector embeddings +semantic_search: + # Enable semantic search for music (requires Qdrant and sentence-transformers) + enabled: false # Set to true to enable + # Qdrant vector database URL (can be local or cloud instance) + qdrant_url: "https://your-qdrant-instance.com" # Change to your Qdrant URL + # Qdrant API key (required for cloud instances, optional for local) + qdrant_api_key: "your-qdrant-api-key" # Change to your API key + # Vector collection name for music embeddings + collection_name: "xiaozhi_music" + # Sentence transformer model for embeddings (smaller models are faster) + # Options: "all-MiniLM-L6-v2" (fast), "all-mpnet-base-v2" (better quality) + embedding_model: "all-MiniLM-L6-v2" + # Number of search results to return + search_limit: 5 + # Minimum similarity score threshold (0.0 to 1.0, higher = more strict) + min_score_threshold: 0.5 \ No newline at end of file diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index b956974b4..c6777dcfc 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1,1209 +1,3 @@ -# import os -# import sys -# import copy -# import json -# import uuid -# import time -# import queue -# import asyncio -# import threading -# import traceback -# import subprocess -# import websockets -# from core.utils.util import ( -# extract_json_from_string, -# check_vad_update, -# check_asr_update, -# filter_sensitive_info, -# ) -# from typing import Dict, Any -# from collections import deque -# from core.utils.modules_initialize import ( -# initialize_modules, -# initialize_tts, -# initialize_asr, -# ) -# from core.handle.reportHandle import report -# from core.providers.tts.default import DefaultTTS -# from concurrent.futures import ThreadPoolExecutor -# from core.utils.dialogue import Message, Dialogue -# from core.providers.asr.dto.dto import InterfaceType -# from core.handle.textHandle import handleTextMessage -# from core.providers.tools.unified_tool_handler import UnifiedToolHandler -# from plugins_func.loadplugins import auto_import_modules -# from plugins_func.register import Action, ActionResponse -# from core.auth import AuthMiddleware, AuthenticationError -# from config.config_loader import get_private_config_from_api -# from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType -# from config.logger import setup_logging, build_module_string, create_connection_logger -# from config.manage_api_client import DeviceNotFoundException, DeviceBindException -# from core.utils.prompt_manager import PromptManager -# from core.utils.voiceprint_provider import VoiceprintProvider -# from core.utils import textUtils - -# TAG = __name__ - -# auto_import_modules("plugins_func.functions") - - -# class TTSException(RuntimeError): -# pass - - -# class ConnectionHandler: -# def __init__( -# self, -# config: Dict[str, Any], -# _vad, -# _asr, -# _llm, -# _memory, -# _intent, -# server=None, -# ): -# self.common_config = config -# self.config = copy.deepcopy(config) -# self.session_id = str(uuid.uuid4()) -# self.logger = setup_logging() -# self.server = server # Save a reference to the server instance - -# self.auth = AuthMiddleware(config) -# self.need_bind = False -# self.bind_code = None -# self.read_config_from_api = self.config.get( -# "read_config_from_api", False) - -# self.websocket = None -# self.headers = None -# self.device_id = None -# self.client_ip = None -# self.prompt = None -# self.welcome_msg = None -# self.max_output_size = 0 -# self.chat_history_conf = 0 -# self.audio_format = "opus" - -# # Client state related -# self.client_abort = False -# self.client_is_speaking = False -# self.client_listen_mode = "auto" - -# # Thread task related -# self.loop = asyncio.get_event_loop() -# self.stop_event = threading.Event() -# self.executor = ThreadPoolExecutor(max_workers=5) - -# # Add reporting thread pool -# self.report_queue = queue.Queue() -# self.report_thread = None -# # This can be modified in the future to adjust ASR and TTS reporting. Currently, both are enabled by default. -# self.report_asr_enable = self.read_config_from_api -# self.report_tts_enable = self.read_config_from_api - -# # Dependent components -# self.vad = None -# self.asr = None -# self.tts = None -# self._asr = _asr -# self._vad = _vad -# self.llm = _llm -# self.memory = _memory -# self.intent = _intent - -# # Manage voiceprint recognition separately for each connection -# self.voiceprint_provider = None - -# # VAD related variables -# self.client_audio_buffer = bytearray() -# self.client_have_voice = False -# # Unified activity timestamp (milliseconds) -# self.last_activity_time = 0.0 -# self.client_voice_stop = False -# self.client_voice_window = deque(maxlen=5) -# self.last_is_voice = False - -# # ASR related variables -# # Since a public local ASR might be used in actual deployment, variables cannot be exposed to the public ASR. -# # Therefore, variables related to ASR need to be defined here as private variables of the connection. -# self.asr_audio = [] -# self.asr_audio_queue = queue.Queue() - -# # Pre-buffer to store audio chunks before voice detection -# # This helps capture the beginning of speech that might be missed -# self.audio_pre_buffer = deque(maxlen=10) # Store last 10 chunks (600ms) before voice detection - -# # Audio recording timeout tracking -# self.audio_recording_start_time = None # When voice recording started -# self.max_audio_recording_seconds = 10 # Maximum recording duration in seconds - -# # LLM related variables -# self.llm_finish_task = True -# self.dialogue = Dialogue() - -# # TTS related variables -# self.sentence_id = None -# # Handle cases where TTS response has no text -# self.tts_MessageText = "" - -# # IoT related variables -# self.iot_descriptors = {} -# self.func_handler = None - -# self.cmd_exit = self.config["exit_commands"] -# self.max_cmd_length = 0 -# for cmd in self.cmd_exit: -# if len(cmd) > self.max_cmd_length: -# self.max_cmd_length = len(cmd) - -# # Whether to close the connection after the chat ends -# self.close_after_chat = False -# self.load_function_plugin = False -# self.intent_type = "nointent" - -# self.timeout_seconds = ( -# int(self.config.get("close_connection_no_voice_time", 120)) + 60 -# ) # Add 60 seconds to the original first-level close for a second-level close -# self.timeout_task = None - -# # {"mcp":true} indicates that the MCP function is enabled -# self.features = None - -# # Initialize prompt manager -# self.prompt_manager = PromptManager(config, self.logger) - -# async def handle_connection(self, ws): -# try: -# # Get and validate headers -# self.headers = dict(ws.request.headers) - -# if self.headers.get("device-id", None) is None: -# # Try to get device-id from the URL's query parameters -# from urllib.parse import parse_qs, urlparse - -# # Get the path from the WebSocket request -# request_path = ws.request.path -# if not request_path: -# self.logger.bind(tag=TAG).error( -# "Unable to get request path") -# return -# parsed_url = urlparse(request_path) -# query_params = parse_qs(parsed_url.query) -# if "device-id" in query_params: -# self.headers["device-id"] = query_params["device-id"][0] -# self.headers["client-id"] = query_params["client-id"][0] -# else: -# await ws.send("Port is normal. To test the connection, please use test_page.html") -# await self.close(ws) -# return -# real_ip = self.headers.get("x-real-ip") or self.headers.get( -# "x-forwarded-for" -# ) -# if real_ip: -# self.client_ip = real_ip.split(",")[0].strip() -# else: -# self.client_ip = ws.remote_address[0] -# self.logger.bind(tag=TAG).info( -# f"{self.client_ip} conn - Headers: {self.headers}" -# ) - -# # Perform authentication -# await self.auth.authenticate(self.headers) - -# # Authentication passed, continue processing -# self.websocket = ws -# self.device_id = self.headers.get("device-id", None) - -# # Initialize activity timestamp -# self.last_activity_time = time.time() * 1000 - -# # Start timeout check task -# self.timeout_task = asyncio.create_task(self._check_timeout()) - -# self.welcome_msg = self.config["xiaozhi"] -# self.welcome_msg["session_id"] = self.session_id - -# # Get differential configuration -# self._initialize_private_config() -# # Asynchronous initialization -# self.executor.submit(self._initialize_components) - -# try: -# async for message in self.websocket: -# await self._route_message(message) -# except websockets.exceptions.ConnectionClosed: -# self.logger.bind(tag=TAG).info("Client disconnected") - -# except AuthenticationError as e: -# self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}") -# return -# except Exception as e: -# stack_trace = traceback.format_exc() -# self.logger.bind(tag=TAG).error( -# f"Connection error: {str(e)}-{stack_trace}") -# return -# finally: -# try: -# await self._save_and_close(ws) -# except Exception as final_error: -# self.logger.bind(tag=TAG).error( -# f"Error during final cleanup: {final_error}") -# # Ensure the connection is closed even if saving memory fails -# try: -# await self.close(ws) -# except Exception as close_error: -# self.logger.bind(tag=TAG).error( -# f"Error during forced connection closure: {close_error}" -# ) - -# async def _save_and_close(self, ws): -# """Save memory and close the connection""" -# try: -# if self.memory: -# # Log where memory is being saved based on memory type -# memory_type = getattr(self, 'memory_type', 'unknown') -# if memory_type == "nomem": -# self.logger.bind(tag=TAG).info("Memory saving DISABLED (using nomem)") -# elif memory_type == "mem0ai": -# self.logger.bind(tag=TAG).info("Saving memory to MEM0 CLOUD") -# elif memory_type == "mem_local_short": -# self.logger.bind(tag=TAG).info("Saving memory to LOCAL STORAGE (mem_local_short)") -# else: -# self.logger.bind(tag=TAG).info(f"Saving memory using: {memory_type}") - -# # Use a thread pool to save memory asynchronously -# def save_memory_task(): -# try: -# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting memory save task for {memory_type}") -# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Dialogue messages count: {len(self.dialogue.dialogue) if self.dialogue and self.dialogue.dialogue else 0}") - -# # Create a new event loop (to avoid conflicts with the main loop) -# loop = asyncio.new_event_loop() -# asyncio.set_event_loop(loop) - -# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Calling memory.save_memory()") -# result = loop.run_until_complete( -# self.memory.save_memory(self.dialogue.dialogue) -# ) - -# if result: -# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Memory saved successfully using {memory_type}. Result: {result}") -# else: -# self.logger.bind(tag=TAG).warning(f"[MEM0-THREAD] Memory save returned None/False for {memory_type}") -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"[MEM0-THREAD] Failed to save memory: {e}") -# self.logger.bind(tag=TAG).error( -# f"[MEM0-THREAD] Exception traceback: {traceback.format_exc()}") -# finally: -# try: -# loop.close() -# except Exception: -# pass - -# # Start a thread to save memory, do not wait for completion -# self.logger.bind(tag=TAG).info(f"[MEM0-THREAD] Starting new thread for memory save") -# threading.Thread(target=save_memory_task, daemon=True).start() -# except Exception as e: -# self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}") -# finally: -# # Close the connection immediately, do not wait for memory saving to complete -# try: -# await self.close(ws) -# except Exception as close_error: -# self.logger.bind(tag=TAG).error( -# f"Failed to close connection after saving memory: {close_error}" -# ) - -# async def _route_message(self, message): -# """Message routing""" -# if isinstance(message, str): -# await handleTextMessage(self, message) -# elif isinstance(message, bytes): -# if self.vad is None: -# return -# if self.asr is None: -# return -# self.asr_audio_queue.put(message) - -# async def handle_restart(self, message): -# """Handle server restart request""" -# try: - -# self.logger.bind(tag=TAG).info( -# "Received server restart command, preparing to execute...") - -# # Send confirmation response -# await self.websocket.send( -# json.dumps( -# { -# "type": "server", -# "status": "success", -# "message": "Server restarting...", -# "content": {"action": "restart"}, -# } -# ) -# ) - -# # Asynchronously execute the restart operation -# def restart_server(): -# """The actual method to execute the restart""" -# time.sleep(1) -# self.logger.bind(tag=TAG).info("Executing server restart...") -# subprocess.Popen( -# [sys.executable, "app.py"], -# stdin=sys.stdin, -# stdout=sys.stdout, -# stderr=sys.stderr, -# start_new_session=True, -# ) -# os._exit(0) - -# # Use a thread to execute the restart to avoid blocking the event loop -# threading.Thread(target=restart_server, daemon=True).start() - -# except Exception as e: -# self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}") -# await self.websocket.send( -# json.dumps( -# { -# "type": "server", -# "status": "error", -# "message": f"Restart failed: {str(e)}", -# "content": {"action": "restart"}, -# } -# ) -# ) - -# def _initialize_components(self): -# try: -# self.selected_module_str = build_module_string( -# self.config.get("selected_module", {}) -# ) -# self.logger = create_connection_logger(self.selected_module_str) - -# """Initialize components""" -# if self.config.get("prompt") is not None: -# user_prompt = self.config["prompt"] -# # Use a quick prompt for initialization -# prompt = self.prompt_manager.get_quick_prompt(user_prompt) -# self.change_system_prompt(prompt) -# self.logger.bind(tag=TAG).info( -# f"Quickly initialized component: prompt successful {prompt[:50]}..." -# ) - -# """Initialize local components""" -# if self.vad is None: -# self.vad = self._vad -# if self.asr is None: -# self.asr = self._initialize_asr() - -# # Initialize voiceprint recognition -# self._initialize_voiceprint() - -# # Open speech recognition channel -# asyncio.run_coroutine_threadsafe( -# self.asr.open_audio_channels(self), self.loop -# ) -# if self.tts is None: -# self.tts = self._initialize_tts() -# # Open speech synthesis channel -# asyncio.run_coroutine_threadsafe( -# self.tts.open_audio_channels(self), self.loop -# ) - -# """Load memory""" -# self._initialize_memory() -# """Load intent recognition""" -# self._initialize_intent() -# """Initialize reporting thread""" -# self._init_report_threads() -# """Update system prompt""" -# self._init_prompt_enhancement() - -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Failed to instantiate components: {e}") - -# def _init_prompt_enhancement(self): -# # Update context information -# self.prompt_manager.update_context_info(self, self.client_ip) -# enhanced_prompt = self.prompt_manager.build_enhanced_prompt( -# self.config["prompt"], self.device_id, self.client_ip -# ) -# if enhanced_prompt: -# self.change_system_prompt(enhanced_prompt) -# self.logger.bind(tag=TAG).info( -# "System prompt has been enhanced and updated") - -# def _init_report_threads(self): -# """Initialize ASR and TTS reporting threads""" -# if not self.read_config_from_api or self.need_bind: -# return -# if self.chat_history_conf == 0: -# return -# if self.report_thread is None or not self.report_thread.is_alive(): -# self.report_thread = threading.Thread( -# target=self._report_worker, daemon=True -# ) -# self.report_thread.start() -# self.logger.bind(tag=TAG).info("TTS reporting thread started") - -# def _initialize_tts(self): -# """Initialize TTS""" -# tts = None -# if not self.need_bind: -# tts = initialize_tts(self.config) - -# if tts is None: -# tts = DefaultTTS(self.config, delete_audio_file=True) - -# return tts - -# def _initialize_asr(self): -# """Initialize ASR""" -# if self._asr.interface_type == InterfaceType.LOCAL: -# # If the public ASR is a local service, return directly -# # Because one local ASR instance can be shared by multiple connections -# asr = self._asr -# else: -# # If the public ASR is a remote service, initialize a new instance -# # Because a remote ASR involves a WebSocket connection and a receiving thread, each connection needs its own instance -# asr = initialize_asr(self.config) - -# return asr - -# def _initialize_voiceprint(self): -# """Initialize voiceprint recognition for the current connection""" -# try: -# voiceprint_config = self.config.get("voiceprint", {}) -# if voiceprint_config: -# self.voiceprint_provider = VoiceprintProvider( -# voiceprint_config) -# self.logger.bind(tag=TAG).info( -# "Voiceprint recognition function dynamically enabled on connection") -# else: -# self.logger.bind(tag=TAG).info( -# "Voiceprint recognition function not enabled or configuration is incomplete") -# except Exception as e: -# self.logger.bind(tag=TAG).warning( -# f"Voiceprint recognition initialization failed: {str(e)}") - -# def _initialize_private_config(self): -# """If getting from the configuration file, perform a second instantiation""" -# if not self.read_config_from_api: -# return -# """Get differential configuration from the interface for a second instantiation, not a full re-instantiation""" -# try: -# begin_time = time.time() -# private_config = get_private_config_from_api( -# self.config, -# self.headers.get("device-id"), -# self.headers.get("client-id", self.headers.get("device-id")), -# ) -# private_config["delete_audio"] = bool( -# self.config.get("delete_audio", True)) -# # Log the actual API key status for debugging (without exposing the full key) -# if "Memory" in private_config and "Memory_mem0ai" in private_config.get("Memory", {}): -# mem0_config = private_config["Memory"]["Memory_mem0ai"] -# api_key = mem0_config.get("api_key", "") - -# # DEBUG: Print the full API key to verify what's being received -# self.logger.bind(tag=TAG).info(f"[DEBUG] Raw mem0 API key received: '{api_key}'") - -# if api_key == "***": -# self.logger.bind(tag=TAG).warning( -# "Mem0 API key is MASKED (***) from manager API - please configure the actual API key in the Manager Web Dashboard under Provider Management" -# ) -# elif api_key: -# masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****" -# self.logger.bind(tag=TAG).debug(f"Mem0 API key received: {masked_key} (length: {len(api_key)})") -# else: -# self.logger.bind(tag=TAG).warning("Mem0 API key is empty in differential configuration") - -# self.logger.bind(tag=TAG).info( -# f"{time.time() - begin_time} seconds, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}" -# ) -# except DeviceNotFoundException as e: -# self.need_bind = True -# private_config = {} -# except DeviceBindException as e: -# self.need_bind = True -# self.bind_code = e.bind_code -# private_config = {} -# except Exception as e: -# self.need_bind = True -# self.logger.bind(tag=TAG).error( -# f"Failed to get differential configuration: {e}") -# private_config = {} - -# init_llm, init_tts, init_memory, init_intent = ( -# False, -# False, -# False, -# False, -# ) - -# init_vad = check_vad_update(self.common_config, private_config) -# init_asr = check_asr_update(self.common_config, private_config) - -# if init_vad: -# self.config["VAD"] = private_config["VAD"] -# self.config["selected_module"]["VAD"] = private_config["selected_module"][ -# "VAD" -# ] -# if init_asr: -# self.config["ASR"] = private_config["ASR"] -# self.config["selected_module"]["ASR"] = private_config["selected_module"][ -# "ASR" -# ] -# if private_config.get("TTS", None) is not None: -# init_tts = True -# self.config["TTS"] = private_config["TTS"] -# self.config["selected_module"]["TTS"] = private_config["selected_module"][ -# "TTS" -# ] -# if private_config.get("LLM", None) is not None: -# init_llm = True -# self.config["LLM"] = private_config["LLM"] -# self.config["selected_module"]["LLM"] = private_config["selected_module"][ -# "LLM" -# ] -# if private_config.get("VLLM", None) is not None: -# self.config["VLLM"] = private_config["VLLM"] -# self.config["selected_module"]["VLLM"] = private_config["selected_module"][ -# "VLLM" -# ] -# if private_config.get("Memory", None) is not None: -# init_memory = True -# self.config["Memory"] = private_config["Memory"] -# self.config["selected_module"]["Memory"] = private_config[ -# "selected_module" -# ]["Memory"] -# if private_config.get("Intent", None) is not None: -# init_intent = True -# self.config["Intent"] = private_config["Intent"] -# model_intent = private_config.get( -# "selected_module", {}).get("Intent", {}) -# self.config["selected_module"]["Intent"] = model_intent -# # Load plugin configuration -# if model_intent != "Intent_nointent": -# plugin_from_server = private_config.get("plugins", {}) -# for plugin, config_str in plugin_from_server.items(): -# plugin_from_server[plugin] = json.loads(config_str) -# self.config["plugins"] = plugin_from_server -# self.config["Intent"][self.config["selected_module"]["Intent"]][ -# "functions" -# ] = list(plugin_from_server.keys()) -# if private_config.get("prompt", None) is not None: -# self.config["prompt"] = private_config["prompt"] -# # Get voiceprint information -# if private_config.get("voiceprint", None) is not None: -# self.config["voiceprint"] = private_config["voiceprint"] -# if private_config.get("summaryMemory", None) is not None: -# self.config["summaryMemory"] = private_config["summaryMemory"] -# if private_config.get("device_max_output_size", None) is not None: -# self.max_output_size = int( -# private_config["device_max_output_size"]) -# if private_config.get("chat_history_conf", None) is not None: -# self.chat_history_conf = int(private_config["chat_history_conf"]) -# if private_config.get("mcp_endpoint", None) is not None: -# self.config["mcp_endpoint"] = private_config["mcp_endpoint"] -# try: -# modules = initialize_modules( -# self.logger, -# private_config, -# init_vad, -# init_asr, -# init_llm, -# init_tts, -# init_memory, -# init_intent, -# ) -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Failed to initialize components: {e}") -# modules = {} -# if modules.get("tts", None) is not None: -# self.tts = modules["tts"] -# if modules.get("vad", None) is not None: -# self.vad = modules["vad"] -# if modules.get("asr", None) is not None: -# self.asr = modules["asr"] -# if modules.get("llm", None) is not None: -# self.llm = modules["llm"] -# if modules.get("intent", None) is not None: -# self.intent = modules["intent"] -# if modules.get("memory", None) is not None: -# self.memory = modules["memory"] - -# def _initialize_memory(self): -# if self.memory is None: -# return -# """Initialize memory module""" -# self.memory.init_memory( -# role_id=self.device_id, -# llm=self.llm, -# summary_memory=self.config.get("summaryMemory", None), -# save_to_file=not self.read_config_from_api, -# ) - -# # Get memory summary configuration -# memory_config = self.config["Memory"] -# memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][ -# "type" -# ] -# # Store memory type for logging -# self.memory_type = memory_type - -# # If using nomem, return directly -# if memory_type == "nomem": -# self.logger.bind(tag=TAG).info("Memory module initialized: DISABLED (nomem)") -# return -# # Use mem_local_short mode -# elif memory_type == "mem_local_short": -# self.logger.bind(tag=TAG).info("Memory module initialized: LOCAL STORAGE (mem_local_short)") -# # ALWAYS use the main LLM for memory operations -# # This ensures consistency and avoids configuration issues -# self.memory.set_llm(self.llm) -# self.logger.bind(tag=TAG).info( -# f"Using main LLM ({self.config['selected_module']['LLM']}) for memory operations") -# elif memory_type == "mem0ai": -# self.logger.bind(tag=TAG).info("Memory module initialized: MEM0 CLOUD (mem0ai)") -# else: -# self.logger.bind(tag=TAG).info(f"Memory module initialized: {memory_type}") - -# def _initialize_intent(self): -# if self.intent is None: -# return -# self.intent_type = self.config["Intent"][ -# self.config["selected_module"]["Intent"] -# ]["type"] -# if self.intent_type == "function_call" or self.intent_type == "intent_llm": -# self.load_function_plugin = True -# """Initialize intent recognition module""" -# # Get intent recognition configuration -# intent_config = self.config["Intent"] -# intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ -# "type" -# ] - -# # If using nointent, return directly -# if intent_type == "nointent": -# return -# # Use intent_llm mode -# elif intent_type == "intent_llm": -# intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ -# "llm" -# ] - -# if intent_llm_name and intent_llm_name in self.config["LLM"]: -# # If a dedicated LLM is configured, create an independent LLM instance -# from core.utils import llm as llm_utils - -# intent_llm_config = self.config["LLM"][intent_llm_name] -# intent_llm_type = intent_llm_config.get( -# "type", intent_llm_name) -# intent_llm = llm_utils.create_instance( -# intent_llm_type, intent_llm_config -# ) -# self.logger.bind(tag=TAG).info( -# f"Created a dedicated LLM for intent recognition: {intent_llm_name}, type: {intent_llm_type}" -# ) -# self.intent.set_llm(intent_llm) -# else: -# # Otherwise use main LLM -# self.intent.set_llm(self.llm) -# self.logger.bind(tag=TAG).info( -# "Using main LLM as intent recognition model") - -# """Load unified tool handler""" -# self.func_handler = UnifiedToolHandler(self) - -# # Asynchronously initialize tool handler -# if hasattr(self, "loop") and self.loop: -# asyncio.run_coroutine_threadsafe( -# self.func_handler._initialize(), self.loop) - -# def change_system_prompt(self, prompt): -# self.prompt = prompt -# # Update system prompt in the context -# self.dialogue.update_system_message(self.prompt) - -# def chat(self, query, tool_call=False, depth=0): -# self.logger.bind(tag=TAG).info(f"LLM received user message: {query}") -# self.llm_finish_task = False - -# if not tool_call: -# self.dialogue.put(Message(role="user", content=query)) - -# # Create a new session ID and send a FIRST request for the top-level call -# if depth == 0: -# self.sentence_id = str(uuid.uuid4().hex) -# self.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=self.sentence_id, -# sentence_type=SentenceType.FIRST, -# content_type=ContentType.ACTION, -# ) -# ) - -# # Define intent functions -# functions = None -# if self.intent_type == "function_call" and hasattr(self, "func_handler"): -# functions = self.func_handler.get_functions() -# response_message = [] - -# try: -# # Use dialogue with memory -# memory_str = None -# if self.memory is not None: -# future = asyncio.run_coroutine_threadsafe( -# self.memory.query_memory(query), self.loop -# ) -# memory_str = future.result() - -# if self.intent_type == "function_call" and functions is not None: -# # Use streaming interface that supports functions -# llm_responses = self.llm.response_with_functions( -# self.session_id, -# self.dialogue.get_llm_dialogue_with_memory( -# memory_str, self.config.get("voiceprint", {}) -# ), -# functions=functions, -# ) -# else: -# llm_responses = self.llm.response( -# self.session_id, -# self.dialogue.get_llm_dialogue_with_memory( -# memory_str, self.config.get("voiceprint", {}) -# ), -# ) -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"LLM processing error for '{query}': {e}") - -# ##Hre to - -# # Send error message to client and ensure proper completion -# if depth == 0: -# error_message = "Sorry, I'm having trouble understanding right now. Please try again." -# self.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=self.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.TEXT, -# content_detail=error_message, -# ) -# ) -# # Send completion signal -# self.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=self.sentence_id, -# sentence_type=SentenceType.LAST, -# content_type=ContentType.ACTION, -# ) -# ) - -# self.llm_finish_task = True - -# #here -# return None - -# # Handle streaming response -# tool_call_flag = False -# function_name = None -# function_id = None -# function_arguments = "" -# content_arguments = "" -# self.client_abort = False -# emotion_flag = True -# for response in llm_responses: -# if self.client_abort: -# break -# if self.intent_type == "function_call" and functions is not None: -# content, tools_call = response -# if "content" in response: -# content = response["content"] -# tools_call = None -# if content is not None and len(content) > 0: -# content_arguments += content - -# if not tool_call_flag and content_arguments.startswith(""): -# # print("content_arguments", content_arguments) -# tool_call_flag = True - -# if tools_call is not None and len(tools_call) > 0: -# tool_call_flag = True -# if tools_call[0].id is not None: -# function_id = tools_call[0].id -# if tools_call[0].function.name is not None: -# function_name = tools_call[0].function.name -# if tools_call[0].function.arguments is not None: -# function_arguments += tools_call[0].function.arguments -# else: -# content = response - -# # Get emotion from LLM reply, only once at the beginning of a conversation turn -# if emotion_flag and content is not None and content.strip(): -# asyncio.run_coroutine_threadsafe( -# textUtils.get_emotion(self, content), -# self.loop, -# ) -# emotion_flag = False - -# if content is not None and len(content) > 0: -# if not tool_call_flag: -# response_message.append(content) -# self.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=self.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.TEXT, -# content_detail=content, -# ) -# ) -# # Handle function call -# if tool_call_flag: -# bHasError = False -# if function_id is None: -# a = extract_json_from_string(content_arguments) -# if a is not None: -# try: -# content_arguments_json = json.loads(a) -# function_name = content_arguments_json["name"] -# function_arguments = json.dumps( -# content_arguments_json["arguments"], ensure_ascii=False -# ) -# function_id = str(uuid.uuid4().hex) -# except Exception as e: -# bHasError = True -# response_message.append(a) -# else: -# bHasError = True -# response_message.append(content_arguments) -# if bHasError: -# self.logger.bind(tag=TAG).error( -# f"function call error: {content_arguments}" -# ) -# if not bHasError: -# # If the LLM needs to process a turn first, add relevant processed log information -# if len(response_message) > 0: -# text_buff = "".join(response_message) -# self.tts_MessageText = text_buff -# self.dialogue.put( -# Message(role="assistant", content=text_buff)) -# response_message.clear() -# self.logger.bind(tag=TAG).debug( -# f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}" -# ) -# function_call_data = { -# "name": function_name, -# "id": function_id, -# "arguments": function_arguments, -# } - -# # Use unified tool handler to process all tool calls -# result = asyncio.run_coroutine_threadsafe( -# self.func_handler.handle_llm_function_call( -# self, function_call_data -# ), -# self.loop, -# ).result() -# self._handle_function_result( -# result, function_call_data, depth=depth) - -# # Store dialogue content -# if len(response_message) > 0: -# text_buff = "".join(response_message) -# self.tts_MessageText = text_buff -# self.dialogue.put(Message(role="assistant", content=text_buff)) -# if depth == 0: -# self.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=self.sentence_id, -# sentence_type=SentenceType.LAST, -# content_type=ContentType.ACTION, -# ) -# ) -# self.llm_finish_task = True -# # Use lambda for delayed calculation, get_llm_dialogue() is only executed at DEBUG level -# self.logger.bind(tag=TAG).debug( -# lambda: json.dumps( -# self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False -# ) -# ) - -# return True - -# def _handle_function_result(self, result, function_call_data, depth): -# if result.action == Action.RESPONSE: # Respond directly to the front-end -# text = result.response -# self.tts.tts_one_sentence( -# self, ContentType.TEXT, content_detail=text) -# self.dialogue.put(Message(role="assistant", content=text)) -# elif result.action == Action.REQLLM: # Request LLM to generate a reply after calling the function -# text = result.result -# if text is not None and len(text) > 0: -# function_id = function_call_data["id"] -# function_name = function_call_data["name"] -# function_arguments = function_call_data["arguments"] -# self.dialogue.put( -# Message( -# role="assistant", -# tool_calls=[ -# { -# "id": function_id, -# "function": { -# "arguments": "{}" if function_arguments == "" else function_arguments, -# "name": function_name, -# }, -# "type": "function", -# "index": 0, -# } -# ], -# ) -# ) - -# self.dialogue.put( -# Message( -# role="tool", -# tool_call_id=( -# str(uuid.uuid4()) if function_id is None else function_id -# ), -# content=text, -# ) -# ) -# self.chat(text, tool_call=True, depth=depth + 1) -# elif result.action == Action.NOTFOUND or result.action == Action.ERROR: -# text = result.response if result.response else result.result -# self.tts.tts_one_sentence( -# self, ContentType.TEXT, content_detail=text) -# self.dialogue.put(Message(role="assistant", content=text)) -# else: -# pass - -# def _report_worker(self): -# """Chat history reporting worker thread""" -# while not self.stop_event.is_set(): -# try: -# # Get data from the queue, set a timeout to periodically check the stop event -# item = self.report_queue.get(timeout=1) -# if item is None: # Detect the poison pill object -# break -# try: -# # Check the thread pool status -# if self.executor is None: -# continue -# # Submit the task to the thread pool -# self.executor.submit(self._process_report, *item) -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Chat history reporting thread exception: {e}") -# except queue.Empty: -# continue -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Chat history reporting worker thread exception: {e}") - -# self.logger.bind(tag=TAG).info("Chat history reporting thread exited") - -# def _process_report(self, type, text, audio_data, report_time): -# """Process the reporting task""" -# try: -# # Execute the report (pass binary data) -# report(self, type, text, audio_data, report_time) -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Report processing exception: {e}") -# finally: -# # Mark the task as done -# self.report_queue.task_done() - -# def clearSpeakStatus(self): -# self.client_is_speaking = False -# self.logger.bind(tag=TAG).debug(f"Cleared server speaking status") - -# async def close(self, ws=None): -# """Resource cleanup method""" -# try: -# # Cancel the timeout task -# if self.timeout_task and not self.timeout_task.done(): -# self.timeout_task.cancel() -# try: -# await self.timeout_task -# except asyncio.CancelledError: -# pass -# self.timeout_task = None - -# # Clean up tool handler resources -# if hasattr(self, "func_handler") and self.func_handler: -# try: -# await self.func_handler.cleanup() -# except Exception as cleanup_error: -# self.logger.bind(tag=TAG).error( -# f"Error cleaning up tool handler: {cleanup_error}" -# ) - -# # Trigger the stop event -# if self.stop_event: -# self.stop_event.set() - -# # Clear task queues -# self.clear_queues() - -# # Close the WebSocket connection -# try: -# if ws: -# # Safely check WebSocket state and close -# try: -# if hasattr(ws, "closed") and not ws.closed: -# await ws.close() -# elif hasattr(ws, "state") and ws.state.name != "CLOSED": -# await ws.close() -# else: -# # If no closed attribute, try to close directly -# await ws.close() -# except Exception: -# # If closing fails, ignore the error -# pass -# elif self.websocket: -# try: -# if ( -# hasattr(self.websocket, "closed") -# and not self.websocket.closed -# ): -# await self.websocket.close() -# elif ( -# hasattr(self.websocket, "state") -# and self.websocket.state.name != "CLOSED" -# ): -# await self.websocket.close() -# else: -# # If no closed attribute, try to close directly -# await self.websocket.close() -# except Exception: -# # If closing fails, ignore the error -# pass -# except Exception as ws_error: -# self.logger.bind(tag=TAG).error( -# f"Error closing WebSocket connection: {ws_error}") - -# if self.tts: -# await self.tts.close() - -# # Finally close thread pool (avoid blocking) -# if self.executor: -# try: -# self.executor.shutdown(wait=False) -# except Exception as executor_error: -# self.logger.bind(tag=TAG).error( -# f"Error shutting down thread pool: {executor_error}" -# ) -# self.executor = None - -# self.logger.bind(tag=TAG).info("Connection resources released") -# except Exception as e: -# self.logger.bind(tag=TAG).error( -# f"Error occurred while closing connection: {e}") -# finally: -# # Ensure the stop event is set -# if self.stop_event: -# self.stop_event.set() - -# def clear_queues(self): -# """Clear all task queues""" -# if self.tts: -# self.logger.bind(tag=TAG).debug( -# f"Starting cleanup: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}" -# ) - -# # Use non-blocking method to clear queues -# for q in [ -# self.tts.tts_text_queue, -# self.tts.tts_audio_queue, -# self.report_queue, -# ]: -# if not q: -# continue -# while True: -# try: -# q.get_nowait() -# except queue.Empty: -# break - -# self.logger.bind(tag=TAG).debug( -# f"Cleanup completed: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}" -# ) - -# def reset_vad_states(self): -# self.client_audio_buffer = bytearray() -# self.client_have_voice = False -# self.client_voice_stop = False -# # Reset VAD provider internal states -# if hasattr(self, 'vad') and self.vad is not None: -# self.vad.reset() -# # Clear pre-buffer when resetting VAD states -# if hasattr(self, 'audio_pre_buffer'): -# self.audio_pre_buffer.clear() -# # Clear ASR audio buffer to prevent processing leftover audio -# if hasattr(self, 'asr_audio'): -# self.asr_audio.clear() -# # Clear ASR audio queue for this specific connection only -# if hasattr(self, 'asr_audio_queue'): -# # Empty the queue by getting all items without blocking -# cleared_count = 0 -# while not self.asr_audio_queue.empty(): -# try: -# self.asr_audio_queue.get_nowait() -# cleared_count += 1 -# except queue.Empty: -# break -# if cleared_count > 0: -# self.logger.bind(tag=TAG).debug(f"Cleared {cleared_count} audio chunks from ASR queue") -# self.logger.bind(tag=TAG).info("VAD states reset.") - -# def chat_and_close(self, text): -# """Chat with the user and then close the connection""" -# try: -# # Use the existing chat method -# self.chat(text) - -# # After chat is complete, close the connection -# self.close_after_chat = True -# except Exception as e: -# self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}") - -# async def _check_timeout(self): -# """Check for connection timeout""" -# try: -# while not self.stop_event.is_set(): -# # Check for timeout (only if the timestamp has been initialized) -# if self.last_activity_time > 0.0: -# current_time = time.time() * 1000 -# if ( -# current_time - self.last_activity_time -# > self.timeout_seconds * 1000 -# ): -# if not self.stop_event.is_set(): -# self.logger.bind(tag=TAG).info( -# "Connection timed out, preparing to close") -# # Set the stop event to prevent duplicate processing -# self.stop_event.set() -# # Use try-except to wrap the close operation, ensuring no blocking due to exceptions -# try: -# await self.close(self.websocket) -# except Exception as close_error: -# self.logger.bind(tag=TAG).error( -# f"Error closing connection on timeout: {close_error}" -# ) -# break -# # Check every 10 seconds to avoid being too frequent -# await asyncio.sleep(10) -# except Exception as e: -# self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}") -# finally: -# self.logger.bind(tag=TAG).info("Timeout check task has exited") - import os import sys import copy @@ -1315,6 +109,9 @@ class ConnectionHandler: self.llm = _llm self.memory = _memory self.intent = _intent + + # ASR provider reference for VAD streaming + self.asr_provider = None # Manage voiceprint recognition separately for each connection self.voiceprint_provider = None @@ -1522,14 +319,51 @@ class ConnectionHandler: async def _route_message(self, message): """Message routing""" if isinstance(message, str): + self.logger.bind(tag=TAG).debug(f"Received text message: {message[:100]}...") await handleTextMessage(self, message) elif isinstance(message, bytes): + self.logger.bind(tag=TAG).debug(f"Received audio message: {len(message)} bytes") if self.vad is None: + self.logger.bind(tag=TAG).error("VAD is None, cannot process audio") return if self.asr is None: + self.logger.bind(tag=TAG).error("ASR is None, cannot process audio") return + + # For streaming ASR (like Chirp 2), call VAD directly for each audio packet + # This enables real-time streaming instead of batched processing + self.logger.bind(tag=TAG).info(f"Calling VAD directly for streaming ASR") + + # Call VAD asynchronously for each audio packet + asyncio.create_task(self._process_streaming_audio(message)) + + # Also put in queue for compatibility with non-streaming ASR + self.logger.bind(tag=TAG).debug(f"Putting audio message into ASR queue for compatibility") self.asr_audio_queue.put(message) + async def _process_streaming_audio(self, audio_packet): + """Process audio packet directly with VAD for streaming ASR. + + This method is called for each incoming audio packet to enable + real-time streaming to ASR providers like Chirp 2. + """ + try: + self.logger.bind(tag=TAG).debug(f"Processing streaming audio packet: {len(audio_packet)} bytes") + + # Call VAD directly for this audio packet + # This will handle streaming to ASR if voice is detected + have_voice = await self.vad.is_vad(self, audio_packet) + + # Update activity timestamp + if have_voice: + self.last_activity_time = time.time() * 1000 + self.logger.bind(tag=TAG).debug(f"Voice detected in streaming audio packet") + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error processing streaming audio: {e}") + import traceback + self.logger.bind(tag=TAG).debug(f"Streaming audio error traceback: {traceback.format_exc()}") + async def handle_restart(self, message): """Handle server restart request""" try: @@ -1601,14 +435,19 @@ class ConnectionHandler: self.vad = self._vad if self.asr is None: self.asr = self._initialize_asr() + + # Set ASR provider for VAD streaming + self.asr_provider = self.asr # Initialize voiceprint recognition self._initialize_voiceprint() # Open speech recognition channel + self.logger.bind(tag=TAG).info("Opening ASR audio channels...") asyncio.run_coroutine_threadsafe( self.asr.open_audio_channels(self), self.loop ) + self.logger.bind(tag=TAG).info("ASR audio channels opened") if self.tts is None: self.tts = self._initialize_tts() # Open speech synthesis channel @@ -1834,6 +673,8 @@ class ConnectionHandler: self.vad = modules["vad"] if modules.get("asr", None) is not None: self.asr = modules["asr"] + # Update ASR provider reference for VAD streaming + self.asr_provider = self.asr if modules.get("llm", None) is not None: self.llm = modules["llm"] if modules.get("intent", None) is not None: diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index da427d168..48ae0a71d 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -228,7 +228,7 @@ async def handleAudioMessage(conn, audio): return # Whether the current segment has someone speaking - have_voice = conn.vad.is_vad(conn, audio) + have_voice = await 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 diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 411b3b7df..f426a9aea 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -39,9 +39,11 @@ 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, @@ -395,6 +397,46 @@ 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""" diff --git a/main/xiaozhi-server/core/providers/asr/google_speech_v2.py b/main/xiaozhi-server/core/providers/asr/google_speech_v2.py new file mode 100644 index 000000000..628adfdb0 --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/google_speech_v2.py @@ -0,0 +1,556 @@ +import os +import time +import json +import asyncio +from google.cloud import speech_v2 +from google.api_core import exceptions +from google.api_core.client_options import ClientOptions +from config.logger import setup_logging +from typing import Optional, Tuple, List, AsyncIterator +from core.providers.asr.base import ASRProviderBase +from core.providers.asr.dto.dto import InterfaceType + +TAG = __name__ +logger = setup_logging() + + +class ASRProvider(ASRProviderBase): + """ + Google Cloud Speech-to-Text v2 Provider with Chirp 2 model support + Chirp 2 is Google's next-generation universal speech model with improved accuracy + """ + + def __init__(self, config: dict, delete_audio_file: bool): + super().__init__(config) + self.interface_type = InterfaceType.NON_STREAM + + # Google Cloud configuration + self.project_id = config.get("project_id") + self.location = config.get("location", "global") # Chirp 2 is available globally + self.credentials_path = config.get("credentials_path") + + # Model configuration - Chirp 2 specific + self.model = config.get("model", "chirp_2") # Use Chirp 2 by default + language_codes_from_config = config.get("language_codes", ["en-US"]) + + # Ensure language_codes is never empty (Google API requirement) + if not language_codes_from_config or not isinstance(language_codes_from_config, list): + self.language_codes = ["en-US"] + logger.bind(tag=TAG).warning(f"Invalid or empty language_codes in config, using default: ['en-US']") + else: + self.language_codes = language_codes_from_config + + # Debug logging for language codes + logger.bind(tag=TAG).info(f"Configured language_codes: {self.language_codes} (type: {type(self.language_codes)})") + + # Audio configuration + self.sample_rate_hertz = config.get("sample_rate_hertz", 16000) + self.encoding = config.get("encoding", "LINEAR16") + + # Recognition configuration + self.enable_automatic_punctuation = config.get("enable_automatic_punctuation", True) + self.enable_word_time_offsets = config.get("enable_word_time_offsets", False) + self.enable_word_confidence = config.get("enable_word_confidence", False) + self.enable_spoken_punctuation = config.get("enable_spoken_punctuation", False) + self.enable_spoken_emojis = config.get("enable_spoken_emojis", False) + + # File management + self.output_dir = config.get("output_dir", "./audio_files") + self.delete_audio_file = delete_audio_file + + # Set credentials if provided + if self.credentials_path: + os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = self.credentials_path + + # Initialize the Speech client with v2 API + try: + # For Chirp 2, use regional endpoint and recognizer + if self.model == "chirp_2": + # Use regional API endpoint for Chirp 2 + api_endpoint = f"{self.location}-speech.googleapis.com" + client_options = ClientOptions(api_endpoint=api_endpoint) + self.client = speech_v2.SpeechClient(client_options=client_options) + + # Use regional recognizer path to match regional endpoint + # Note: When using regional endpoint, recognizer path must also use same region + self.recognizer_name = f"projects/{self.project_id}/locations/{self.location}/recognizers/_" + logger.bind(tag=TAG).info(f"Using regional API endpoint: {api_endpoint}") + else: + # Use default global client and recognizer for standard models + self.client = speech_v2.SpeechClient() + self.recognizer_name = f"projects/{self.project_id}/locations/global/recognizers/_" + + logger.bind(tag=TAG).info( + f"Google Speech v2 initialized with model: {self.model}, " + f"project: {self.project_id}, recognizer: {self.recognizer_name}" + ) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to initialize Google Speech v2 client: {e}") + raise + + # Ensure output directory exists + os.makedirs(self.output_dir, exist_ok=True) + + # Streaming session management + self.streaming_sessions = {} # conn.session_id -> streaming session data + + def _get_audio_encoding(self): + """Map encoding string to Google Speech enum""" + try: + encoding_map = { + "LINEAR16": speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16, + "FLAC": speech_v2.ExplicitDecodingConfig.AudioEncoding.FLAC, + "MULAW": speech_v2.ExplicitDecodingConfig.AudioEncoding.MULAW, + "AMR": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR, + "AMR_WB": speech_v2.ExplicitDecodingConfig.AudioEncoding.AMR_WB, + "OGG_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.OGG_OPUS, + "MP3": speech_v2.ExplicitDecodingConfig.AudioEncoding.MP3, + "WEBM_OPUS": speech_v2.ExplicitDecodingConfig.AudioEncoding.WEBM_OPUS, + } + + # Add SPEEX if available (not all versions support it) + if hasattr(speech_v2.ExplicitDecodingConfig.AudioEncoding, 'SPEEX_WITH_HEADER_BYTE'): + encoding_map["SPEEX_WITH_HEADER_BYTE"] = speech_v2.ExplicitDecodingConfig.AudioEncoding.SPEEX_WITH_HEADER_BYTE + + return encoding_map.get(self.encoding, speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16) + except AttributeError as e: + logger.bind(tag=TAG).warning(f"Audio encoding {self.encoding} not supported, using LINEAR16: {e}") + return speech_v2.ExplicitDecodingConfig.AudioEncoding.LINEAR16 + + 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 using Google Cloud Speech v2 API with Chirp 2""" + start_time = time.time() + audio_file_path = None + + try: + # Decode Opus to PCM if needed + if audio_format == "opus": + pcm_data = self.decode_opus(opus_data) + if not pcm_data: + logger.bind(tag=TAG).error("Failed to decode Opus audio") + return "", None + else: + pcm_data = opus_data + + # Save audio to file for logging/debugging + audio_file_path = self.save_audio_to_file(pcm_data, session_id) + + # Combine PCM data + audio_content = b"".join(pcm_data) + + # Calculate audio length for logging + audio_length_seconds = len(audio_content) / (self.sample_rate_hertz * 2) # 16-bit audio + + # Configure recognition request - use model name as-is + model_name = self.model + encoding = self._get_audio_encoding() + logger.bind(tag=TAG).debug(f"Using model: {model_name} for recognition") + logger.bind(tag=TAG).debug(f"Audio encoding: {encoding}, sample_rate: {self.sample_rate_hertz}, audio_length: {len(audio_content)} bytes") + + # Configure recognition request based on model type + if self.model == "chirp_2": + # Use explicit decoding config for Chirp 2 with proper audio format + config = speech_v2.RecognitionConfig( + explicit_decoding_config=speech_v2.ExplicitDecodingConfig( + encoding=encoding, + sample_rate_hertz=self.sample_rate_hertz, + audio_channel_count=1, + ), + language_codes=self.language_codes, + model=model_name, # chirp_2 + features=speech_v2.RecognitionFeatures( + enable_automatic_punctuation=self.enable_automatic_punctuation, + enable_word_time_offsets=self.enable_word_time_offsets, + enable_word_confidence=self.enable_word_confidence, + enable_spoken_punctuation=self.enable_spoken_punctuation, + enable_spoken_emojis=self.enable_spoken_emojis, + profanity_filter=False, + ), + ) + else: + # Use explicit decoding for standard models + config = speech_v2.RecognitionConfig( + explicit_decoding_config=speech_v2.ExplicitDecodingConfig( + encoding=encoding, + sample_rate_hertz=self.sample_rate_hertz, + audio_channel_count=1, + ), + language_codes=self.language_codes, + model=model_name, + features=speech_v2.RecognitionFeatures( + enable_automatic_punctuation=self.enable_automatic_punctuation, + enable_word_time_offsets=self.enable_word_time_offsets, + enable_word_confidence=self.enable_word_confidence, + enable_spoken_punctuation=self.enable_spoken_punctuation, + enable_spoken_emojis=self.enable_spoken_emojis, + profanity_filter=False, + ), + ) + + # Create recognition request + request = speech_v2.RecognizeRequest( + recognizer=self.recognizer_name, + config=config, + content=audio_content, + ) + + # Perform synchronous speech recognition + try: + response = self.client.recognize(request=request) + + # Extract transcription from response + transcript = "" + confidence_scores = [] + + for result in response.results: + # Get the best alternative (highest confidence) + if result.alternatives: + best_alternative = result.alternatives[0] + transcript += best_alternative.transcript + " " + + # Collect confidence scores if available + if hasattr(best_alternative, 'confidence'): + confidence_scores.append(best_alternative.confidence) + + # Log word-level details if enabled + if self.enable_word_time_offsets and hasattr(best_alternative, 'words'): + for word_info in best_alternative.words: + logger.bind(tag=TAG).debug( + f"Word: {word_info.word}, " + f"Start: {word_info.start_offset}, " + f"End: {word_info.end_offset}" + ) + + transcript = transcript.strip() + + # Calculate average confidence if available + avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else None + + elapsed_time = time.time() - start_time + logger.bind(tag=TAG).info( + f"Google Speech v2 (Chirp 2) transcription completed in {elapsed_time:.2f}s" + f"{f', confidence: {avg_confidence:.2f}' if avg_confidence else ''}: {transcript}" + ) + + # Log the transcript for debugging/analysis + if transcript: + self.log_audio_transcript(audio_file_path, audio_length_seconds, transcript) + + return transcript, audio_file_path + + except exceptions.GoogleAPIError as e: + logger.bind(tag=TAG).error(f"Google Speech API error: {e}") + return "", audio_file_path + + except Exception as e: + logger.bind(tag=TAG).error( + f"Speech-to-text error: {str(e)}, type: {type(e).__name__}" + ) + import traceback + logger.bind(tag=TAG).debug(f"Traceback: {traceback.format_exc()}") + return "", audio_file_path + + finally: + # Clean up audio file if configured + if self.delete_audio_file and audio_file_path and os.path.exists(audio_file_path): + try: + os.remove(audio_file_path) + logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}") + except Exception as e: + logger.bind(tag=TAG).warning( + f"Failed to delete audio file {audio_file_path}: {e}" + ) + + 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 + """ + try: + logger.bind(tag=TAG).info(f"[STREAM-START] Starting streaming session: {session_id}") + + # Validate language codes + safe_language_codes = self.language_codes if self.language_codes else ["en-US"] + logger.bind(tag=TAG).debug(f"[STREAM-START] Using language_codes: {safe_language_codes}") + + # Create simplified session data with direct audio buffer + session_data = { + 'language_codes': safe_language_codes, + 'model': self.model, + 'audio_buffer': [], # Simple list to collect audio chunks + 'stream_iterator': None, + 'streaming_task': None, + 'final_transcript': "", + 'partial_transcript': "", + 'session_active': True, + 'audio_count': 0 + } + + # Store session + self.streaming_sessions[session_id] = session_data + logger.bind(tag=TAG).info(f"[STREAM-START] Session {session_id} created with simplified data structure") + + # Start the streaming task + session_data['streaming_task'] = asyncio.create_task( + self._simplified_streaming_task(session_id, session_data) + ) + + logger.bind(tag=TAG).info(f"[STREAM-START] Streaming session {session_id} started successfully") + return True + + except Exception as e: + logger.bind(tag=TAG).error(f"[STREAM-START] Failed to start streaming session {session_id}: {e}") + import traceback + logger.bind(tag=TAG).error(f"[STREAM-START] Traceback: {traceback.format_exc()}") + return False + + async def _simplified_streaming_task(self, session_id: str, session_data: dict): + """Simplified streaming task that processes audio directly without complex queues.""" + logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting simplified streaming task for session {session_id}") + + try: + # Create streaming configuration with explicit decoding (matches non-streaming config) + config = speech_v2.StreamingRecognitionConfig( + config=speech_v2.RecognitionConfig( + explicit_decoding_config=speech_v2.ExplicitDecodingConfig( + encoding=self._get_audio_encoding(), + sample_rate_hertz=self.sample_rate_hertz, + audio_channel_count=1, + ), + language_codes=session_data['language_codes'], + model=session_data['model'], + features=speech_v2.RecognitionFeatures( + enable_automatic_punctuation=self.enable_automatic_punctuation, + enable_word_time_offsets=self.enable_word_time_offsets, + enable_word_confidence=self.enable_word_confidence, + enable_spoken_punctuation=self.enable_spoken_punctuation, + enable_spoken_emojis=self.enable_spoken_emojis, + profanity_filter=False, + ), + ), + streaming_features=speech_v2.StreamingRecognitionFeatures( + interim_results=True, + enable_voice_activity_events=True, + ) + ) + + logger.bind(tag=TAG).info(f"[STREAM-TASK] Created config for {session_id}:") + logger.bind(tag=TAG).info(f" - Language codes: {session_data['language_codes']}") + logger.bind(tag=TAG).info(f" - Model: {session_data['model']}") + logger.bind(tag=TAG).info(f" - Encoding: {self._get_audio_encoding()}") + logger.bind(tag=TAG).info(f" - Sample rate: {self.sample_rate_hertz} Hz") + logger.bind(tag=TAG).info(f" - Channels: 1 (mono)") + + # Use a thread-safe queue to pass audio data to generator + import queue + import threading + + audio_queue = queue.Queue() + + def audio_generator(): + """Generator that yields audio requests to Google API.""" + logger.bind(tag=TAG).debug(f"[AUDIO-GEN] Starting audio generator for {session_id}") + + # First request: configuration + config_request = speech_v2.StreamingRecognizeRequest( + recognizer=self.recognizer_name, + streaming_config=config + ) + logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending config request for {session_id}") + yield config_request + + # Track audio chunks sent + chunks_sent = 0 + + # Process audio chunks from queue + while True: + try: + # Wait for audio data with timeout + audio_chunk = audio_queue.get(timeout=1.0) + + if audio_chunk is None: # End signal + logger.bind(tag=TAG).info(f"[AUDIO-GEN] Received end signal for {session_id}") + break + + chunks_sent += 1 + logger.bind(tag=TAG).info(f"[AUDIO-GEN] Sending audio chunk #{chunks_sent} ({len(audio_chunk)} bytes) for {session_id}") + + # Create and yield audio request + audio_request = speech_v2.StreamingRecognizeRequest(audio=audio_chunk) + yield audio_request + + except queue.Empty: + # Timeout - check if session is still active + if not session_data['session_active']: + logger.bind(tag=TAG).info(f"[AUDIO-GEN] Session {session_id} no longer active, stopping generator") + break + continue + except Exception as e: + logger.bind(tag=TAG).error(f"[AUDIO-GEN] Error in generator for {session_id}: {e}") + break + + logger.bind(tag=TAG).info(f"[AUDIO-GEN] Audio generator finished for {session_id} (sent {chunks_sent} chunks)") + + # Function to feed audio data from buffer to queue + def audio_feeder(): + """Feed audio data from session buffer to generator queue.""" + logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Starting audio feeder for {session_id}") + + try: + while session_data['session_active']: + # Check if we have audio data in buffer + if session_data['audio_buffer']: + audio_chunk = session_data['audio_buffer'].pop(0) + audio_queue.put(audio_chunk) + logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Moved audio chunk to queue for {session_id}") + else: + # No audio data, sleep briefly + import time + time.sleep(0.01) # 10ms + + # Send end signal when session ends + audio_queue.put(None) + logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Sent end signal for {session_id}") + + except Exception as e: + logger.bind(tag=TAG).error(f"[AUDIO-FEEDER] Error in feeder for {session_id}: {e}") + finally: + logger.bind(tag=TAG).debug(f"[AUDIO-FEEDER] Audio feeder finished for {session_id}") + + # Start audio feeder in separate thread + feeder_thread = threading.Thread(target=audio_feeder, daemon=True) + feeder_thread.start() + + # Start streaming recognition + logger.bind(tag=TAG).info(f"[STREAM-TASK] Starting Google API streaming for {session_id}") + responses = self.client.streaming_recognize(audio_generator()) + + # Process responses + response_count = 0 + for response in responses: + if not session_data['session_active']: + logger.bind(tag=TAG).info(f"[STREAM-TASK] Session {session_id} no longer active, stopping") + break + + response_count += 1 + logger.bind(tag=TAG).debug(f"[STREAM-TASK] Processing response #{response_count} for {session_id}") + + # Process recognition results + for result in response.results: + if result.alternatives: + transcript = result.alternatives[0].transcript + confidence = getattr(result.alternatives[0], 'confidence', 0.0) + + if result.is_final: + session_data['final_transcript'] += transcript + " " + session_data['partial_transcript'] = "" + logger.bind(tag=TAG).info(f"[STREAM-TASK] FINAL transcript for {session_id}: '{transcript}' (confidence: {confidence:.2f})") + else: + session_data['partial_transcript'] = transcript + logger.bind(tag=TAG).debug(f"[STREAM-TASK] PARTIAL transcript for {session_id}: '{transcript}'") + + logger.bind(tag=TAG).info(f"[STREAM-TASK] Completed streaming for {session_id} (processed {response_count} responses)") + + except Exception as e: + logger.bind(tag=TAG).error(f"[STREAM-TASK] Error in streaming task for {session_id}: {e}") + import traceback + logger.bind(tag=TAG).error(f"[STREAM-TASK] Traceback: {traceback.format_exc()}") + finally: + logger.bind(tag=TAG).info(f"[STREAM-TASK] Streaming task ended for {session_id}") + + 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).info(f"[STREAM-AUDIO] stream_audio_chunk called for {session_id} with {len(audio_chunk)} bytes") + try: + if session_id not in self.streaming_sessions: + logger.bind(tag=TAG).warning(f"[STREAM-AUDIO] No active streaming session for {session_id}") + return None + + session_data = self.streaming_sessions[session_id] + session_data['audio_count'] += 1 + + # Add audio chunk directly to buffer + session_data['audio_buffer'].append(audio_chunk) + logger.bind(tag=TAG).info(f"[STREAM-AUDIO] Added audio chunk #{session_data['audio_count']} ({len(audio_chunk)} bytes) to session {session_id}. Buffer size: {len(session_data['audio_buffer'])}") + + # Return latest partial transcript if available + partial = session_data.get('partial_transcript', '') + if partial: + logger.bind(tag=TAG).debug(f"[STREAM-AUDIO] Returning partial transcript for {session_id}: '{partial}'") + return partial + + return None + + except Exception as e: + logger.bind(tag=TAG).error(f"[STREAM-AUDIO] Error streaming audio chunk for {session_id}: {e}") + 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) + """ + try: + if session_id not in self.streaming_sessions: + logger.bind(tag=TAG).warning(f"[STREAM-END] No active streaming session for {session_id}") + return "", None + + session_data = self.streaming_sessions[session_id] + logger.bind(tag=TAG).info(f"[STREAM-END] Ending streaming session: {session_id}") + + # Signal end of audio stream + session_data['session_active'] = False + logger.bind(tag=TAG).debug(f"[STREAM-END] Marked session {session_id} as inactive") + + # Wait for streaming task to complete + if session_data['streaming_task']: + try: + logger.bind(tag=TAG).debug(f"[STREAM-END] Waiting for streaming task to complete for {session_id}") + await asyncio.wait_for(session_data['streaming_task'], timeout=3.0) + logger.bind(tag=TAG).debug(f"[STREAM-END] Streaming task completed for {session_id}") + except asyncio.TimeoutError: + logger.bind(tag=TAG).warning(f"[STREAM-END] Streaming task timeout for {session_id}, cancelling") + session_data['streaming_task'].cancel() + try: + await session_data['streaming_task'] + except asyncio.CancelledError: + pass + + # Get final transcript + final_transcript = session_data.get('final_transcript', '').strip() + audio_count = session_data.get('audio_count', 0) + + logger.bind(tag=TAG).info(f"[STREAM-END] Session {session_id} processed {audio_count} audio chunks") + logger.bind(tag=TAG).info(f"[STREAM-END] Final transcript for {session_id}: '{final_transcript}'") + + # Clean up session + del self.streaming_sessions[session_id] + + return final_transcript, None + + except Exception as e: + logger.bind(tag=TAG).error(f"[STREAM-END] Error ending streaming session {session_id}: {e}") + import traceback + logger.bind(tag=TAG).error(f"[STREAM-END] Traceback: {traceback.format_exc()}") + return "", None \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/vad/base.py b/main/xiaozhi-server/core/providers/vad/base.py index 3737be1d1..ce1af1d01 100644 --- a/main/xiaozhi-server/core/providers/vad/base.py +++ b/main/xiaozhi-server/core/providers/vad/base.py @@ -5,7 +5,7 @@ from typing import Optional class VADProviderBase(ABC): @abstractmethod - def is_vad(self, conn, data) -> bool: + async def is_vad(self, conn, data) -> bool: """Detect voice activity in audio data""" pass diff --git a/main/xiaozhi-server/core/providers/vad/silero_onnx.py b/main/xiaozhi-server/core/providers/vad/silero_onnx.py index ca7ae3052..ebc93b5ca 100644 --- a/main/xiaozhi-server/core/providers/vad/silero_onnx.py +++ b/main/xiaozhi-server/core/providers/vad/silero_onnx.py @@ -266,11 +266,11 @@ class VADProvider(VADProviderBase): """Reset the VAD provider internal states.""" self.analyzer.reset() - def is_vad(self, conn, opus_packet) -> bool: - """Detect voice activity in Opus audio packet. + async def is_vad(self, conn, opus_packet) -> bool: + """Detect voice activity in Opus audio packet and stream to ASR. - This method maintains compatibility with the existing interface while - using the new production-ready VAD analyzer internally. + This method handles VAD detection and streaming to ASR in real-time, + replacing the old buffer-based approach. Args: conn: Connection object with client state @@ -288,23 +288,99 @@ 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.name}") + logger.bind(tag=TAG).info(f"[VAD-STATE] VAD state changed to: {vad_state.name} for {conn.session_id}") self._last_logged_state = vad_state # Update connection state based on VAD state - current_have_voice = vad_state in [VADState.SPEAKING, VADState.STARTING] + # Include STOPPING state because it still contains speech that should be processed + current_have_voice = vad_state in [VADState.SPEAKING, VADState.STARTING, VADState.STOPPING] - # 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") + # 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}") + + # 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'): @@ -317,4 +393,6 @@ 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 \ No newline at end of file diff --git a/main/xiaozhi-server/music/English/metadata.json b/main/xiaozhi-server/music/English/metadata.json index 521cd36c1..011654214 100644 --- a/main/xiaozhi-server/music/English/metadata.json +++ b/main/xiaozhi-server/music/English/metadata.json @@ -1,194 +1,376 @@ { - "Baa Baa Black Sheep": { - "romanized": "Baa Baa Black Sheep", - "filename": "Baa Baa Black Sheep.mp3", - "alternatives": [ - "Baa Baa Black Sheep", - "baa baa black sheep", - "black sheep song", - "sheep song", - "nursery rhyme sheep", - "wool song", - "classic nursery rhyme", - "baa baa" - ] - }, - "Baby Shark Dance": { - "romanized": "Baby Shark Dance", - "filename": "Baby Shark Dance.mp3", - "alternatives": [ - "Baby Shark Dance", - "baby shark", - "shark song", - "doo doo doo", - "baby shark family", - "shark dance", - "kids shark song", - "popular kids song", - "viral kids song" - ] - }, - "Five Little Animals": { - "romanized": "Five Little Animals", - "filename": "Five Little Animals.mp3", - "alternatives": [ - "Five Little Animals", - "five animals", - "little animals", - "counting animals", - "animal counting song", - "5 little animals", - "animals song", - "counting song" - ] - }, - "Five Little Ducks": { - "romanized": "Five Little Ducks", - "filename": "Five Little Ducks.mp3", - "alternatives": [ - "Five Little Ducks", - "five ducks", - "little ducks", - "duck song", - "counting ducks", - "5 little ducks", - "ducks went swimming", - "mother duck song", - "quack quack song" - ] - }, - "Once I Caught A Fish Alive": { - "romanized": "Once I Caught A Fish Alive", - "filename": "Once I Caught A Fish Alive.mp3", - "alternatives": [ - "Once I Caught A Fish Alive", - "fish alive", - "caught a fish", - "fishing song", - "fish counting song", - "1 2 3 4 5 fish", - "counting fish", - "fish nursery rhyme" - ] - }, - "Ten Little Dinos": { - "romanized": "Ten Little Dinos", - "filename": "Ten Little Dinos.mp3", - "alternatives": [ - "Ten Little Dinos", - "ten dinos", - "little dinosaurs", - "dinosaur song", - "counting dinosaurs", - "10 little dinos", - "dino counting song", - "prehistoric song", - "kids dinosaur song" - ] - }, - "The Wheels on the Bus": { - "romanized": "The Wheels on the Bus", - "filename": "The Wheels on the Bus.mp3", - "alternatives": [ - "The Wheels on the Bus", - "wheels on the bus", - "bus song", - "wheels go round and round", - "children's bus song", - "classic kids song", - "nursery rhyme bus", - "preschool bus song", - "traditional children's song", - "kids transport song", - "bus wheels song", - "go round and round" - ] + "Baa Baa Black Sheep": { + "romanized": "Baa Baa Black Sheep", + "filename": "Baa Baa Black Sheep.mp3", + "alternatives": [ + "Baa Baa Black Sheep", + "baa baa black sheep", + "black sheep song", + "sheep song", + "nursery rhyme sheep", + "wool song", + "classic nursery rhyme", + "baa baa" + ] }, - "Head Shoulders Knees and Toes": { - "romanized": "Head Shoulders Knees and Toes", - "filename": "Head, Shoulders, Knees and Toes.mp3", - "alternatives": [ - "head shoulders knees and toes", - "body parts song", - "action song", - "exercise song", - "kids body song", - "nursery action song", - "movement song", - "body song" - ] - }, - "Hot Cross Buns": { - "romanized": "Hot Cross Buns", - "filename": "Hot Cross Buns.mp3", - "alternatives": [ - "hot cross buns", - "easter song", - "buns song", - "one a penny", - "two a penny", - "traditional nursery rhyme", - "food song", - "classic rhyme" - ] - }, - "I'm A Little Teapot": { - "romanized": "I'm A Little Teapot", - "filename": "I'm A Little Teapot.mp3", - "alternatives": [ - "i'm a little teapot", - "little teapot", - "teapot song", - "short and stout", - "tip me over", - "pour me out", - "action nursery rhyme", - "tea song" - ] - }, - "Johny Johny Yes Papa": { - "romanized": "Johny Johny Yes Papa", - "filename": "Johny Johny Yes Papa.mp3", - "alternatives": [ - "johny johny yes papa", - "johnny johnny", - "yes papa", - "eating sugar", - "no papa", - "telling lies", - "open your mouth", - "ha ha ha", - "popular kids song" - ] - }, - "Rain Rain Go Away": { - "romanized": "Rain Rain Go Away", - "filename": "Rain rain go away.mp3", - "alternatives": [ - "rain rain go away", - "come again another day", - "rain song", - "weather song", - "little johnny wants to play", - "rainy day song", - "nursery weather song", - "rain rhyme" - ] - }, - "Twinkle Twinkle Little Star": { - "romanized": "Twinkle Twinkle Little Star", - "filename": "Twinkle Twinkle Little Star.mp3", - "alternatives": [ - "twinkle twinkle little star", - "twinkle twinkle", - "little star", - "how i wonder what you are", - "star song", - "night song", - "lullaby", - "classic nursery rhyme", - "bedtime song", - "diamond in the sky" - ] - } - } \ No newline at end of file + "Baby Shark Dance": { + "romanized": "Baby Shark Dance", + "filename": "Baby Shark Dance.mp3", + "alternatives": [ + "Baby Shark Dance", + "baby shark", + "shark song", + "doo doo doo", + "baby shark family", + "shark dance", + "kids shark song", + "popular kids song", + "viral kids song" + ] + }, + "Five Little Animals": { + "romanized": "Five Little Animals", + "filename": "Five Little Animals.mp3", + "alternatives": [ + "Five Little Animals", + "five animals", + "little animals", + "counting animals", + "animal counting song", + "5 little animals", + "animals song", + "counting song" + ] + }, + "Five Little Ducks": { + "romanized": "Five Little Ducks", + "filename": "Five Little Ducks.mp3", + "alternatives": [ + "Five Little Ducks", + "five ducks", + "little ducks", + "duck song", + "counting ducks", + "5 little ducks", + "ducks went swimming", + "mother duck song", + "quack quack song" + ] + }, + "Once I Caught A Fish Alive": { + "romanized": "Once I Caught A Fish Alive", + "filename": "Once I Caught A Fish Alive.mp3", + "alternatives": [ + "Once I Caught A Fish Alive", + "fish alive", + "caught a fish", + "fishing song", + "fish counting song", + "1 2 3 4 5 fish", + "counting fish", + "fish nursery rhyme" + ] + }, + "Ten Little Dinos": { + "romanized": "Ten Little Dinos", + "filename": "Ten Little Dinos.mp3", + "alternatives": [ + "Ten Little Dinos", + "ten dinos", + "little dinosaurs", + "dinosaur song", + "counting dinosaurs", + "10 little dinos", + "dino counting song", + "prehistoric song", + "kids dinosaur song" + ] + }, + "The Wheels on the Bus": { + "romanized": "The Wheels on the Bus", + "filename": "The Wheels on the Bus.mp3", + "alternatives": [ + "The Wheels on the Bus", + "wheels on the bus", + "bus song", + "wheels go round and round", + "children's bus song", + "classic kids song", + "nursery rhyme bus", + "preschool bus song", + "traditional children's song", + "kids transport song", + "bus wheels song", + "go round and round" + ] +}, + "Head Shoulders Knees and Toes": { + "romanized": "Head Shoulders Knees and Toes", + "filename": "Head, Shoulders, Knees and Toes.mp3", + "alternatives": [ + "head shoulders knees and toes", + "body parts song", + "action song", + "exercise song", + "kids body song", + "nursery action song", + "movement song", + "body song" + ] + }, + "Hot Cross Buns": { + "romanized": "Hot Cross Buns", + "filename": "Hot Cross Buns.mp3", + "alternatives": [ + "hot cross buns", + "easter song", + "buns song", + "one a penny", + "two a penny", + "traditional nursery rhyme", + "food song", + "classic rhyme" + ] + }, + "I'm A Little Teapot": { + "romanized": "I'm A Little Teapot", + "filename": "I'm A Little Teapot.mp3", + "alternatives": [ + "i'm a little teapot", + "little teapot", + "teapot song", + "short and stout", + "tip me over", + "pour me out", + "action nursery rhyme", + "tea song" + ] + }, + "Johny Johny Yes Papa": { + "romanized": "Johny Johny Yes Papa", + "filename": "Johny Johny Yes Papa.mp3", + "alternatives": [ + "johny johny yes papa", + "johnny johnny", + "yes papa", + "eating sugar", + "no papa", + "telling lies", + "open your mouth", + "ha ha ha", + "popular kids song" + ] + }, + "Rain Rain Go Away": { + "romanized": "Rain Rain Go Away", + "filename": "Rain rain go away.mp3", + "alternatives": [ + "rain rain go away", + "come again another day", + "rain song", + "weather song", + "little johnny wants to play", + "rainy day song", + "nursery weather song", + "rain rhyme" + ] + }, + "Twinkle Twinkle Little Star": { + "romanized": "Twinkle Twinkle Little Star", + "filename": "Twinkle Twinkle Little Star.mp3", + "alternatives": [ + "twinkle twinkle little star", + "twinkle twinkle", + "little star", + "how i wonder what you are", + "star song", + "night song", + "lullaby", + "classic nursery rhyme", + "bedtime song", + "diamond in the sky" + ] + }, + "River Woods": { + "romanized": "River Woods", + "filename": "River Woods.mp3", + "alternatives": [ + "river woods", + "nature song", + "forest song", + "woodland song", + "river song", + "outdoor song", + "kids nature song" + ] + }, + "Hickory": { + "romanized": "Hickory", + "filename": "Hickory.mp3", + "alternatives": [ + "hickory", + "hickory dickory dock", + "mouse ran up the clock", + "clock song", + "time song", + "mouse song", + "classic nursery rhyme" + ] + }, + "Mary Lamb": { + "romanized": "Mary Lamb", + "filename": "Mary Lamb.mp3", + "alternatives": [ + "mary had a little lamb", + "little lamb", + "lamb song", + "mary lamb", + "fleece was white as snow", + "school song", + "classic nursery rhyme" + ] + }, + "One Two": { + "romanized": "One Two", + "filename": "One Two.mp3", + "alternatives": [ + "one two", + "buckle my shoe", + "counting song", + "number song", + "1 2 buckle my shoe", + "learning numbers", + "counting rhyme" + ] + }, + "Bingo": { + "romanized": "Bingo", + "filename": "Bingo.mp3", + "alternatives": [ + "bingo", + "b-i-n-g-o", + "farmer had a dog", + "dog song", + "spelling song", + "letter song", + "classic nursery rhyme" + ] + }, + "Hush Baby": { + "romanized": "Hush Baby", + "filename": "Hush Baby.mp3", + "alternatives": [ + "hush baby", + "hush little baby", + "don't say a word", + "mockingbird", + "lullaby", + "bedtime song", + "sleep song" + ] + }, + "Happy": { + "romanized": "Happy", + "filename": "Happy.mp3", + "alternatives": [ + "happy", + "if you're happy and you know it", + "clap your hands", + "action song", + "movement song", + "kids activity song" + ] + }, + "Sleeping": { + "romanized": "Sleeping", + "filename": "Sleeping.mp3", + "alternatives": [ + "sleeping", + "are you sleeping", + "brother john", + "frere jacques", + "morning bells", + "wake up song", + "lullaby" + ] + }, + "Hokey": { + "romanized": "Hokey", + "filename": "Hokey.mp3", + "alternatives": [ + "hokey", + "hokey pokey", + "put your right hand in", + "shake it all about", + "action song", + "dance song", + "movement song" + ] + }, + "ABC Song": { + "romanized": "ABC Song", + "filename": "ABC Song.mp3", + "alternatives": [ + "abc song", + "alphabet song", + "a b c d e f g", + "learning letters", + "alphabet", + "letter song", + "educational song" + ] + }, + "Splashing In The Sea Numbers": { + "romanized": "Splashing In The Sea Numbers", + "filename": "Splashing In The Sea Numbers.mp3", + "alternatives": [ + "splashing in the sea", + "sea numbers", + "ocean counting", + "water song", + "beach song", + "counting song", + "sea creatures" + ] + }, + "Five Little Monkeys Jumping On The Bed": { + "romanized": "Five Little Monkeys Jumping On The Bed", + "filename": "Five Little Monkeys Jumping On The Bed.mp3", + "alternatives": [ + "five little monkeys", + "jumping on the bed", + "monkeys jumping", + "one fell off", + "no more monkeys", + "counting monkeys", + "bedtime story song" + ] + }, + "Five Little Piggies Jumping On The Bed": { + "romanized": "Five Little Piggies Jumping On The Bed", + "filename": "Five Little Piggies Jumping On The Bed.mp3", + "alternatives": [ + "five little piggies", + "piggies jumping on bed", + "little pigs jumping", + "pig song", + "counting pigs", + "farm animals", + "bedtime song" + ] + }, + "Old MacDonald": { + "romanized": "Old MacDonald", + "filename": "Old MacDonald.mp3", + "alternatives": [ + "old macdonald", + "had a farm", + "e-i-e-i-o", + "farm song", + "animal sounds", + "cow goes moo", + "farm animals", + "classic nursery rhyme" + ] + } +} \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/play_story.py b/main/xiaozhi-server/plugins_func/functions/play_story.py index ea726a5be..d092f473c 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_story.py +++ b/main/xiaozhi-server/plugins_func/functions/play_story.py @@ -1,839 +1,3 @@ -# import os -# import re -# import time -# import random -# import difflib -# import traceback -# from pathlib import Path -# from core.handle.sendAudioHandle import send_stt_message -# from plugins_func.register import register_function, ToolType, ActionResponse, Action -# from core.utils.dialogue import Message -# from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType -# from plugins_func.utils.multilingual_matcher import MultilingualMatcher - -# # S3 Streaming imports -# import boto3 -# from botocore.exceptions import ClientError -# import logging - -# # CDN Download imports -# from core.utils.cdn_manager import download_cdn_file - -# TAG = __name__ - -# STORY_CACHE = {} -# STORY_MULTILINGUAL_MATCHER = None - -# # S3 Configuration -# S3_CLIENT = None -# S3_BUCKET_NAME = "cheeko-audio-files" - -# # Story categories mapping for better recognition -# STORY_CATEGORIES = { -# "bedtime": ["Bedtime", "bedtime story", "sleep story", "night story"], -# "fantasy": ["Fantasy", "fantasy story", "magical story", "magic story"], -# "fairy tales": ["Fairy Tales", "fairy tale", "fairytale"], -# "educational": ["Educational", "educational story", "learning story", "education"], -# "adventure": ["Adventure", "adventure story", "exciting story"] -# } - -# play_story_function_desc = { -# "type": "function", -# "function": { -# "name": "play_story", -# "description": ( -# "CRITICAL: This function ONLY plays pre-recorded story audio files from the stories folder. " -# "NEVER generate, create, or tell stories using text. ALWAYS call this function for ANY story request. " -# "This plays actual audio story files, not generated text stories. " -# "MANDATORY: Use this function for ALL story requests including: 'tell me a story', 'story please', " -# "'I want to hear a story', 'play a bedtime story', 'tell me The Boy Who Cried Wolf', etc. " -# "DO NOT create stories with text - only play pre-recorded audio story files. " -# "Examples: 'tell me a story' → play random story file, 'bedtime story' → play bedtime category file, " -# "'कहानी सुनाओ' (Hindi) → play story file, 'ಕಥೆ ಹೇಳಿ' (Kannada) → play story file" -# ), -# "parameters": { -# "type": "object", -# "properties": { -# "user_request": { -# "type": "string", -# "description": "Complete user request for story. Examples: 'tell me a story', 'tell me The Boy Who Cried Wolf story', 'play a bedtime story', 'I want to hear a fantasy story', 'story please', 'कहानी सुनाओ', 'ಕಥೆ ಹೇಳಿ'", -# }, -# "story_type": { -# "type": "string", -# "enum": ["specific", "category", "random"], -# "description": "Use 'specific' for ANY story title, name, or specific story request (e.g., 'golden gift story', 'The Boy Who Cried Wolf', 'Cinderella', 'three little pigs'). Use 'category' for category requests like 'bedtime story', 'fantasy story'. Use 'random' ONLY for very general requests like 'tell me any story', 'play a story'." -# }, -# "category_preference": { -# "type": "string", -# "description": "Story category if mentioned: 'bedtime', 'fantasy', 'fairy tales', 'educational', 'adventure'. Only set if explicitly mentioned.", -# }, -# "requested_language": { -# "type": "string", -# "description": "Language user requested the story in (e.g., 'hindi', 'english', 'kannada'). Note: Stories may be available in multiple languages depending on metadata.", -# } -# }, -# "required": ["user_request", "story_type"], -# }, -# }, -# } - - -# @register_function("play_story", play_story_function_desc, ToolType.SYSTEM_CTL) -# def play_story(conn, user_request: str, story_type: str = "random", category_preference: str = None, requested_language: str = None): -# try: -# # Initialize multilingual story system -# initialize_multilingual_story_system(conn) - -# # Log the request for debugging -# conn.logger.bind(tag=TAG).info(f"Story request: '{user_request}', type: {story_type}, category: {category_preference}, language: {requested_language}") - -# # Check event loop status -# if not conn.loop.is_running(): -# conn.logger.bind(tag=TAG).error("Event loop not running, cannot submit task") -# return ActionResponse( -# action=Action.RESPONSE, result="System busy", response="Please try again later" -# ) - -# # Submit async task with enhanced parameters -# task = conn.loop.create_task( -# handle_multilingual_story_command(conn, user_request, story_type, category_preference, requested_language) -# ) - -# # Non-blocking callback handling -# def handle_done(f): -# try: -# f.result() -# conn.logger.bind(tag=TAG).info("Multilingual story playback completed") -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Multilingual story playback failed: {e}") - -# task.add_done_callback(handle_done) - -# return ActionResponse( -# action=Action.NONE, -# result="Multilingual story command received", -# response="Let me find a wonderful story for you!" -# ) -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Error handling multilingual story request: {e}") -# return ActionResponse( -# action=Action.RESPONSE, result=str(e), response="Error occurred while processing your story request" -# ) - - -# def normalize_category_name(category_input): -# """Normalize story category name to match folder names""" -# if not category_input: -# return None - -# category_lower = category_input.lower().strip() - -# # Direct mapping for exact matches from LLM -# direct_mappings = { -# "bedtime": "Bedtime", -# "fantasy": "Fantasy", -# "fairy tales": "Fairy Tales", -# "educational": "Educational", -# "adventure": "Adventure", -# "random": None # None means select random category -# } - -# # Check direct mappings first -# if category_lower in direct_mappings: -# return direct_mappings[category_lower] - -# # Check against category variations -# for key, variations in STORY_CATEGORIES.items(): -# for variation in variations: -# if variation.lower() in category_lower or category_lower in variation.lower(): -# # Return the actual folder name -# if key == "bedtime": -# return "Bedtime" -# elif key == "fantasy": -# return "Fantasy" -# elif key == "fairy tales": -# return "Fairy Tales" -# elif key == "educational": -# return "Educational" -# elif key == "adventure": -# return "Adventure" - -# # If no match, return None to trigger random selection -# return None - - -# def get_story_files(story_dir, story_ext): -# """Get all story files organized by category - S3 MODE: Read from metadata.json""" -# import json - -# story_dir = Path(story_dir) -# story_files_by_category = {} -# all_story_files = [] - -# # Check if stories directory exists -# if not story_dir.exists(): -# return {}, [] - -# # Iterate through category folders -# for category_folder in story_dir.iterdir(): -# if category_folder.is_dir(): -# category_name = category_folder.name -# story_files_by_category[category_name] = [] - -# # Check for metadata.json file first (S3 mode) -# metadata_file = category_folder / "metadata.json" -# if metadata_file.exists(): -# try: -# with open(metadata_file, 'r', encoding='utf-8') as f: -# metadata = json.load(f) - -# # Add stories from metadata -# for story_title, story_info in metadata.items(): -# filename = story_info.get('filename', f"{story_title}.mp3") -# relative_path = f"{category_name}/{filename}" -# story_files_by_category[category_name].append(relative_path) -# all_story_files.append(relative_path) - -# logging.info(f"Loaded {len(metadata)} stories from {category_name} metadata") -# continue - -# except Exception as e: -# logging.error(f"Error reading metadata from {metadata_file}: {e}") - -# # Fallback: scan for actual audio files (legacy mode) -# for file in category_folder.rglob("*"): -# if file.is_file(): -# ext = file.suffix.lower() -# if ext in story_ext: -# relative_path = str(file.relative_to(story_dir)) -# story_files_by_category[category_name].append(relative_path) -# all_story_files.append(relative_path) - -# return story_files_by_category, all_story_files - - -# def initialize_s3_client(): -# """Initialize S3 client for streaming with SigV4""" -# global S3_CLIENT -# if S3_CLIENT is None: -# try: -# from botocore.config import Config - -# aws_access_key = os.getenv('AWS_ACCESS_KEY_ID') -# aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY') -# aws_region = os.getenv('AWS_DEFAULT_REGION', 'us-east-1') - -# if aws_access_key and aws_secret_key: -# S3_CLIENT = boto3.client( -# 's3', -# aws_access_key_id=aws_access_key, -# aws_secret_access_key=aws_secret_key, -# region_name=aws_region, -# config=Config(signature_version="s3v4") -# ) -# logging.info(f"S3 client initialized for story streaming (region: {aws_region})") -# else: -# logging.warning("AWS credentials not found, S3 streaming disabled") -# except Exception as e: -# logging.error(f"Failed to initialize S3 client: {e}") -# S3_CLIENT = None - -# def generate_cdn_story_url(category, filename): -# """Generate CDN streaming URL for story file""" -# try: -# # Import CDN helper -# from utils.cdn_helper import get_audio_url - -# # Ensure proper capitalization for S3 key (S3 folders are capitalized) -# # Handle special cases like "Fairy Tales" -# if category.lower() == "fairy tales": -# category_capitalized = "Fairy Tales" -# else: -# category_capitalized = category.capitalize() - -# audio_path = f"stories/{category_capitalized}/{filename}" - -# # Use CDN helper to generate URL with automatic encoding -# cdn_url = get_audio_url(audio_path) -# logging.info(f"Generated CDN URL for story: {audio_path} -> {cdn_url}") -# return cdn_url - -# except Exception as e: -# logging.error(f"Error generating CDN URL for story: {e}") -# # Fallback to S3 presigned URL if CDN fails -# return generate_s3_story_url_fallback(category, filename) - -# def generate_s3_story_url_fallback(category, filename): -# """Fallback S3 streaming URL for story file""" -# global S3_CLIENT, S3_BUCKET_NAME - -# if not S3_CLIENT: -# return None - -# try: -# # Ensure proper capitalization for S3 key (S3 folders are capitalized) -# # Handle special cases like "Fairy Tales" -# if category.lower() == "fairy tales": -# category_capitalized = "Fairy Tales" -# else: -# category_capitalized = category.capitalize() - -# s3_key = f"stories/{category_capitalized}/{filename}" -# url = S3_CLIENT.generate_presigned_url( -# 'get_object', -# Params={'Bucket': S3_BUCKET_NAME, 'Key': s3_key}, -# ExpiresIn=7200 # 2 hours for streaming -# ) -# logging.info(f"Generated fallback S3 URL for story: {s3_key}") -# return url -# except ClientError as e: -# logging.error(f"Error generating fallback S3 URL for story: {e}") -# return None - -# def initialize_story_handler(conn): -# """Initialize story handler with configuration""" -# global STORY_CACHE -# # Initialize S3 client -# initialize_s3_client() - -# if STORY_CACHE == {}: -# if "play_story" in conn.config["plugins"]: -# STORY_CACHE["story_config"] = conn.config["plugins"]["play_story"] -# STORY_CACHE["story_dir"] = os.path.abspath( -# STORY_CACHE["story_config"].get("story_dir", "./stories") -# ) -# STORY_CACHE["story_ext"] = STORY_CACHE["story_config"].get( -# "story_ext", (".mp3", ".wav", ".p3") -# ) -# STORY_CACHE["refresh_time"] = STORY_CACHE["story_config"].get( -# "refresh_time", 300 # Refresh every 5 minutes -# ) -# else: -# STORY_CACHE["story_dir"] = os.path.abspath("./stories") -# STORY_CACHE["story_ext"] = (".mp3", ".wav", ".p3") -# STORY_CACHE["refresh_time"] = 300 - -# # Get story files organized by category -# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( -# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] -# ) -# STORY_CACHE["scan_time"] = time.time() - -# # Log available categories -# if STORY_CACHE["story_files_by_category"]: -# conn.logger.bind(tag=TAG).info( -# f"Found story categories: {list(STORY_CACHE['story_files_by_category'].keys())}" -# ) -# for category, files in STORY_CACHE["story_files_by_category"].items(): -# conn.logger.bind(tag=TAG).info(f" {category}: {len(files)} stories") - -# return STORY_CACHE - -# def initialize_multilingual_story_system(conn): -# """Initialize the multilingual story matching system""" -# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE - -# # Initialize basic story cache first -# initialize_story_handler(conn) - -# # Initialize multilingual matcher if not already done -# if STORY_MULTILINGUAL_MATCHER is None: -# try: -# STORY_MULTILINGUAL_MATCHER = MultilingualMatcher( -# STORY_CACHE["story_dir"], -# STORY_CACHE["story_ext"] -# ) -# if STORY_MULTILINGUAL_MATCHER.language_folders: -# conn.logger.bind(tag=TAG).info(f"Multilingual story matcher initialized with languages: {STORY_MULTILINGUAL_MATCHER.language_folders}") -# else: -# conn.logger.bind(tag=TAG).info("Multilingual story matcher initialized (no metadata.json found, using filesystem fallback)") -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual story matcher: {e}") -# STORY_MULTILINGUAL_MATCHER = None - -# async def handle_multilingual_story_command(conn, user_request: str, story_type: str, category_preference: str = None, requested_language: str = None): -# """Enhanced story command handler with multilingual AI matching""" -# global STORY_MULTILINGUAL_MATCHER, STORY_CACHE - -# conn.logger.bind(tag=TAG).debug(f"Processing multilingual story request: '{user_request}'") - -# # Check if stories directory exists -# if not os.path.exists(STORY_CACHE["story_dir"]): -# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}") -# await send_stt_message(conn, "Sorry, I couldn't find the story collection.") -# return - -# # Refresh cache if needed -# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]: -# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( -# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] -# ) -# STORY_CACHE["scan_time"] = time.time() - -# selected_story = None -# match_info = None - -# # Try multilingual AI matching for specific stories -# if STORY_MULTILINGUAL_MATCHER and story_type == "specific": -# try: -# match_result = STORY_MULTILINGUAL_MATCHER.find_content_match(user_request, requested_language) -# if match_result: -# selected_story, detected_language, metadata_entry = match_result -# match_info = { -# 'method': 'ai_multilingual', -# 'language': detected_language, -# 'title': metadata_entry.get('romanized', 'Unknown'), -# 'original_title': list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[ -# list(STORY_MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry) -# ] if detected_language in STORY_MULTILINGUAL_MATCHER.metadata_cache else 'Unknown', -# 'category': 'unknown' -# } -# conn.logger.bind(tag=TAG).info(f"AI story match found: {selected_story} ({detected_language})") -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Error in AI story matching: {e}") - -# # Try language-specific selection if no AI match and language is specified -# if not selected_story and requested_language and STORY_MULTILINGUAL_MATCHER: -# try: -# language_content = STORY_MULTILINGUAL_MATCHER.get_language_specific_content(requested_language) -# if language_content: -# selected_path, metadata_entry = random.choice(language_content) -# selected_story = selected_path -# match_info = { -# 'method': 'language_random', -# 'language': requested_language, -# 'title': metadata_entry.get('romanized', 'Unknown'), -# 'category': 'unknown' -# } -# conn.logger.bind(tag=TAG).info(f"Language-specific story selection: {selected_story}") -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Error in language-specific story selection: {e}") - -# # Fallback to legacy category-based selection -# if not selected_story and category_preference: -# normalized_category = normalize_category_name(category_preference) -# if normalized_category and normalized_category in STORY_CACHE["story_files_by_category"]: -# if STORY_CACHE["story_files_by_category"][normalized_category]: -# selected_story = random.choice(STORY_CACHE["story_files_by_category"][normalized_category]) -# match_info = { -# 'method': 'category_selection', -# 'language': 'english', # Default assumption -# 'title': os.path.splitext(os.path.basename(selected_story))[0], -# 'category': normalized_category -# } -# conn.logger.bind(tag=TAG).info(f"Category-based story selection: {selected_story}") - -# # Try legacy specific story matching (for explicit specific requests) -# if not selected_story and story_type == "specific": -# # Extract story name and try fuzzy matching -# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"]) -# if story_name_match: -# selected_story = story_name_match -# match_info = { -# 'method': 'legacy_fuzzy', -# 'language': 'english', -# 'title': os.path.splitext(os.path.basename(selected_story))[0], -# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' -# } -# conn.logger.bind(tag=TAG).info(f"Legacy fuzzy story match: {selected_story}") - -# # SMART FALLBACK: Try specific story matching even for "random" requests that might contain story names -# # This handles cases where LLM misclassifies specific story requests as random -# if not selected_story and story_type != "specific": -# # Check if the request might contain a specific story name by trying fuzzy matching -# story_name_match = find_best_story_match(user_request, STORY_CACHE["all_story_files"]) -# if story_name_match: -# selected_story = story_name_match -# match_info = { -# 'method': 'smart_fallback_fuzzy', -# 'language': 'english', -# 'title': os.path.splitext(os.path.basename(selected_story))[0], -# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' -# } -# conn.logger.bind(tag=TAG).info(f"Smart fallback story match (LLM misclassified): {selected_story}") - -# # Final fallback to random selection -# if not selected_story and STORY_CACHE["all_story_files"]: -# selected_story = random.choice(STORY_CACHE["all_story_files"]) -# match_info = { -# 'method': 'random_fallback', -# 'language': 'english', -# 'title': os.path.splitext(os.path.basename(selected_story))[0], -# 'category': selected_story.split(os.sep)[0] if os.sep in selected_story else 'unknown' -# } -# conn.logger.bind(tag=TAG).info(f"Random story fallback: {selected_story}") - -# # Play the selected story -# if selected_story: -# await play_multilingual_story(conn, selected_story, match_info, user_request) -# else: -# conn.logger.bind(tag=TAG).error("No stories found to play") -# await send_stt_message(conn, "Sorry, I couldn't find any stories to play.") - -# async def play_multilingual_story(conn, selected_story: str, match_info: dict, original_request: str): -# """Play selected story with contextual introduction - CDN STREAMING VERSION""" -# global STORY_CACHE - -# try: -# # Extract category and filename from selected_story path -# # selected_story format: "Fantasy/story.mp3" or "Adventure/story.mp3" -# path_parts = selected_story.split('/') -# if len(path_parts) >= 2: -# category = path_parts[0] -# filename = path_parts[1] -# else: -# # Fallback: try to get from match_info -# category = match_info.get('category', 'Fantasy') -# filename = os.path.basename(selected_story) - -# # Generate CDN streaming URL -# cdn_url = generate_cdn_story_url(category, filename) - -# if not cdn_url: -# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") -# await send_stt_message(conn, "Sorry, I couldn't access the story file.") -# return - -# # CRITICAL CHANGE: Download from CDN to local file first -# local_file_path = await download_cdn_file(cdn_url, conn) -# if not local_file_path: -# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") -# await send_stt_message(conn, "Sorry, I couldn't download the story file.") -# return - -# # Generate contextual introduction based on match info -# intro_text = generate_multilingual_story_intro(match_info, original_request) - -# await send_stt_message(conn, intro_text) -# conn.dialogue.put(Message(role="assistant", content=intro_text)) - -# # Queue TTS messages with S3 URL -# if conn.intent_type == "intent_llm": -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.FIRST, -# content_type=ContentType.ACTION, -# ) -# ) - -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.TEXT, -# content_detail=intro_text, -# ) -# ) - -# # Use CDN URL instead of local file path -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.FILE, -# content_file=local_file_path, # LOCAL FILE, NOT CDN URL! -# ) -# ) - -# if conn.intent_type == "intent_llm": -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.LAST, -# content_type=ContentType.ACTION, -# ) -# ) - -# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes -# conn.llm_finish_task = True - -# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") - -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") -# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") - -# def generate_multilingual_story_intro(match_info: dict, original_request: str) -> str: -# """Generate contextual introduction based on matching method and info""" -# method = match_info.get('method', 'unknown') -# language = match_info.get('language', 'english') -# title = match_info.get('title', 'Unknown Story') -# category = match_info.get('category', 'story') -# original_title = match_info.get('original_title', title) - -# # Clean up the title (remove underscores, etc.) -# clean_title = title.replace("_", " ").replace("-", " ") - -# if method == 'ai_multilingual': -# if language != 'english': -# intros = [ -# f"Perfect! I found '{clean_title}' for you!", -# f"Great choice! Here's the story '{clean_title}'!", -# f"I found exactly what you wanted: '{clean_title}'!", -# f"Let me tell you '{clean_title}' - this should be perfect!" -# ] -# else: -# intros = [ -# f"I found '{clean_title}' which matches your request perfectly!", -# f"Here's '{clean_title}' - I think you'll love this story!", -# f"Playing '{clean_title}' based on your request!" -# ] -# elif method == 'language_random': -# intros = [ -# f"Here's a wonderful story for you: '{clean_title}'!", -# f"Let me tell you '{clean_title}' - a beautiful story!", -# f"I picked '{clean_title}' from our collection!" -# ] -# elif method == 'category_selection': -# if category != 'unknown': -# intros = [ -# f"Here's a lovely {category.lower()} story: '{clean_title}'!", -# f"Perfect! I have a {category.lower()} story for you: '{clean_title}'!", -# f"Let me tell you this {category.lower()} story called '{clean_title}'!" -# ] -# else: -# intros = [ -# f"Here's a wonderful story: '{clean_title}'!", -# f"Let me tell you '{clean_title}'!", -# f"I have a great story for you: '{clean_title}'!" -# ] -# elif method == 'legacy_fuzzy': -# intros = [ -# f"I think you'll love '{clean_title}'!", -# f"Here's '{clean_title}' - hope this is what you wanted!", -# f"Let me tell you the story of '{clean_title}'!" -# ] -# else: # random_fallback -# intros = [ -# f"Let me tell you a wonderful story: '{clean_title}'!", -# f"Here's a great story for you: '{clean_title}'!", -# f"I have a special story called '{clean_title}'!" -# ] - -# return random.choice(intros) - - -# def find_best_story_match(story_name, story_files): -# """Find the best matching story from available files with enhanced matching""" -# best_match = None -# highest_score = 0 - -# # Clean and normalize the input story name -# clean_story_name = story_name.lower().strip() -# # Remove common story words that don't help with matching -# story_words_to_remove = ['story', 'tale', 'a', 'the', 'play', 'tell', 'me'] -# story_name_words = [word for word in clean_story_name.split() if word not in story_words_to_remove] - -# for story_file in story_files: -# # Extract just the filename without path and extension -# file_name = os.path.splitext(os.path.basename(story_file))[0].lower() -# file_name_words = file_name.split() - -# # Method 1: Direct sequence matching (existing approach) -# sequence_ratio = difflib.SequenceMatcher(None, clean_story_name, file_name).ratio() - -# # Method 2: Word-based matching - check how many words match -# word_match_score = 0 -# if story_name_words: -# matching_words = 0 -# for word in story_name_words: -# if any(word in file_word for file_word in file_name_words): -# matching_words += 1 -# word_match_score = matching_words / len(story_name_words) - -# # Method 3: Partial string matching - check if story name is contained in filename -# containment_score = 0 -# if clean_story_name in file_name or file_name in clean_story_name: -# containment_score = 0.8 - -# # Combine scores with weights -# combined_score = (sequence_ratio * 0.4) + (word_match_score * 0.4) + (containment_score * 0.2) - -# # Lower threshold but use combined scoring for better matches -# if combined_score > highest_score and combined_score > 0.3: -# highest_score = combined_score -# best_match = story_file - -# return best_match - - -# async def handle_story_command(conn, category, specific_story=None, requested_language=None): -# """Handle story playback command""" -# initialize_story_handler(conn) -# global STORY_CACHE - -# conn.logger.bind(tag=TAG).debug(f"Handling story command - Category: {category}, Story: {specific_story}, Language: {requested_language}") - -# # Check if stories directory exists -# if not os.path.exists(STORY_CACHE["story_dir"]): -# conn.logger.bind(tag=TAG).error(f"Story directory does not exist: {STORY_CACHE['story_dir']}") -# await send_stt_message(conn, "Sorry, I couldn't find the story collection.") -# return - -# # Refresh cache if needed -# if time.time() - STORY_CACHE["scan_time"] > STORY_CACHE["refresh_time"]: -# STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( -# STORY_CACHE["story_dir"], STORY_CACHE["story_ext"] -# ) -# STORY_CACHE["scan_time"] = time.time() - -# selected_story = None - -# # If specific story name is provided, try to find it -# if specific_story: -# selected_story = find_best_story_match(specific_story, STORY_CACHE["all_story_files"]) -# if selected_story: -# conn.logger.bind(tag=TAG).info(f"Found matching story: {selected_story}") - -# # If no specific story found, select based on category -# if not selected_story: -# if category and category.lower() != "random": -# # Normalize category name -# normalized_category = normalize_category_name(category) - -# # Try to find the category -# matching_category = None -# for cat_name in STORY_CACHE["story_files_by_category"].keys(): -# if cat_name.lower() == normalized_category.lower(): -# matching_category = cat_name -# break - -# if matching_category and STORY_CACHE["story_files_by_category"][matching_category]: -# selected_story = random.choice(STORY_CACHE["story_files_by_category"][matching_category]) -# conn.logger.bind(tag=TAG).info(f"Selected {matching_category} story: {selected_story}") -# else: -# conn.logger.bind(tag=TAG).warning(f"Category '{category}' not found or empty, selecting random story") -# if STORY_CACHE["all_story_files"]: -# selected_story = random.choice(STORY_CACHE["all_story_files"]) -# else: -# # Select random story from all available -# if STORY_CACHE["all_story_files"]: -# selected_story = random.choice(STORY_CACHE["all_story_files"]) -# conn.logger.bind(tag=TAG).info(f"Selected random story: {selected_story}") - -# if selected_story: -# await play_story_file(conn, selected_story, requested_language) -# else: -# conn.logger.bind(tag=TAG).error("No stories found in the collection") -# await send_stt_message(conn, "I'm sorry, I couldn't find any stories to play.") - - -# def get_story_intro(story_file, requested_language=None): -# """Generate an introduction for the story""" -# # Extract story name and category -# parts = story_file.split(os.sep) -# if len(parts) > 1: -# category = parts[0] -# story_name = os.path.splitext(parts[-1])[0] -# else: -# category = "story" -# story_name = os.path.splitext(story_file)[0] - -# # Clean up the story name (remove underscores, etc.) -# story_name = story_name.replace("_", " ").replace("-", " ") - -# # Always use English intros since stories are in English -# intros = [ -# f"Let me tell you a wonderful {category.lower()} story called '{story_name}'", -# f"Here's a {category.lower()} story for you: '{story_name}'", -# f"Get comfortable and enjoy this {category.lower()} story: '{story_name}'", -# f"I have a special {category.lower()} story for you called '{story_name}'", -# f"Listen carefully to this amazing story: '{story_name}'", -# f" Let's begin '{story_name}'", -# ] - -# intro = random.choice(intros) - -# # Add note if requested in another language -# if requested_language and requested_language != "english": -# intro = f"Playing English story. {intro}" - -# return intro - - -# async def play_story_file(conn, story_file, requested_language=None): -# """Play the selected story file - CDN STREAMING VERSION""" -# try: -# # Extract category and filename from story_file path -# path_parts = story_file.split('/') -# if len(path_parts) >= 2: -# category = path_parts[0] -# filename = path_parts[1] -# else: -# # Fallback -# category = "Fantasy" -# filename = os.path.basename(story_file) - -# # Generate CDN streaming URL -# cdn_url = generate_cdn_story_url(category, filename) - -# if not cdn_url: -# conn.logger.bind(tag=TAG).error(f"Failed to generate CDN URL for: {category}/{filename}") -# await send_stt_message(conn, "Sorry, I couldn't access the story file.") -# return - -# # CRITICAL CHANGE: Download from CDN to local file first -# local_file_path = await download_cdn_file(cdn_url, conn) -# if not local_file_path: -# conn.logger.bind(tag=TAG).error(f"Failed to download CDN file: {cdn_url}") -# await send_stt_message(conn, "Sorry, I couldn't download the story file.") -# return - -# # Generate and send introduction (always in English) -# intro_text = get_story_intro(story_file, requested_language) -# await send_stt_message(conn, intro_text) -# conn.dialogue.put(Message(role="assistant", content=intro_text)) - -# # Send TTS messages to play the story from CDN -# if conn.intent_type == "intent_llm": -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.FIRST, -# content_type=ContentType.ACTION, -# ) -# ) - -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.TEXT, -# content_detail=intro_text, -# ) -# ) - -# # Use CDN URL instead of local file path -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.MIDDLE, -# content_type=ContentType.FILE, -# content_file=local_file_path, # LOCAL FILE, NOT CDN URL! -# ) -# ) - -# if conn.intent_type == "intent_llm": -# conn.tts.tts_text_queue.put( -# TTSMessageDTO( -# sentence_id=conn.sentence_id, -# sentence_type=SentenceType.LAST, -# content_type=ContentType.ACTION, -# ) -# ) - -# # CRITICAL FIX: Set llm_finish_task to True so stop signal is sent after story completes -# conn.llm_finish_task = True - -# conn.logger.bind(tag=TAG).info(f"Streaming story from local cache: {local_file_path}") - -# except Exception as e: -# conn.logger.bind(tag=TAG).error(f"Failed to stream story from CDN: {str(e)}") -# conn.logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}") - - - import os import re import time diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index 9bd44f5a0..fce94d4c7 100755 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -43,4 +43,6 @@ amazon_transcribe # Semantic search dependencies qdrant-client>=1.7.0 sentence-transformers>=2.2.0 -pyspellchecker>=0.7.0 \ No newline at end of file +pyspellchecker>=0.7.0 +# Google Cloud Speech v2 dependencies +google-cloud-speech>=2.26.0 \ No newline at end of file diff --git a/main/xiaozhi-server/test_google_speech_v2.py b/main/xiaozhi-server/test_google_speech_v2.py new file mode 100644 index 000000000..0732035c2 --- /dev/null +++ b/main/xiaozhi-server/test_google_speech_v2.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +""" +Test script for Google Cloud Speech-to-Text v2 ASR Provider +This script validates the provider implementation without requiring actual credentials +""" + +import sys +import os +import asyncio +from unittest.mock import Mock, patch, MagicMock + +# Add the project root to Python path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +# Mock the Google Cloud Speech v2 imports before importing our provider +sys.modules['google.cloud.speech_v2'] = Mock() +sys.modules['google.api_core.exceptions'] = Mock() + +from core.providers.asr.google_speech_v2 import ASRProvider + +def test_provider_initialization(): + """Test that the provider initializes correctly with valid configuration""" + config = { + "project_id": "test-project-123", + "location": "global", + "credentials_path": "/path/to/credentials.json", + "model": "chirp_2", + "language_codes": ["en-US"], + "sample_rate_hertz": 16000, + "encoding": "LINEAR16", + "enable_automatic_punctuation": True, + "enable_word_time_offsets": False, + "enable_word_confidence": False, + "output_dir": "./tmp/" + } + + print("Testing provider initialization...") + + # Mock the Google Cloud client + with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client: + mock_instance = Mock() + mock_client.return_value = mock_instance + + try: + provider = ASRProvider(config, delete_audio_file=True) + print("[PASS] Provider initialized successfully") + + # Verify configuration + assert provider.project_id == "test-project-123" + assert provider.model == "chirp_2" + assert provider.language_codes == ["en-US"] + assert provider.sample_rate_hertz == 16000 + print("[PASS] Configuration validated") + + # Verify recognizer name format + expected_recognizer = f"projects/{config['project_id']}/locations/{config['location']}/recognizers/_" + assert provider.recognizer_name == expected_recognizer + print("[PASS] Recognizer name format correct") + + except Exception as e: + print(f"[FAIL] Provider initialization failed: {e}") + return False + + return True + +def test_audio_encoding_mapping(): + """Test the audio encoding mapping function""" + config = { + "project_id": "test-project", + "encoding": "LINEAR16" + } + + print("Testing audio encoding mapping...") + + with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'): + provider = ASRProvider(config, delete_audio_file=True) + + # Test various encoding mappings + test_cases = [ + ("LINEAR16", "LINEAR16"), + ("FLAC", "FLAC"), + ("MP3", "MP3"), + ("OGG_OPUS", "OGG_OPUS"), + ] + + for input_encoding, expected in test_cases: + provider.encoding = input_encoding + result = provider._get_audio_encoding() + print(f"[PASS] {input_encoding} -> {result}") + + return True + +async def test_speech_to_text_mock(): + """Test the speech_to_text method with mocked Google Cloud API response""" + config = { + "project_id": "test-project", + "location": "global", + "model": "chirp_2", + "language_codes": ["en-US"], + "sample_rate_hertz": 16000, + "encoding": "LINEAR16", + "output_dir": "./tmp/" + } + + print("Testing speech_to_text method...") + + # Create mock audio data (simulating Opus packets) + mock_opus_data = [b"fake_opus_packet_1", b"fake_opus_packet_2"] + + # Mock the Google Cloud response + mock_alternative = Mock() + mock_alternative.transcript = "Hello, this is a test transcript" + mock_alternative.confidence = 0.95 + + mock_result = Mock() + mock_result.alternatives = [mock_alternative] + + mock_channel = Mock() + mock_channel.alternatives = [mock_alternative] + + mock_response = Mock() + mock_response.results = [mock_result] + + with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient') as mock_client_class: + mock_client = Mock() + mock_client_class.return_value = mock_client + mock_client.recognize.return_value = mock_response + + # Mock other dependencies + with patch('core.providers.asr.google_speech_v2.ASRProviderBase.decode_opus') as mock_decode, \ + patch('core.providers.asr.google_speech_v2.ASRProviderBase.save_audio_to_file') as mock_save, \ + patch('core.providers.asr.google_speech_v2.ASRProviderBase.log_audio_transcript') as mock_log, \ + patch('os.makedirs'): + + # Configure mocks + mock_decode.return_value = [b"pcm_data_1", b"pcm_data_2"] + mock_save.return_value = "/tmp/test_audio.wav" + + provider = ASRProvider(config, delete_audio_file=False) + + # Test the speech_to_text method + try: + result_text, file_path = await provider.speech_to_text( + mock_opus_data, + session_id="test_session_123", + audio_format="opus" + ) + + print(f"[PASS] Speech-to-text completed") + print(f" Result: '{result_text}'") + print(f" File path: {file_path}") + + # Verify the result + assert result_text == "Hello, this is a test transcript" + assert file_path == "/tmp/test_audio.wav" + + # Verify Google Cloud API was called correctly + mock_client.recognize.assert_called_once() + print("[PASS] Google Cloud API called with correct parameters") + + except Exception as e: + print(f"[FAIL] Speech-to-text test failed: {e}") + import traceback + traceback.print_exc() + return False + + return True + +def test_configuration_validation(): + """Test configuration validation and edge cases""" + print("Testing configuration validation...") + + # Test minimal configuration + minimal_config = { + "project_id": "test-project" + } + + with patch('core.providers.asr.google_speech_v2.speech_v2.SpeechClient'), \ + patch('os.makedirs'): + provider = ASRProvider(minimal_config, delete_audio_file=True) + + # Verify defaults + assert provider.location == "global" + assert provider.model == "chirp_2" + assert provider.language_codes == ["en-US"] + assert provider.sample_rate_hertz == 16000 + assert provider.encoding == "LINEAR16" + + print("[PASS] Default values applied correctly") + + return True + +def main(): + """Run all tests""" + print("Testing Google Cloud Speech-to-Text v2 ASR Provider") + print("=" * 60) + + tests = [ + ("Provider Initialization", test_provider_initialization), + ("Audio Encoding Mapping", test_audio_encoding_mapping), + ("Configuration Validation", test_configuration_validation), + ("Speech-to-Text (Mocked)", lambda: asyncio.run(test_speech_to_text_mock())), + ] + + passed = 0 + total = len(tests) + + for test_name, test_func in tests: + print(f"\nRunning: {test_name}") + try: + if test_func(): + print(f"[PASS] {test_name}: PASSED") + passed += 1 + else: + print(f"[FAIL] {test_name}: FAILED") + except Exception as e: + print(f"[ERROR] {test_name}: ERROR - {e}") + + print("\n" + "=" * 60) + print(f"Test Results: {passed}/{total} tests passed") + + if passed == total: + print("All tests passed! Google Speech v2 provider is ready to use.") + print("\nNext steps:") + print("1. Install dependencies: pip install google-cloud-speech>=2.26.0") + print("2. Set up Google Cloud credentials") + print("3. Update selected_module.ASR in config.yaml to: GoogleSpeechV2") + print("4. Configure your Google Cloud project settings") + else: + print("Some tests failed. Please check the implementation.") + sys.exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file