diff --git a/config.yaml b/config.yaml index 5dd2793e9..c4e9e1bd8 100644 --- a/config.yaml +++ b/config.yaml @@ -107,6 +107,13 @@ LLM: base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 model_name: qwen-turbo api_key: 你的deepseek api key + OpenAILLM: + # 定义LLM API类型 + type: openai + # 可在这里找到你的 api_key https://platform.openai.com/api-keys + base_url: https://api.openai.com/v1 + model_name: gpt-4-turbo # o3-mini + api_key: 你的openAI api key DeepSeekLLM: # 定义LLM API类型 type: openai @@ -161,6 +168,23 @@ LLM: base_url: http://homeassistant.local:8123 agent_id: conversation.chatgpt api_key: 你的home assistant api访问令牌 + SparkLLM: + # 定义LLM API类型 + type: spark + #appid、api_secret、api_key三个服务认证信息请前往开放平台控制台查看(https://console.xfyun.cn/services/bm35) + # base_url = "wss://spark-api.xf-yun.com/v3.5/chat", # Max环境的地址 + # base_url = "wss://spark-api.xf-yun.com/v4.0/chat", # 4.0Ultra环境的地址 + # base_url = "wss://spark-api.xf-yun.com/v3.1/chat" # Pro环境的地址 + # base_url = "wss://spark-api.xf-yun.com/v1.1/chat" # Lite环境的地址 + # domain = "generalv3.5", # Max版本 + # domain = "4.0Ultra", # 4.0Ultra 版本 + # domain = "generalv3" # Pro版本 + # domain = "lite" # Lite版本址 + appid: 你的xfyun App Id + api_secret: 你的xfyun Access Token + api_key: 你的xfyun api key + base_url: wss://spark-api.xf-yun.com/v4.0/chat + model_name: 4.0Ultra TTS: # 当前支持的type为edge、doubao,可自行适配 EdgeTTS: @@ -305,6 +329,31 @@ TTS: # volume: 50 # speech_rate: 0 # pitch_rate: 0 + OpenAITTS: + # 定义TTS API类型 + type: openai + # OpenAI TTS服务配置 + model_name: tts-1 + api_url: https://api.openai.com/v1 + api_key: 你的openAI api key + # 可选的语音模型:alloy, ash, coral, echo, fable, onyx, nova, sage, shimmer + voice: alloy + # 输出文件目录 + output_file: tmp/ + SparkTTS: + # 定义LLM API类型 + type: spark + # "voice": "xiaoyan", + # "sample_rate": 16000, + # "output_file": "output" + #appid、api_secret、api_key三个服务认证信息请前往开放平台控制台查看(https://console.xfyun.cn/services/bm35) + # Spark_url="wss://spark-api.xf-yun.com/v3.5/chat", # Max环境的地址 + appid: 你的xfyun App Id + api_secret: 你的xfyun Access Token + api_key: 你的xfyun api key + voice: xiaoyan + sample_rate: 16000 + output_file: tmp/ # 模块测试配置 module_test: diff --git a/core/providers/llm/spark/spark.py b/core/providers/llm/spark/spark.py new file mode 100644 index 000000000..d5ccf88b2 --- /dev/null +++ b/core/providers/llm/spark/spark.py @@ -0,0 +1,148 @@ +# coding: utf-8 +import json +import base64 +import hmac +import hashlib +import ssl +import websocket +from urllib.parse import urlencode, urlparse +from datetime import datetime +from time import mktime +from wsgiref.handlers import format_date_time +from core.providers.llm.base import LLMProviderBase +from config.logger import setup_logging +import queue + +TAG = __name__ +logger = setup_logging() + +class LLMProvider(LLMProviderBase): + def __init__(self, config): + self.appid = config.get("appid") + self.api_key = config.get("api_key") + self.api_secret = config.get("api_secret") + self.base_url = config.get("base_url") + self.model_name = config.get("model_name", "4.0Ultra") + if "你" in self.api_key: + logger.bind(tag=TAG).error("你还没配置LLM的密钥,请在配置文件中配置密钥,否则无法正常工作") + + self.host = urlparse(self.base_url).netloc + self.path = urlparse(self.base_url).path + self.query_url = self.create_url() + self.response_queue = queue.Queue() # 用来收集WebSocket的响应 + + def create_url(self): + # 生成访问讯飞星火API的URL + now = datetime.now() + date = format_date_time(mktime(now.timetuple())) + + signature_origin = f"host: {self.host}\ndate: {date}\nGET {self.path} HTTP/1.1" + signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'), hashlib.sha256).digest() + signature_sha_base64 = base64.b64encode(signature_sha).decode('utf-8') + + authorization_origin = f'api_key="{self.api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"' + authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode('utf-8') + + params = { + "authorization": authorization, + "date": date, + "host": self.host + } + return self.base_url + '?' + urlencode(params) + + def on_message(self, ws, message): + # 处理接收到的消息 + data = json.loads(message) + code = data['header']['code'] + if code != 0: + logger.bind(tag=TAG).error(f'请求错误: {code}, {data}') + ws.close() + else: + choices = data["payload"]["choices"] + status = choices["status"] + content = choices["text"][0]["content"] + if content: + self.response_queue.put(content) # 收集内容 + if status == 2: + logger.bind(tag=TAG).info("会话结束") + ws.close() + + def on_error(self, ws, error): + # 处理WebSocket错误 + logger.bind(tag=TAG).error(f"WebSocket错误: {error}") + + def on_close(self, ws, close_status_code, close_msg): + # 处理WebSocket关闭 + logger.bind(tag=TAG).info(f"WebSocket已关闭,状态码: {close_status_code}, 消息: {close_msg}") + + def on_open(self, ws): + # 处理WebSocket连接打开 + # 发送请求数据 + request_data = self.gen_params(ws.query) + logger.bind(tag=TAG).debug(f"request_data: {request_data}") + ws.send(json.dumps(request_data)) + + def gen_params(self, query): + # 生成WebSocket请求参数 + data = { + "header": { + "app_id": self.appid, + "uid": "1234", # 可根据需要生成或传入实际UID + }, + "parameter": { + "chat": { + "domain": self.model_name, + "temperature": 0.5, + "max_tokens": 4096, + } + }, + "payload": { + "message": { + "text": query + } + } + } + return data + + def run_websocket(self, query): + # 启动WebSocket连接并发送请求 + ws = websocket.WebSocketApp(self.query_url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) + ws.appid = self.appid + ws.query = query + logger.bind(tag=TAG).debug(f"ws.query: {ws.query}") + ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) + + def response(self, session_id, dialogue): + # 生成LLM的响应(通过WebSocket获取流式响应) + try: + # 启动WebSocket连接并获取流式数据 + logger.bind(tag=TAG).debug(f"dialogue: {dialogue}") + if dialogue == "": + logger.bind(tag=TAG).error("对话内容为空") + dialogue = "你好" + + self.run_websocket(dialogue) + # 通过Queue来获取响应内容 + while not self.response_queue.empty(): + yield self.response_queue.get() # 返回队列中的内容 + except Exception as e: + logger.bind(tag=TAG).error(f"获取LLM响应时发生错误: {e}") + +# windows下执行 $env:PYTHONPATH="../../../../"; python spark.py 进行测试 +# Linux/MacOS下执行 PYTHONPATH=../../../../ python your_script.py 进行测试 +if __name__ == "__main__": + config = { + "appid": "xxxx", + "api_key": "xxxx", + "api_secret": "xxxx", + "base_url": "wss://spark-api.xf-yun.com/v4.0/chat", + "model_name": "4.0Ultra", + } + + provider = LLMProvider(config) + session_id = "1234" + dialogue = "给我写一篇100字的作文" + data = [{"role": "user", "content": dialogue}] + + for content in provider.response(session_id, data): + logger.bind(tag=TAG).info(f"content: {content}") diff --git a/core/providers/tts/openai.py b/core/providers/tts/openai.py new file mode 100644 index 000000000..abc3936e9 --- /dev/null +++ b/core/providers/tts/openai.py @@ -0,0 +1,70 @@ +import os +import uuid +# import logging +from datetime import datetime +from openai import OpenAI +from core.providers.tts.base import TTSProviderBase +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.api_key = config.get("api_key") + self.api_url = config.get("api_url") + self.model_name = config.get("model_name", "tts-1") + + if not self.api_key: + raise ValueError("OpenAI API key is required but not provided in config") + + self.voice = config.get("voice", "alloy") + + try: + # Initialize OpenAI client with custom base URL if provided + if self.api_url: + self.client = OpenAI( + api_key=self.api_key, + base_url=self.api_url + ) + else: + self.client = OpenAI(api_key=self.api_key) + except Exception as e: + logger.bind(tag=TAG).error(f"Failed to initialize OpenAI client: {str(e)}") + raise + + def generate_filename(self, extension=".mp3"): + return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}") + + async def text_to_speak(self, text, output_file): + if not text or not output_file: + raise ValueError("Both text and output_file must be provided") + + try: + # Ensure output directory exists + output_dir = os.path.dirname(output_file) + if not os.path.exists(output_dir): + os.makedirs(output_dir, exist_ok=True) + + logger.bind(tag=TAG).info(f"Generating speech for text: {text}") + logger.bind(tag=TAG).info(f"Using API URL: {self.api_url if self.api_url else 'default OpenAI URL'}") + + response = self.client.audio.speech.create( + model=self.model_name, + voice=self.voice, + input=text + ) + + # Save the audio file + response.stream_to_file(output_file) + + # Verify file was created + if not os.path.exists(output_file): + raise Exception("Failed to create audio file") + else: + logger.bind(tag=TAG).info(f"Successfully created audio file: {output_file}") + + except Exception as e: + logger.bind(tag=TAG).error(f"OpenAI TTS generation failed: {str(e)}") + raise Exception(f"OpenAI TTS generation failed: {str(e)}") diff --git a/core/providers/tts/spark.py b/core/providers/tts/spark.py new file mode 100644 index 000000000..44a3b2244 --- /dev/null +++ b/core/providers/tts/spark.py @@ -0,0 +1,188 @@ +# coding: utf-8 +import ssl +import uuid +import websocket +import json +import base64 +import os +import time +import threading +import hashlib +import hmac +from urllib.parse import urlencode +from wsgiref.handlers import format_date_time +from datetime import datetime +from time import mktime +from urllib.parse import urlencode +from config.logger import setup_logging +from core.providers.tts.base import TTSProviderBase, logger, TAG +from core.utils.util import read_config, get_project_dir + +STATUS_FIRST_FRAME = 0 # 第一帧的标识 +STATUS_CONTINUE_FRAME = 1 # 中间帧标识 +STATUS_LAST_FRAME = 2 # 最后一帧的标识 + + +class TTSProvider(TTSProviderBase): + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.appid = config.get("appid") + self.api_key = config.get("api_key") + self.api_secret = config.get("api_secret") + self.is_finished = False # 用于标记是否已完成音频接收 + + if not self.api_key or not self.api_secret: + raise ValueError("Xunfei API key and secret are required but not provided in config") + + self.voice = config.get("voice", "xiaoyan") + self.sample_rate = config.get("sample_rate", 16000) + self.ws_url = "wss://tts-api.xfyun.cn/v2/tts" + self.common_args = {"app_id": self.appid} + self.business_args = { + "aue": "lame", + "auf": "audio/L16;rate=16000", + "vcn": self.voice, + "tte": "utf8" + } + self.text = None + self.my_output_file = None + + + def create_url(self): + now = datetime.now() + date = format_date_time(mktime(now.timetuple())) + + signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" + signature_origin += "date: " + date + "\n" + signature_origin += "GET " + "/v2/tts " + "HTTP/1.1" + + signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'), + digestmod=hashlib.sha256).digest() + signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8') + + authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % ( + self.api_key, "hmac-sha256", "host date request-line", signature_sha) + authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8') + + v = { + "authorization": authorization, + "date": date, + "host": "ws-api.xfyun.cn" + } + + url = self.ws_url + '?' + urlencode(v) + return url + + def generate_filename(self, extension=".mp3"): + return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}") + + async def text_to_speak(self, text, output_file): + # """ + # 语音合成接口 + # :param text: 需要合成的文本 + # :param output_file: 输出音频文件的路径 + # :return: 返回合成音频的文件路径 + # """ + if not text or not output_file: + raise ValueError("Both text and output_file must be provided") + + try: + self.text = text + self.my_output_file = output_file + + # Ensure output directory exists + output_dir = os.path.dirname(output_file) + if not os.path.exists(output_dir): + os.makedirs(output_dir, exist_ok=True) + + self.run() + + # Verify file was created + if not os.path.exists(output_file): + raise Exception("Failed to create audio file") + else: + logger.bind(tag=TAG).debug(f"Successfully created audio file: {output_file}") + + except Exception as e: + logger.bind(tag=TAG).error(f"SparkTTS generation failed: {str(e)}") + raise Exception(f"SparkTTS generation failed: {str(e)}") + + def on_message(self, ws, message): + try: + message = json.loads(message) + code = message["code"] + sid = message["sid"] + audio = message["data"]["audio"] + audio = base64.b64decode(audio) + status = message["data"]["status"] + logger.bind(tag=TAG).debug(f"message: {message}") + + if status == 2: # 最后一帧 + logger.bind(tag=TAG).debug(f"Received the last frame, closing websocket.") + self.is_finished = True + ws.close() + + if code != 0: + errMsg = message["message"] + logger.bind(tag=TAG).error(f"sid:{sid} call error: {errMsg} code is:{code}") + else: + file_to_save = open(self.my_output_file, "wb") + file_to_save.write(audio) + # file_to_save.write(base64.b64decode(data)) + # with open(self.output_file, 'ab') as f: + # f.write(audio) + + except Exception as e: + logger.bind(tag=TAG).error(f"Error while receiving message: {e}") + + def on_error(self, ws, error): + logger.bind(tag=TAG).error(f"Error: {error}") + self.is_finished = True + + def on_close(self, ws, close_status_code, close_msg): + logger.bind(tag=TAG).debug(f"WebSocket closed.") + self.is_finished = True + + def on_open(self, ws): + def run(*args): + data = { + "common": self.common_args, + "business": self.business_args, + "data": {"status": 2, "text": str(base64.b64encode(self.text.encode('utf-8')), "UTF8")} + } + data = json.dumps(data) + logger.bind(tag=TAG).debug(f"Sending text data to server...") + ws.send(data) + + threading.Thread(target=run).start() + + def run(self): + ws_url = self.create_url() + ws = websocket.WebSocketApp(ws_url, + on_message=self.on_message, + on_error=self.on_error, + on_close=self.on_close) + ws.on_open = self.on_open + ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) + + # 等待音频接收完成后再退出 + while not self.is_finished: + time.sleep(0.1) # 等待直到接收到最后一帧或发生错误 + + logger.bind(tag=TAG).debug(f"WebSocket session finished.") + + +# 例子 +if __name__ == "__main__": + config = { + "appid": "xxxx", + "api_key": "xxxx", + "api_secret": "xxxx", + "voice": "xiaoyan", + "sample_rate": 16000 + } + + provider = TTSProvider(config, False) + output_file = provider.generate_filename(extension=".mp3") + provider.text_to_speak("这是一个语音合成示例", output_file) + logger.bind(tag=TAG).debug(f"合成的语音文件保存到: {output_file}") diff --git a/core/utils/llm.py b/core/utils/llm.py index 8fdec09b2..472e33ded 100644 --- a/core/utils/llm.py +++ b/core/utils/llm.py @@ -15,6 +15,7 @@ from core.utils.util import is_segment from core.utils.util import get_string_no_punctuation_or_emoji from core.utils.util import read_config, get_project_dir +TAG = __name__ logger = setup_logging() @@ -22,6 +23,7 @@ def create_instance(class_name, *args, **kwargs): # 创建LLM实例 if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')): lib_name = f'core.providers.llm.{class_name}.{class_name}' + logger.bind(tag=TAG).info(f"加载LLM模块: {lib_name}") if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].LLMProvider(*args, **kwargs) diff --git a/core/utils/tts.py b/core/utils/tts.py index 2fc733f73..246cff449 100644 --- a/core/utils/tts.py +++ b/core/utils/tts.py @@ -5,6 +5,7 @@ import importlib from datetime import datetime from core.utils.util import read_config, get_project_dir +TAG = __name__ logger = setup_logging() @@ -12,6 +13,7 @@ def create_instance(class_name, *args, **kwargs): # 创建TTS实例 if os.path.exists(os.path.join('core', 'providers', 'tts', f'{class_name}.py')): lib_name = f'core.providers.tts.{class_name}' + logger.bind(tag=TAG).info(f"加载TTS模块: {lib_name}") if lib_name not in sys.modules: sys.modules[lib_name] = importlib.import_module(f'{lib_name}') return sys.modules[lib_name].TTSProvider(*args, **kwargs)