From 0bba2992c9b8eb0fe13fd09f6946ea05cbcc3de9 Mon Sep 17 00:00:00 2001 From: Jordan Date: Thu, 8 Oct 2026 12:58:27 -0300 Subject: [PATCH] feat(voiceprint): integrate voice registration via Java API and centralize configs in .env - Update register_voiceprint to fetch audio from API history and send audioId - Add filter to ignore identity questions (e.g., 'who am I') - Handle already-registered voice response (code 10080) with Action.RESPONSE - Centralize environment variables in .env, settings.py, and docker-compose.yml --- main/xiaozhi-server/config/settings.py | 17 ++- .../tools/server_plugins/plugin_executor.py | 2 +- .../functions/register_voiceprint.py | 116 ++++++++++++++---- 3 files changed, 102 insertions(+), 33 deletions(-) diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py index cfca89b61..4495af670 100644 --- a/main/xiaozhi-server/config/settings.py +++ b/main/xiaozhi-server/config/settings.py @@ -1,20 +1,25 @@ import os import asyncio +from dotenv import load_dotenv from config.config_loader import read_config, get_project_dir, load_config +# Carrega as variáveis do arquivo .env para o ambiente Python +load_dotenv() +XIAOZHI_BASE_URL = os.getenv("XIAOZHI_BASE_URL", "http://host.docker.internal:8002/xiaozhi") +XIAOZHI_USER_TOKEN = os.getenv("XIAOZHI_USER_TOKEN", "") +DEFAULT_AGENT_ID = os.getenv("DEFAULT_AGENT_ID", "a69fbf960e9840f09a2ba12dd3ff4c15") default_config_file = "config.yaml" config_file_valid = False - def check_config_file(): global config_file_valid if config_file_valid: return - """ - 简化的配置检查,仅提示用户配置文件的使用情况 - """ - custom_config_file = get_project_dir() + "data/." + default_config_file + + # os.path.join garante a montagem correta de caminhos no Linux/Docker + custom_config_file = os.path.join(get_project_dir(), "data", f".{default_config_file}") + if not os.path.exists(custom_config_file): raise FileNotFoundError( "找不到data/.config.yaml文件,请按教程确认该配置文件是否存在" @@ -31,4 +36,4 @@ def check_config_file(): error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n" error_msg += "2、按教程配置好接口地址和密钥\n" raise ValueError(error_msg) - config_file_valid = True + config_file_valid = True \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index afe89c18d..69c9fa0d4 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -96,7 +96,7 @@ class ServerPluginExecutor(ToolExecutor): tools = {} # 获取必要的函数 - necessary_functions = ["handle_exit_intent", "get_lunar"] + necessary_functions = ["handle_exit_intent", "get_lunar", "register_voiceprint"] # 获取配置中的函数 config_functions = self.config["Intent"][ diff --git a/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py b/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py index 7050189fa..c51394287 100644 --- a/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py +++ b/main/xiaozhi-server/plugins_func/functions/register_voiceprint.py @@ -1,9 +1,10 @@ from typing import TYPE_CHECKING, Optional import requests -import glob -import os +import logging +import traceback from plugins_func.register import register_function, ToolType, ActionResponse, Action from config.logger import setup_logging +from config.settings import XIAOZHI_BASE_URL, XIAOZHI_USER_TOKEN, DEFAULT_AGENT_ID if TYPE_CHECKING: from core.connection import ConnectionHandler @@ -15,7 +16,7 @@ register_voiceprint_function_desc = { "type": "function", "function": { "name": "register_voiceprint", - "description": "Register the user's voiceprint for future identification", + "description": "ONLY call this function when the user explicitly commands to save or register their name (e.g., 'meu nome é X', 'salve meu nome como X'). DO NOT call this if the user asks 'who am I' or asks a question.", "parameters": { "type": "object", "properties": { @@ -35,47 +36,110 @@ register_voiceprint_function_desc = { ) def register_voiceprint(conn: "ConnectionHandler", speaker_id: Optional[str] = None): try: - audio_path = getattr(conn, "last_audio_file", None) + # Configuração do Agent ID e Token de Autenticação ainda hardcoded + # TODO: Implementar a obtenção dinâmica do token de autenticação, aparentemente o agent_id não muda + + agent_id = DEFAULT_AGENT_ID + user_token = XIAOZHI_USER_TOKEN + base_url = XIAOZHI_BASE_URL - if not audio_path and hasattr(conn, "session_id"): - session_files = sorted(glob.glob(f"tmp/*{conn.session_id}*.wav"), key=os.path.getmtime) - if session_files: - audio_path = session_files[-1] + headers = {"Content-Type": "application/json"} + if user_token: + headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token - if not audio_path or not os.path.exists(audio_path): + # Consultar o histórico de áudios + history_url = f"{base_url}/agent/{agent_id}/chat-history/user" + logger.bind(tag=TAG).info(f"[Voiceprint] Buscando histórico em: {history_url}") + + history_res = requests.get(history_url, headers=headers, timeout=5) + logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do histórico ({history_res.status_code}): {history_res.text}") + + if history_res.status_code != 200: return ActionResponse( action=Action.NONE, - result="Audio file not found for voice registration", - response="I couldn't find the audio file to register your voice. Please make sure to record your voice first." + result=f"Erro na API de histórico: status {history_res.status_code}", + response="Não consegui obter o histórico recente para cadastrar sua voz." ) - with open(audio_path, 'rb') as f: - files = {'file': (os.path.basename(audio_path), f, 'audio/wav')} - payload = {'speaker_id': speaker_id} - - response = requests.post( - 'http://192.168.1.178:8005/voiceprint/register', - data=payload, - files=files, - timeout=5 - ) + history_data = history_res.json() + audio_list = history_data.get("data", []) - if response.status_code == 200: + if not audio_list: + logger.bind(tag=TAG).warning("[Voiceprint] A API retornou uma lista de áudios vazia (data: []).") return ActionResponse( action=Action.NONE, + result="Nenhum áudio encontrado no histórico do agente", + response="Não encontrei nenhum registro de voz recente no histórico." + ) + + # evita registrar a voz se o usuário apenas perguntou "quem sou eu" ou algo similar + user_text = audio_list[0].get("content", "").lower() + perguntas_identidade = ["quem sou", "me diga quem", "qual é o meu nome", "qual meu nome"] + + if any(p in user_text for p in perguntas_identidade): + logger.bind(tag=TAG).info(f"[Voiceprint] Interceptado: Usuário apenas perguntou a identidade ('{user_text}'). Cancelando registro.") + return ActionResponse( + action=Action.NONE, + result="Ignorado: O usuário apenas perguntou quem ele é.", + response=f"Eu sei quem você é! Você é o {speaker_id}." + ) + + # Áudio mais recente + latest_audio = audio_list[0] + audio_id = latest_audio.get("audioId") + + if not audio_id: + logger.bind(tag=TAG).error(f"[Voiceprint] Item do histórico sem audioId: {latest_audio}") + return ActionResponse( + action=Action.NONE, + result="audioId ausente no item mais recente", + response="Não foi possível identificar o código do seu último áudio." + ) + + logger.bind(tag=TAG).info(f"[Voiceprint] Áudio selecionado: audioId={audio_id}, texto='{latest_audio.get('content')}'") + + # Enviar requisição de salvamento do Voiceprint + register_url = f"{base_url}/agent/voice-print" + payload = { + "agentId": agent_id, + "audioId": audio_id, + "introduce": speaker_id, + "sourceName": speaker_id + } + + logger.bind(tag=TAG).info(f"[Voiceprint] Enviando cadastro: {payload}") + register_res = requests.post(register_url, json=payload, headers=headers, timeout=5) + logger.bind(tag=TAG).info(f"[Voiceprint] Resposta do cadastro ({register_res.status_code}): {register_res.text}") + + res_json = register_res.json() if register_res.status_code == 200 else {} + code = res_json.get("code") + + # Sucesso + if register_res.status_code == 200 and code == 0: + return ActionResponse( + action=Action.RESPONSE, result=f"Voiceprint de {speaker_id} registrado com sucesso", response=f"Pronto! Cadastrei a voz de {speaker_id} no sistema." ) + # Tratamento da voz já cadastrada + elif code == 10080: + logger.bind(tag=TAG).info(f"[Voiceprint] Voz já cadastrada anteriormente como {speaker_id}.") + return ActionResponse( + action=Action.RESPONSE, + result=f"Voz já cadastrada para {speaker_id}", + response=f"Sua voz já está cadastrada no sistema como {speaker_id}." + ) + # Outros erros else: - logger.bind(tag=TAG).error(f"Erro API Voiceprint: {response.status_code} - {response.text}") return ActionResponse( action=Action.NONE, - result=f"Erro status {response.status_code}", - response="Ocorreu um erro no servidor de voz ao tentar salvar." + result=f"Falha no salvamento: {register_res.text}", + response="Ocorreu um erro no servidor ao tentar salvar sua voz." ) except Exception as e: - logger.bind(tag=TAG).error(f"Erro ao registrar a impressão de voz: {e}") + logger.bind(tag=TAG).error(f"[Voiceprint] Exceção: {e}") + logger.bind(tag=TAG).error(traceback.format_exc()) return ActionResponse( action=Action.NONE, result=f"Exceção: {e}",