mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
intent fix, news fix
This commit is contained in:
parent
4d14977f7d
commit
3b52a72bf4
4 changed files with 82 additions and 90 deletions
|
|
@ -19,9 +19,9 @@ import opuslib
|
|||
|
||||
# --- Configuration ---
|
||||
|
||||
SERVER_IP = "192.168.1.101" # !!! UPDATE with your server's local IP address !!!
|
||||
SERVER_IP = "192.168.1.2" # !!! UPDATE with your server's local IP address !!!
|
||||
OTA_PORT = 8003
|
||||
MQTT_BROKER_HOST = "192.168.1.101" # MQTT gateway IP
|
||||
MQTT_BROKER_HOST = "192.168.1.2" # MQTT gateway IP
|
||||
|
||||
|
||||
MQTT_BROKER_PORT = 1883
|
||||
|
|
|
|||
|
|
@ -69,9 +69,11 @@ GET_INDIAN_NEWS_API_FUNCTION_DESC = {
|
|||
"function": {
|
||||
"name": "get_indian_news_api",
|
||||
"description": (
|
||||
"Get latest Indian news from reliable sources including business, technology, politics, and general news. "
|
||||
"Provides current news from major Indian publications and government sources. "
|
||||
"Can specify category like business, technology, politics, or get general news."
|
||||
"Get latest Indian news from reliable sources - THIS IS THE PRIMARY NEWS FUNCTION. "
|
||||
"Use this for ALL general news requests unless user specifically asks for international news. "
|
||||
"Provides current news from major Indian publications and government sources including business, technology, politics, and general news. "
|
||||
"Can specify category like business, technology, politics, science, education, or get general news. "
|
||||
"This should be the DEFAULT choice for news requests."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ CHANNEL_MAP = {
|
|||
}
|
||||
|
||||
# Default news sources dictionary, used when not specified in config
|
||||
DEFAULT_NEWS_SOURCES = "Pengpai News;Baidu Hot Search;CLS"
|
||||
DEFAULT_NEWS_SOURCES = "Wall Street Journal;Hacker News;BBC News"
|
||||
|
||||
|
||||
def get_news_sources_from_config(conn):
|
||||
|
|
@ -92,10 +92,10 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = {
|
|||
"function": {
|
||||
"name": "get_news_from_newsnow",
|
||||
"description": (
|
||||
"Get latest news, randomly select one news item for broadcast. "
|
||||
f"Users can choose different news sources, standard names are: {example_sources_str}"
|
||||
"For example, if user requests Baidu news, it's actually Baidu Hot Search. If not specified, defaults to Pengpai News. "
|
||||
"Users can request detailed content, which will fetch detailed news content."
|
||||
"Get latest INTERNATIONAL news from global sources (NOT for Indian news - use get_indian_news_api for Indian news). "
|
||||
f"Users can choose different international news sources, standard names are: {example_sources_str}"
|
||||
"For example, if user requests Baidu news, it's actually Baidu Hot Search. If not specified, defaults to Wall Street Journal. "
|
||||
"Users can request detailed content, which will fetch detailed news content. Use this ONLY for international/global news, NOT for Indian news."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
|
|
@ -110,7 +110,7 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = {
|
|||
},
|
||||
"lang": {
|
||||
"type": "string",
|
||||
"description": "Language code for user response, e.g., zh_CN/zh_HK/en_US/ja_JP etc., defaults to zh_CN",
|
||||
"description": "Language code for user response, e.g., en_US/zh_CN/zh_HK/ja_JP etc., defaults to en_US",
|
||||
},
|
||||
},
|
||||
"required": ["lang"],
|
||||
|
|
@ -246,9 +246,9 @@ def get_news_from_newsnow(
|
|||
# If corresponding English ID not found, use default source
|
||||
if not english_source_id:
|
||||
logger.bind(tag=TAG).warning(
|
||||
f"Invalid news source: {source}, using default source Pengpai News")
|
||||
english_source_id = "thepaper"
|
||||
source = "Pengpai News"
|
||||
f"Invalid news source: {source}, using default source Wall Street Journal")
|
||||
english_source_id = "wallstreetcn-quick"
|
||||
source = "Wall Street Journal"
|
||||
|
||||
logger.bind(tag=TAG).info(
|
||||
f"Getting news: news source={source}({english_source_id})")
|
||||
|
|
|
|||
|
|
@ -1,13 +1,10 @@
|
|||
from config.logger import setup_logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import random
|
||||
import asyncio
|
||||
import difflib
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from core.utils import p3
|
||||
from core.handle.sendAudioHandle import send_stt_message
|
||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||
from core.utils.dialogue import Message
|
||||
|
|
@ -21,13 +18,13 @@ play_music_function_desc = {
|
|||
"type": "function",
|
||||
"function": {
|
||||
"name": "play_music",
|
||||
"description": "Method for singing, listening to songs, and playing music.",
|
||||
"description": "唱歌、听歌、播放音乐的方法。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"song_name": {
|
||||
"type": "string",
|
||||
"description": "Song name. If user doesn't specify a specific song name, it should be 'random'. When explicitly specified, return the music name. Example: ```User: play Two Tigers\nParameter: Two Tigers``` ```User: play music\nParameter: random```",
|
||||
"description": "歌曲名称,如果用户没有指定具体歌名则为'random', 明确指定的时返回音乐的名字 示例: ```用户:播放两只老虎\n参数:两只老虎``` ```用户:播放音乐 \n参数:random ```",
|
||||
}
|
||||
},
|
||||
"required": ["song_name"],
|
||||
|
|
@ -40,45 +37,44 @@ play_music_function_desc = {
|
|||
def play_music(conn, song_name: str):
|
||||
try:
|
||||
music_intent = (
|
||||
f"Play music {song_name}" if song_name != "random" else "Play random music"
|
||||
f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
|
||||
)
|
||||
|
||||
# Check event loop status
|
||||
# 检查事件循环状态
|
||||
if not conn.loop.is_running():
|
||||
conn.logger.bind(tag=TAG).error(
|
||||
"Event loop is not running, cannot submit task")
|
||||
conn.logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
|
||||
return ActionResponse(
|
||||
action=Action.RESPONSE, result="System busy", response="Please try again later"
|
||||
action=Action.RESPONSE, result="系统繁忙", response="请稍后再试"
|
||||
)
|
||||
|
||||
# Submit async task
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
handle_music_command(conn, music_intent), conn.loop
|
||||
# 提交异步任务
|
||||
task = conn.loop.create_task(
|
||||
handle_music_command(conn, music_intent) # 封装异步逻辑
|
||||
)
|
||||
|
||||
# Non-blocking callback handling
|
||||
# 非阻塞回调处理
|
||||
def handle_done(f):
|
||||
try:
|
||||
f.result() # Can handle success logic here
|
||||
conn.logger.bind(tag=TAG).info("Playback completed")
|
||||
f.result() # 可在此处理成功逻辑
|
||||
conn.logger.bind(tag=TAG).info("播放完成")
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Playback failed: {e}")
|
||||
conn.logger.bind(tag=TAG).error(f"播放失败: {e}")
|
||||
|
||||
future.add_done_callback(handle_done)
|
||||
task.add_done_callback(handle_done)
|
||||
|
||||
return ActionResponse(
|
||||
action=Action.NONE, result="Command received", response="Playing music for you"
|
||||
action=Action.NONE, result="指令已接收", response="正在为您播放音乐"
|
||||
)
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Error processing music intent: {e}")
|
||||
conn.logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
|
||||
return ActionResponse(
|
||||
action=Action.RESPONSE, result=str(e), response="Error occurred while playing music"
|
||||
action=Action.RESPONSE, result=str(e), response="播放音乐时出错了"
|
||||
)
|
||||
|
||||
|
||||
def _extract_song_name(text):
|
||||
"""Extract song name from user input"""
|
||||
for keyword in ["Play music"]:
|
||||
"""从用户输入中提取歌名"""
|
||||
for keyword in ["播放音乐"]:
|
||||
if keyword in text:
|
||||
parts = text.split(keyword)
|
||||
if len(parts) > 1:
|
||||
|
|
@ -87,14 +83,13 @@ def _extract_song_name(text):
|
|||
|
||||
|
||||
def _find_best_match(potential_song, music_files):
|
||||
"""Find the best matching song"""
|
||||
"""查找最匹配的歌曲"""
|
||||
best_match = None
|
||||
highest_ratio = 0
|
||||
|
||||
for music_file in music_files:
|
||||
song_name = os.path.splitext(music_file)[0]
|
||||
ratio = difflib.SequenceMatcher(
|
||||
None, potential_song, song_name).ratio()
|
||||
ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio()
|
||||
if ratio > highest_ratio and ratio > 0.4:
|
||||
highest_ratio = ratio
|
||||
best_match = music_file
|
||||
|
|
@ -106,13 +101,13 @@ def get_music_files(music_dir, music_ext):
|
|||
music_files = []
|
||||
music_file_names = []
|
||||
for file in music_dir.rglob("*"):
|
||||
# Check if it's a file
|
||||
# 判断是否是文件
|
||||
if file.is_file():
|
||||
# Get file extension
|
||||
# 获取文件扩展名
|
||||
ext = file.suffix.lower()
|
||||
# Check if extension is in the list
|
||||
# 判断扩展名是否在列表中
|
||||
if ext in music_ext:
|
||||
# Add relative path
|
||||
# 添加相对路径
|
||||
music_files.append(str(file.relative_to(music_dir)))
|
||||
music_file_names.append(
|
||||
os.path.splitext(str(file.relative_to(music_dir)))[0]
|
||||
|
|
@ -126,8 +121,7 @@ def initialize_music_handler(conn):
|
|||
if "play_music" in conn.config["plugins"]:
|
||||
MUSIC_CACHE["music_config"] = conn.config["plugins"]["play_music"]
|
||||
MUSIC_CACHE["music_dir"] = os.path.abspath(
|
||||
MUSIC_CACHE["music_config"].get(
|
||||
"music_dir", "./music") # Default path modified
|
||||
MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改
|
||||
)
|
||||
MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get(
|
||||
"music_ext", (".mp3", ".wav", ".p3")
|
||||
|
|
@ -139,7 +133,7 @@ def initialize_music_handler(conn):
|
|||
MUSIC_CACHE["music_dir"] = os.path.abspath("./music")
|
||||
MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3")
|
||||
MUSIC_CACHE["refresh_time"] = 60
|
||||
# Get music file list
|
||||
# 获取音乐文件列表
|
||||
MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(
|
||||
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"]
|
||||
)
|
||||
|
|
@ -151,88 +145,84 @@ async def handle_music_command(conn, text):
|
|||
initialize_music_handler(conn)
|
||||
global MUSIC_CACHE
|
||||
|
||||
"""Handle music playback commands"""
|
||||
"""处理音乐播放指令"""
|
||||
clean_text = re.sub(r"[^\w\s]", "", text).strip()
|
||||
conn.logger.bind(tag=TAG).debug(
|
||||
f"Check if it's a music command: {clean_text}")
|
||||
conn.logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
|
||||
|
||||
# Try to match specific song name
|
||||
# 尝试匹配具体歌名
|
||||
if os.path.exists(MUSIC_CACHE["music_dir"]):
|
||||
if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]:
|
||||
# Refresh music file list
|
||||
# 刷新音乐文件列表
|
||||
MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = (
|
||||
get_music_files(
|
||||
MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"])
|
||||
get_music_files(MUSIC_CACHE["music_dir"], MUSIC_CACHE["music_ext"])
|
||||
)
|
||||
MUSIC_CACHE["scan_time"] = time.time()
|
||||
|
||||
potential_song = _extract_song_name(clean_text)
|
||||
if potential_song:
|
||||
best_match = _find_best_match(
|
||||
potential_song, MUSIC_CACHE["music_files"])
|
||||
best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
|
||||
if best_match:
|
||||
conn.logger.bind(tag=TAG).info(
|
||||
f"Found best matching song: {best_match}")
|
||||
conn.logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
|
||||
await play_local_music(conn, specific_file=best_match)
|
||||
return True
|
||||
# Check if it's a general play music command
|
||||
# 检查是否是通用播放音乐命令
|
||||
await play_local_music(conn)
|
||||
return True
|
||||
|
||||
|
||||
def _get_random_play_prompt(song_name):
|
||||
"""Generate random play prompt"""
|
||||
# Remove file extension
|
||||
"""生成随机播放引导语"""
|
||||
# 移除文件扩展名
|
||||
clean_name = os.path.splitext(song_name)[0]
|
||||
prompts = [
|
||||
f"Now playing for you, {clean_name}",
|
||||
f"Please enjoy the song, {clean_name}",
|
||||
f"About to play for you, {clean_name}",
|
||||
f"Bringing you, {clean_name}",
|
||||
f"Let's listen to, {clean_name}",
|
||||
f"Next, please enjoy, {clean_name}",
|
||||
f"Presenting to you, {clean_name}",
|
||||
f"Now playing for you, '{clean_name}'",
|
||||
f"Please enjoy the song, '{clean_name}'",
|
||||
f"About to play for you, '{clean_name}'",
|
||||
f"Now bringing you, '{clean_name}'",
|
||||
f"Let's listen together to, '{clean_name}'",
|
||||
f"Next, please enjoy, '{clean_name}'",
|
||||
f"At this moment, presenting to you, '{clean_name}'",
|
||||
]
|
||||
# Use random.choice directly, don't set seed
|
||||
# 直接使用random.choice,不设置seed
|
||||
return random.choice(prompts)
|
||||
|
||||
|
||||
async def play_local_music(conn, specific_file=None):
|
||||
global MUSIC_CACHE
|
||||
"""Play local music files"""
|
||||
"""播放本地音乐文件"""
|
||||
try:
|
||||
if not os.path.exists(MUSIC_CACHE["music_dir"]):
|
||||
conn.logger.bind(tag=TAG).error(
|
||||
f"Music directory does not exist: " + MUSIC_CACHE["music_dir"]
|
||||
f"音乐目录不存在: " + MUSIC_CACHE["music_dir"]
|
||||
)
|
||||
return
|
||||
|
||||
# Ensure path correctness
|
||||
# 确保路径正确性
|
||||
if specific_file:
|
||||
selected_music = specific_file
|
||||
music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
|
||||
else:
|
||||
if not MUSIC_CACHE["music_files"]:
|
||||
conn.logger.bind(tag=TAG).error("No MP3 music files found")
|
||||
conn.logger.bind(tag=TAG).error("未找到MP3音乐文件")
|
||||
return
|
||||
selected_music = random.choice(MUSIC_CACHE["music_files"])
|
||||
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
|
||||
|
||||
if not os.path.exists(music_path):
|
||||
conn.logger.bind(tag=TAG).error(
|
||||
f"Selected music file does not exist: {music_path}")
|
||||
conn.logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
|
||||
return
|
||||
text = _get_random_play_prompt(selected_music)
|
||||
await send_stt_message(conn, text)
|
||||
conn.dialogue.put(Message(role="assistant", content=text))
|
||||
|
||||
conn.tts.tts_text_queue.put(
|
||||
TTSMessageDTO(
|
||||
sentence_id=conn.sentence_id,
|
||||
sentence_type=SentenceType.FIRST,
|
||||
content_type=ContentType.ACTION,
|
||||
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,
|
||||
|
|
@ -249,15 +239,15 @@ async def play_local_music(conn, specific_file=None):
|
|||
content_file=music_path,
|
||||
)
|
||||
)
|
||||
conn.tts.tts_text_queue.put(
|
||||
TTSMessageDTO(
|
||||
sentence_id=conn.sentence_id,
|
||||
sentence_type=SentenceType.LAST,
|
||||
content_type=ContentType.ACTION,
|
||||
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,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
conn.logger.bind(tag=TAG).error(f"Failed to play music: {str(e)}")
|
||||
conn.logger.bind(tag=TAG).error(
|
||||
f"Detailed error: {traceback.format_exc()}")
|
||||
conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
|
||||
conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
|
||||
Loading…
Reference in a new issue