From 8b151d07c2621d27abf653da84cd3755072f330d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AC=A3=E5=8D=97=E7=A7=91=E6=8A=80?= Date: Wed, 5 Mar 2025 00:20:51 +0800 Subject: [PATCH 1/2] Mem0ai (#199) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * update:增加mem0ai包依赖 * update:文档增加mem0ai的描述 --------- Co-authored-by: hrz <1710360675@qq.com> --- README.md | 11 ++++++++++- config.yaml | 3 ++- docs/Deployment.md | 7 ++++--- requirements.txt | 4 +++- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 23424ae71..fc1cb425f 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,8 @@ 1、本项目为开源软件,本软件与对接的任何第三方API服务商(包括但不限于语音识别、大模型、语音合成等平台)均不存在商业合作关系,不为其服务质量及资金安全提供任何形式的担保。 建议使用者优先选择持有相关业务牌照的服务商,并仔细阅读其服务协议及隐私政策。本软件不托管任何账户密钥、不参与资金流转、不承担充值资金损失风险。 -2、本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必在配置文件 `config.yaml` 中开启防护: +2、本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必在配置文件 +`config.yaml` 中开启防护: ```yaml server: @@ -193,6 +194,14 @@ server: --- +### Memory + +| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 | +|:------:|:------:|:----:|:----:|:--:| +| Memory | mem0ai | 接口调用 | 免费 | | + +--- + ## 使用方式 🚀 ### 一、[部署文档](./docs/Deployment.md) diff --git a/config.yaml b/config.yaml index 4185640b0..6d9cd989b 100644 --- a/config.yaml +++ b/config.yaml @@ -85,7 +85,8 @@ selected_module: Memory: mem0ai: type: mem0ai - # https://app.mem0.ai/dashboard/api-keys,注册可获得试用credits + # https://app.mem0.ai/dashboard/api-keys + # 每月有1000次免费调用 api_key: 你的mem0ai api key ASR: diff --git a/docs/Deployment.md b/docs/Deployment.md index 81c4d7f96..8f5b4f914 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -231,9 +231,10 @@ python app.py 如果你的`项目目录`目录没有`data`,你需要创建`data`目录。 如果你的`data`下面没有`.config.yaml`文件,你可以把源码目录下的`config.yaml`文件复制一份,重命名为`.config.yaml` -修改`项目目录`下`data`目录下的`.config.yaml`文件,配置本项目所需的各种参数。默认的LLM使用的是`ChatGLMLLM` -,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。 -默认的TTS使用的是`EdgeTTS`,这个无需配置,如果你需要更换成`豆包TTS`,则需要配置密钥。 +修改`项目目录`下`data`目录下的`.config.yaml`文件,配置本项目必须的两个配置。 + +- 默认的LLM使用的是`ChatGLMLLM`,你需要配置密钥,因为他们的模型,虽然有免费的,但是仍要去[官网](https://bigmodel.cn/usercenter/proj-mgmt/apikeys)注册密钥,才能启动。 +- 默认的记忆层`mem0ai`,你需要配置密钥,因为他们的API,虽然有免费额度,但是仍要去[官网](https://app.mem0.ai/dashboard/api-keys)注册密钥,才能启动。 配置说明:这里是各个功能使用的默认组件,例如LLM默认使用`ChatGLMLLM`模型。如果需要切换模型,就是改对应的名称。 本项目的默认配置仅是成本最低配置(`glm-4-flash`和`EdgeTTS`都是免费的),如果需要更优的更快的搭配,需要自己结合部署环境切换各组件的使用。 diff --git a/requirements.txt b/requirements.txt index 4d75889dc..9716c8252 100755 --- a/requirements.txt +++ b/requirements.txt @@ -17,4 +17,6 @@ ormsgpack==1.7.0 ruamel.yaml==0.18.10 loguru==0.7.3 requests==2.32.3 -cozepy==0.12.0 \ No newline at end of file +cozepy==0.12.0 +miniaudio==1.61 +mem0ai==0.1.62 From ca38a2a0f7855edf22df1c56454dbb08c7825696 Mon Sep 17 00:00:00 2001 From: freshlife001 Date: Wed, 5 Mar 2025 00:25:54 +0800 Subject: [PATCH 2/2] feat: play online mp3 (#181) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 欣南科技 --- core/handle/musicHandler.py | 288 ++++++++++++++++++++++++++++++++++-- requirements.txt | 2 +- 2 files changed, 278 insertions(+), 12 deletions(-) diff --git a/core/handle/musicHandler.py b/core/handle/musicHandler.py index 53ec49c4e..e380704f9 100644 --- a/core/handle/musicHandler.py +++ b/core/handle/musicHandler.py @@ -9,18 +9,251 @@ import time from core.handle.sendAudioHandle import send_stt_message from core.utils import p3 +import urllib.request +import urllib.parse +urllib.request.socket.setdefaulttimeout(10) +import requests +import io +from threading import Thread, Event +from queue import Queue +import struct +from pydub import AudioSegment +import miniaudio +import json +import sys +import opuslib_next + TAG = __name__ logger = setup_logging() -def _extract_song_name(text): - """从用户输入中提取歌名""" - for keyword in ["听", "播放", "放", "唱"]: - if keyword in text: - parts = text.split(keyword) - if len(parts) > 1: - return parts[1].strip() - return None + +class CustomIceCastClient(miniaudio.IceCastClient): + def read(self, num_bytes: int) -> bytes: + """Read a chunk of data from the stream.""" + while len(self._buffer) < num_bytes: + time.sleep(0.1) + if self._stop_stream: + raise ValueError("Steam stoped") + with self._buffer_lock: + chunk = self._buffer[:num_bytes] + self._buffer = self._buffer[num_bytes:] + return chunk + + +class OpusStreamConverter: + @staticmethod + def search_mp3(keywords): + try: + encoded_keywords = urllib.parse.quote(keywords) + search_url = f"https://www.kumeiwp.com/index/search/data?page=1&limit=15&word={encoded_keywords}&scope=all" + + logger.bind(tag=TAG).debug(f"Searching {keywords} {search_url}") + response = requests.get(search_url) + response.raise_for_status() + + data = response.json() + if 'data' in data and len(data['data']) > 0: + for item in data['data']: + if 'file_id' in item and 'title' in item: + file_id = item['file_id'] + import re + title = item['title'] + if title.startswith(' 5: + logger.bind(tag=TAG).debug("No new frames for 5 seconds, closing stream") + self.buffer.put(None) + if self.client: + self.client.close() + break + time.sleep(0.1) + logger.bind(tag=TAG).debug("check_timeout thread ended") + #time.sleep(0.1) + #logger.bind(tag=TAG).debug_all_threads_stack() + + def stream_reader(self, url): + try: + logger.bind(tag=TAG).debug(f"stream reader with {url}") + # Start timeout checker thread + timeout_thread = Thread(target=self.check_timeout) + timeout_thread.start() + self.last_frame_time = time.time() + + self.client = CustomIceCastClient(url) + logger.bind(tag=TAG).debug("stream client created") + + + + self.stream = miniaudio.stream_any( + source=self.client, + source_format=miniaudio.FileFormat.MP3, + output_format=miniaudio.SampleFormat.SIGNED16, + nchannels=1, + sample_rate=16000, + frames_to_read=960 + ) + logger.bind(tag=TAG).debug("stream started") + frame_counter = 0 + last_frame_len = 0 + + for frames in self.stream: + self.last_frame_time = time.time() + if not len(frames): + logger.bind(tag=TAG).debug("Empty frame detected, stream might have ended") + break + + if frame_counter == 0: + self.initialize_encoder(frames) + logger.bind(tag=TAG).debug(f"Sample Rate: {self.sample_rate}") + logger.bind(tag=TAG).debug(f"Channels: {self.channels}") + logger.bind(tag=TAG).debug(f"Frame Size: {self.frame_size}") + + if not self.is_streaming: + logger.bind(tag=TAG).debug("Streaming stopped by user") + break + + # Check for stream errors or interruptions + if last_frame_len and len(frames) != last_frame_len: + logger.bind(tag=TAG).debug(f"Frame size changed: {last_frame_len} -> {len(frames)}") + + last_frame_len = len(frames) + frame_counter += 1 + self.buffer.put(frames.tobytes()) + + logger.bind(tag=TAG).debug(f"Stream ended after {frame_counter} frames") + self.buffer.put(None) + + except ConnectionError as e: + logger.bind(tag=TAG).debug(f"Connection error: {e}") + except Exception as e: + logger.bind(tag=TAG).debug(f"Error in stream reader: {e}") + finally: + logger.bind(tag=TAG).debug(f"Stream closed") + self.timeout_event.set() + try: + self.buffer.put(None) + self.client.close() + except: + pass + + def initialize_encoder(self, first_frames): + self.sample_rate = 16000 + self.channels = 1 + self.frame_size = 960 + + self.encoder = opuslib_next.Encoder( + self.sample_rate, + self.channels, + opuslib_next.APPLICATION_AUDIO + ) + + def convert(self, url, output_file): + stream_thread = Thread(target=self.stream_reader, args=(url,)) + stream_thread.start() + + try: + with open(output_file, 'wb') as opus_file: + while True: + pcm_frame = self.buffer.get() + if pcm_frame is None: + break + + # Encode PCM to Opus + if self.encoder: + opus_frame = self.encoder.encode(pcm_frame, self.frame_size) + frame_length = len(opus_frame) + opus_file.write(struct.pack(' 0: + conn.audio_play_queue.put((opus_packets, selected_music + "[end]")) + break + + # Encode PCM to Opus + if self.encoder: + opus_frame = self.encoder.encode(pcm_frame, self.frame_size) + opus_packets.append(opus_frame) + if len(opus_packets) >= 100: + if not started: + started = True + conn.audio_play_queue.put((opus_packets, selected_music + "[start]")) + else: + conn.audio_play_queue.put((opus_packets, selected_music)) + opus_packets = [] + + except Exception as e: + logger.bind(tag=TAG).debug(f"Error during streaming: {e}") + finally: + logger.bind(tag=TAG).debug("Stream stoping") + self.is_streaming = False + stream_thread.join() + logger.bind(tag=TAG).debug("Stream stoped") + + def play(self, url, conn, selected_music): + stream_thread = Thread(target=self.stream_reader, args=(url,)) + stream_thread.start() + + playing_thread = Thread(target=self.stream_player, args=(url, conn, selected_music, stream_thread)) + playing_thread.start() + + def _find_best_match(potential_song, music_files): @@ -93,7 +326,7 @@ class MusicHandler: self.scan_time = time.time() logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}") - potential_song = _extract_song_name(clean_text) + potential_song = self._extract_song_name(clean_text) if potential_song: best_match = _find_best_match(potential_song, self.music_files) if best_match: @@ -103,11 +336,24 @@ class MusicHandler: # 检查是否是通用播放音乐命令 if any(cmd in clean_text for cmd in self.music_related_keywords): - await self.play_local_music(conn) + potential_song = self._extract_song_name(clean_text) + if potential_song: + await self.play_remote_music(conn, potential_song) + else: + await self.play_local_music(conn) return True return False + def _extract_song_name(self, text): + """从用户输入中提取歌名""" + for keyword in self.music_related_keywords + ["听", "播放", "放", "唱"]: + if keyword in text: + parts = text.split(keyword) + if len(parts) > 1: + return parts[1].strip() + return None + async def play_local_music(self, conn, specific_file=None): """播放本地音乐文件""" try: @@ -137,7 +383,7 @@ class MusicHandler: if not os.path.exists(music_path): logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") return - text = f"正在播放{selected_music}" + text = f"正在本地播放{selected_music}" await send_stt_message(conn, text) conn.tts_first_text_index = 0 conn.tts_last_text_index = 0 @@ -151,3 +397,23 @@ class MusicHandler: except Exception as e: logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + + async def play_remote_music(self, conn, potential_song): + try: + logger.bind(tag=TAG).debug(f"搜索并播放音乐: {potential_song}") + url, title = OpusStreamConverter.search_mp3(potential_song) + if url: + selected_music = title + text = f"正在搜索播放{selected_music}" + await send_stt_message(conn, text) + conn.tts_first_text = selected_music + "[start]" + conn.tts_last_text = selected_music + "[end]" + conn.llm_finish_task = True + converter = OpusStreamConverter() + logger.bind(tag=TAG).debug(f"Starting playing... {selected_music}") + converter.play(url, conn, selected_music) + else: + logger.bind(tag=TAG).debug("MP3 not found") + except Exception as e: + logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 9716c8252..3edafe34b 100755 --- a/requirements.txt +++ b/requirements.txt @@ -19,4 +19,4 @@ loguru==0.7.3 requests==2.32.3 cozepy==0.12.0 miniaudio==1.61 -mem0ai==0.1.62 +mem0ai==0.1.62 \ No newline at end of file