From f28d10fd2c34c97ee1c5d3a17172d74cf20768d4 Mon Sep 17 00:00:00 2001 From: ascii <1280527893@qq.com> Date: Sun, 9 Mar 2025 09:37:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20jellyfin&emby=20=E9=9F=B3=E4=B9=90?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=AF=B9=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/handle/jellyfinHandler.py | 169 +++++++++++++++++ main/xiaozhi-server/config.yaml | 7 + .../core/handle/jellyfinHandler.py | 170 ++++++++++++++++++ .../core/handle/searchHandler.py | 42 +++++ main/xiaozhi-server/core/handle/textHandle.py | 15 +- .../xiaozhi-server/core/providers/tts/base.py | 12 ++ main/xiaozhi-server/core/utils/util.py | 7 + main/xiaozhi-server/core/websocket_server.py | 9 +- 8 files changed, 428 insertions(+), 3 deletions(-) create mode 100644 core/handle/jellyfinHandler.py create mode 100644 main/xiaozhi-server/core/handle/jellyfinHandler.py create mode 100644 main/xiaozhi-server/core/handle/searchHandler.py diff --git a/core/handle/jellyfinHandler.py b/core/handle/jellyfinHandler.py new file mode 100644 index 000000000..2afec1fdf --- /dev/null +++ b/core/handle/jellyfinHandler.py @@ -0,0 +1,169 @@ +import json +from typing import Dict, List + +import requests + +from config.logger import setup_logging +import os +import random +import difflib +import re +import traceback +from pathlib import Path +import time +from core.handle.sendAudioHandle import send_stt_message +from core.utils import p3 +from core.utils.util import seconds_to_time + +TAG = __name__ +logger = setup_logging() + + +def _extract_song_name(text): + """从用户输入中提取歌名,可以使用llm中提取""" + logger.bind(tag=TAG).debug(f"从用户输入中提取歌名: {text}") + for keyword in ["听", "播放", "放", "唱"]: + if keyword in text: + parts = text.split(keyword) + if len(parts) > 1: + return parts[1].strip() + return None + +class JellyfinHandler: + def __init__(self, config): + self.config = config + self.music_related_keywords = [] + + if "music" in self.config: + self.music_config = self.config["music"] + self.jellyfin_endpoint = self.music_config['jellyfin']['endpoint'] + self.jellyfin_container = self.music_config['jellyfin']['container'] + self.jellyfin_api_key = self.music_config['jellyfin']['api_key'] + + self.music_related_keywords = self.music_config.get("music_commands", []) + self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3", ".m4a")) + else: + self.jellyfin_endpoint = os.path.abspath("./music") + self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌", + "播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"] + self.music_ext = (".mp3", ".wav", ".p3", ".m4a") + + async def handle_music_command(self, conn, text): + """处理音乐播放指令""" + clean_text = re.sub(r'[^\w\s]', '', text).strip() + logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") + + # 尝试匹配具体歌名 + if self.jellyfin_endpoint: + potential_song = _extract_song_name(clean_text) + if potential_song: + best_match_item = self._find_best_match(potential_song) + if best_match_item: + logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {str(best_match_item)}") + await self.play_local_music(conn, stream_item=best_match_item) + return True + else: + logger.bind(tag=TAG).debug(f"未找到匹配内容: {potential_song}") + else: + logger.bind(tag=TAG).debug(f"未找到潜在的音乐名[播放、听、唱、放]: {clean_text}") + + + # 检查是否是通用播放音乐命令 + if any(cmd in clean_text for cmd in self.music_related_keywords): + await self.play_local_music(conn) + return True + + return False + + async def play_local_music(self, conn, stream_item=None): + """ + 播放本地音乐文件 + specific_file 歌曲对象 + """ + specific_file = stream_item['ItemId'] + song_name = stream_item['Name'] + music_path = None + song_bytes = None + dura_str = None + try: + # 确保路径正确性 + if specific_file: + song_bytes = self.download_music_stream(specific_file) + selected_music = specific_file + dura_str = seconds_to_time(stream_item['RunTimeTicks']/10000000) + else: + selected_music = '中秋月.mp3' + music_path = os.path.join(self.jellyfin_endpoint, selected_music) + if not os.path.exists(music_path): + logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") + return + text = f"正在播放{song_name}.mp3 {dura_str}" + await send_stt_message(conn, text) + conn.tts_first_text = song_name + conn.tts_last_text = song_name + conn.llm_finish_task = True + if music_path and music_path.endswith(".p3"): + opus_packets, duration = p3.decode_opus_from_file(music_path) + else: + opus_packets, duration = conn.tts.wav_stream_to_opus_data(song_bytes) + conn.audio_play_queue.put((opus_packets, text)) + + except Exception as e: + logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + + def _find_best_match(self, potential_song): + """查找最匹配的歌曲""" + """返回item整个对象 + 参数 potential_song 歌曲名称 + 参数 music_files item_list + """ + best_match = None + highest_ratio = 0 + song_list = self.search_list(potential_song) + + for item in song_list: + song_name = item['Name'] + ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() + if ratio > highest_ratio and ratio > 0.4: + highest_ratio = ratio + best_match = item + return best_match + + def download_music_stream(self, item_id: str): + """ + 根据itemId下载stream + return bytes + """ + resp = requests.get(self.jellyfin_endpoint +f'/Audio/{item_id}/stream.{self.jellyfin_container}') + if resp.status_code == 200: + audio_bytes = b"" + for chunk in resp.iter_content(chunk_size=8192): + audio_bytes += chunk + logger.bind(tag=TAG).info(f"音频流已下载为字节数组,大小为 {len(audio_bytes)>>10} kb") + return audio_bytes + else: + raise Exception(f"Failed to download audio file. Status code: {resp.status_code}") + + def search_list(self, term:str): + """网络搜索歌曲 + [{ + "ItemId": "6ff65cc2ad6c211c92ba92a52cee10e0", + "Id": "6ff65cc2ad6c211c92ba92a52cee10e0", + "Name": "香水有毒-DJ", + "Type": "Audio", + "RunTimeTicks": 2935448576, + "MediaType": "Audio", + "Album": "Rendez-Vous: The Sound of the Mediterranean", + "AlbumId": "2b9bc8f465a6d0e561f1ec633e2002df", + "Artists": [], + "ChannelId": null + }] + return List[Dict[str, str]] + """ + resp = ( + requests.get(self.jellyfin_endpoint + f"/Search/Hints?api_key={self.jellyfin_api_key}&mediaTypes=Audio&searchTerm={term}")) + if resp.status_code == 200: + return json.loads(resp.content)['SearchHints'] + else: + raise Exception(f"Failed to download audio file. Status code: {resp.status_code}") diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index b005cf503..eb4b7ecf7 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -383,6 +383,13 @@ module_test: # 本地音乐播放配置 music: + jellyfin: + #尽量保持同一局域网http://xxx.xx:8096 + endpoint: + #管理-控制台-高级-api密钥 + api_key: your api key + #选择格式 + container: mp3 music_commands: - "来一首歌" - "唱一首歌" diff --git a/main/xiaozhi-server/core/handle/jellyfinHandler.py b/main/xiaozhi-server/core/handle/jellyfinHandler.py new file mode 100644 index 000000000..14f477e95 --- /dev/null +++ b/main/xiaozhi-server/core/handle/jellyfinHandler.py @@ -0,0 +1,170 @@ +import json +from typing import Dict, List + +import requests + +from config.logger import setup_logging +import os +import random +import difflib +import re +import traceback +from pathlib import Path +import time +from core.handle.sendAudioHandle import send_stt_message +from core.utils import p3 +from core.utils.util import seconds_to_time + +TAG = __name__ +logger = setup_logging() + + +def _extract_song_name(text): + """从用户输入中提取歌名,可以使用llm中提取""" + logger.bind(tag=TAG).debug(f"从用户输入中提取歌名: {text}") + for keyword in ["听", "播放", "放", "唱"]: + if keyword in text: + parts = text.split(keyword) + if len(parts) > 1: + return parts[1].strip() + return None + +class JellyfinHandler: + def __init__(self, config): + self.config = config + self.music_related_keywords = [] + + if "music" in self.config: + self.music_config = self.config["music"] + self.jellyfin_endpoint = self.music_config['jellyfin']['endpoint'] + self.jellyfin_container = self.music_config['jellyfin']['container'] + self.jellyfin_api_key = self.music_config['jellyfin']['api_key'] + + self.music_related_keywords = self.music_config.get("music_commands", []) + self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3", ".m4a")) + else: + self.jellyfin_endpoint = os.path.abspath("./music") + self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌", + "播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"] + self.music_ext = (".mp3", ".wav", ".p3", ".m4a") + + async def handle_music_command(self, conn, text): + """处理音乐播放指令""" + clean_text = re.sub(r'[^\w\s]', '', text).strip() + logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") + + # 尝试匹配具体歌名 + if self.jellyfin_endpoint: + potential_song = _extract_song_name(clean_text) + if potential_song: + best_match_item = self._find_best_match(potential_song) + if best_match_item: + logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {str(best_match_item)}") + await self.play_local_music(conn, stream_item=best_match_item) + return True + else: + logger.bind(tag=TAG).debug(f"未找到匹配内容: {potential_song}") + else: + logger.bind(tag=TAG).debug(f"未找到潜在的音乐名[播放、听、唱、放]: {clean_text}") + + + # 检查是否是通用播放音乐命令 + if any(cmd in clean_text for cmd in self.music_related_keywords): + await self.play_local_music(conn) + return True + + return False + + async def play_local_music(self, conn, stream_item=None): + """ + 播放本地音乐文件 + specific_file 歌曲对象 + """ + specific_file = stream_item['ItemId'] + song_name = stream_item['Name'] + music_path = None + song_bytes = None + dura_str = None + try: + # 确保路径正确性 + if specific_file: + song_bytes = self.download_music_stream(specific_file) + selected_music = specific_file + dura_str = seconds_to_time(stream_item['RunTimeTicks']/10000000) + else: + selected_music = '中秋月.mp3' + music_path = os.path.join(self.jellyfin_endpoint, selected_music) + if not os.path.exists(music_path): + logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") + return + text = f"正在播放{song_name}.mp3 {dura_str}" + await send_stt_message(conn, text) + conn.tts_first_text = song_name + conn.tts_last_text = song_name + conn.llm_finish_task = True + if music_path and music_path.endswith(".p3"): + opus_packets, duration = p3.decode_opus_from_file(music_path) + else: + #如果文件下载不完整,会报错no close frame received or sent,一般出现在文件太大且转码速度不够 + opus_packets, duration = conn.tts.wav_stream_to_opus_data(song_bytes) + conn.audio_play_queue.put((opus_packets, text, 0)) + + except Exception as e: + logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + + def _find_best_match(self, potential_song): + """查找最匹配的歌曲""" + """返回item整个对象 + 参数 potential_song 歌曲名称 + 参数 music_files item_list + """ + best_match = None + highest_ratio = 0 + song_list = self.search_list(potential_song) + + for item in song_list: + song_name = item['Name'] + ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() + if ratio > highest_ratio and ratio > 0.4: + highest_ratio = ratio + best_match = item + return best_match + + def download_music_stream(self, item_id: str): + """ + 根据itemId下载stream + return bytes + """ + resp = requests.get(self.jellyfin_endpoint +f'/Audio/{item_id}/stream.{self.jellyfin_container}') + if resp.status_code == 200: + audio_bytes = b"" + for chunk in resp.iter_content(chunk_size=8192): + audio_bytes += chunk + logger.bind(tag=TAG).info(f"音频流已下载为字节数组,大小为 {len(audio_bytes)>>10} kb") + return audio_bytes + else: + raise Exception(f"Failed to download audio file. Status code: {resp.status_code}") + + def search_list(self, term:str): + """网络搜索歌曲 + [{ + "ItemId": "6ff65cc2ad6c211c92ba92a52cee10e0", + "Id": "6ff65cc2ad6c211c92ba92a52cee10e0", + "Name": "香水有毒-DJ", + "Type": "Audio", + "RunTimeTicks": 2935448576, + "MediaType": "Audio", + "Album": "Rendez-Vous: The Sound of the Mediterranean", + "AlbumId": "2b9bc8f465a6d0e561f1ec633e2002df", + "Artists": [], + "ChannelId": null + }] + return List[Dict[str, str]] + """ + resp = ( + requests.get(self.jellyfin_endpoint + f"/Search/Hints?api_key={self.jellyfin_api_key}&mediaTypes=Audio&searchTerm={term}")) + if resp.status_code == 200: + return json.loads(resp.content)['SearchHints'] + else: + raise Exception(f"Failed to download audio file. Status code: {resp.status_code}") diff --git a/main/xiaozhi-server/core/handle/searchHandler.py b/main/xiaozhi-server/core/handle/searchHandler.py new file mode 100644 index 000000000..b21c0f10f --- /dev/null +++ b/main/xiaozhi-server/core/handle/searchHandler.py @@ -0,0 +1,42 @@ +import json + +import requests + +from config.logger import setup_logging +TAG = __name__ +logger = setup_logging() + +class SearchHandler: + """传入config.searxng""" + def __init__(self, config: dict): + self.endpoint = config['endpoint'] or None + self.keywords = config['keywords'] or [] + + def match_keywords(self, text_input:str): + if not self.keywords or not self.endpoint: + return None + logger.bind(tag=TAG).debug(f"从用户输入中提取关键词: {text_input}") + for keyword in self.keywords: + if keyword in text_input: + return keyword + return None + + def handle_music_command(self, key:str, timeout_second=5): + response = requests.post( + f"{self.endpoint}/search?format=json", + data={ + 'q':key, + 'categories': 'general', + 'language': 'auto', + 'time_range':'', + 'safesearch':'0', + 'theme': 'simple' + }, timeout=timeout_second + ) + code = response.status_code + if code != 200: + logger.bind(tag=TAG).info(f'search key={key} result http code = {code}') + resp = response.content + item_list = json.loads(resp)['results'] + logger.bind(tag=TAG).info(f'search key={key} result http code = {code} results len={len(item_list)}') + return '\n'.join([i['content'] for i in item_list[:10]]) \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index cc28dbb40..5feb1e96e 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -4,6 +4,7 @@ from core.handle.abortHandle import handleAbortMessage from core.handle.helloHandle import handleHelloMessage from core.handle.receiveAudioHandle import startToChat from core.handle.iotHandle import handleIotDescriptors, handleIotStatus +from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji TAG = __name__ logger = setup_logging() @@ -36,7 +37,17 @@ async def handleTextMessage(conn, message): conn.client_have_voice = False conn.asr_audio.clear() if "text" in msg_json: - await startToChat(conn, msg_json["text"]) + text = msg_json["text"] + text_len, text_without_punctuation = remove_punctuation_and_length(text) + if await conn.music_handler.handle_music_command(conn, text_without_punctuation): + conn.asr_server_receive = True + conn.asr_audio.clear() + return + # if text_len <= conn.max_cmd_length and await handleCMDMessage(conn, text_without_punctuation): + # return + if text_len > 0: + await startToChat(conn, text) + #await startToChat(conn, msg_json["text"]) elif msg_json["type"] == "iot": if "descriptors" in msg_json: await handleIotDescriptors(conn, msg_json["descriptors"]) @@ -44,3 +55,5 @@ async def handleTextMessage(conn, message): await handleIotStatus(conn, msg_json["states"]) except json.JSONDecodeError: await conn.websocket.send(message) + + diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 84737608e..42c8cab83 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -5,6 +5,7 @@ import numpy as np import opuslib_next from pydub import AudioSegment from abc import ABC, abstractmethod +from io import BytesIO TAG = __name__ logger = setup_logging() @@ -41,6 +42,14 @@ class TTSProviderBase(ABC): async def text_to_speak(self, text, output_file): pass + + def wav_stream_to_opus_data(self, wav_bytes): + # 使用pydub加载PCM文件 + if not wav_bytes: + raise IOError('stream null') + audio = AudioSegment.from_file(BytesIO(wav_bytes)) + return self.audio_to_opus_data(audio) + def wav_to_opus_data(self, wav_file_path): # 使用pydub加载PCM文件 # 获取文件后缀名 @@ -48,6 +57,9 @@ class TTSProviderBase(ABC): if file_type: file_type = file_type.lstrip('.') audio = AudioSegment.from_file(wav_file_path, format=file_type) + return self.audio_to_opus_data(audio) + + def audio_to_opus_data(self, audio:AudioSegment): duration = len(audio) / 1000.0 diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 8a8dac953..cba94d544 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -4,6 +4,7 @@ import yaml import socket import subprocess import logging +import math def get_project_dir(): @@ -119,3 +120,9 @@ def check_ffmpeg_installed(): error_msg += "1、按照项目的安装文档,正确进入conda环境\n" error_msg += "2、查阅安装文档,如何在conda环境中安装ffmpeg\n" raise ValueError(error_msg) + +def seconds_to_time(seconds): + # 将秒数转换为小时、分钟和秒 + hours, remainder = divmod(seconds, 3600) # 1 小时 = 3600 秒 + minutes, seconds = divmod(remainder, 60) # 1 分钟 = 60 秒 + return f"{math.floor(hours):02}:{math.floor(minutes):02}:{math.floor(seconds):02}" \ No newline at end of file diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 41629932f..97f8dfb22 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -2,9 +2,9 @@ import asyncio import websockets from config.logger import setup_logging from core.connection import ConnectionHandler -from core.handle.musicHandler import MusicHandler from core.utils.util import get_local_ip from core.utils import asr, vad, llm, tts, memory +from core.handle.jellyfinHandler import JellyfinHandler TAG = __name__ @@ -21,6 +21,11 @@ class WebSocketServer: has_memory_cfg = self.config.get("Memory") and memory_cls_name in self.config["Memory"] memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {} + if (self.config["music"].__contains__('jellyfin') and self.config["music"]["jellyfin"].__contains__("endpoint") + and self.config["music"]["jellyfin"].__contains__("api_key")): + handler = JellyfinHandler(self.config) + else: + handler = MusicHandler(self.config) """创建处理模块实例""" return ( vad.create_instance( @@ -50,7 +55,7 @@ class WebSocketServer: self.config["TTS"][self.config["selected_module"]["TTS"]], self.config["delete_audio"] ), - MusicHandler(self.config), + handler, memory.create_instance(memory_cls_name, memory_cfg), )