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
This commit is contained in:
Jordan 2026-10-08 12:58:27 -03:00
parent c1a35de460
commit 0bba2992c9
3 changed files with 102 additions and 33 deletions

View file

@ -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文件,请按教程确认该配置文件是否存在"

View file

@ -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"][

View file

@ -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
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]
agent_id = DEFAULT_AGENT_ID
user_token = XIAOZHI_USER_TOKEN
base_url = XIAOZHI_BASE_URL
if not audio_path or not os.path.exists(audio_path):
headers = {"Content-Type": "application/json"}
if user_token:
headers["Authorization"] = f"Bearer {user_token}" if not user_token.startswith("Bearer ") else user_token
# 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}
history_data = history_res.json()
audio_list = history_data.get("data", [])
response = requests.post(
'http://192.168.1.178:8005/voiceprint/register',
data=payload,
files=files,
timeout=5
)
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}",