tianyun vor 3 Monaten
Ursprung
Commit
adb8d5bdf3
3 geänderte Dateien mit 85 neuen und 0 gelöschten Zeilen
  1. 71 0
      tts/main.py
  2. 4 0
      tts/requirements.txt
  3. 10 0
      tts/restart.sh

+ 71 - 0
tts/main.py

@@ -0,0 +1,71 @@
+from flask import Flask, request, send_file, jsonify
+from flask_cors import CORS
+import dashscope
+from dashscope.audio.tts_v2 import SpeechSynthesizer
+import hashlib
+import os
+
+app = Flask(__name__)
+CORS(app)  # 允许所有域名跨域访问
+
+# 配置
+CACHE_FOLDER = 'audio_cache'
+MODEL = "cosyvoice-v1"
+VOICE = "longxiaochun"
+
+# 确保缓存文件夹存在
+os.makedirs(CACHE_FOLDER, exist_ok=True)
+
+
+def get_md5(text):
+    """生成文本的MD5哈希值"""
+    return hashlib.md5(text.encode('utf-8')).hexdigest()
+
+
+def generate_audio(text, output_path):
+    """使用DashScope生成语音文件"""
+    synthesizer = SpeechSynthesizer(model=MODEL, voice=VOICE)
+    audio = synthesizer.call(text)
+    with open(output_path, 'wb') as f:
+        f.write(audio)
+    return synthesizer.get_last_request_id()
+
+
+@app.route('/tts', methods=['POST', 'OPTIONS'])
+def text_to_speech():
+    if request.method == 'OPTIONS':
+        return jsonify({}), 200
+
+    # 获取请求数据
+    data = request.get_json()
+    if not data or 'text' not in data:
+        return jsonify({'error': 'Missing text parameter'}), 400
+
+    text = data['text']
+
+    # 生成文件名
+    filename = get_md5(text) + '.mp3'
+    filepath = os.path.join(CACHE_FOLDER, filename)
+
+    # 检查缓存
+    if not os.path.exists(filepath):
+        try:
+            request_id = generate_audio(text, filepath)
+            print(f'Generated new audio file with requestId: {request_id}')
+        except Exception as e:
+            return jsonify({'error': f'Failed to generate audio: {str(e)}'}), 500
+
+    # 返回音频文件
+    try:
+        return send_file(
+            filepath,
+            mimetype='audio/mpeg',
+            as_attachment=True,
+            download_name=f'tts_{filename}'
+        )
+    except Exception as e:
+        return jsonify({'error': f'Failed to send audio file: {str(e)}'}), 500
+
+
+if __name__ == '__main__':
+    app.run(host='0.0.0.0', port=15001, debug=True)

+ 4 - 0
tts/requirements.txt

@@ -0,0 +1,4 @@
+flask
+flask_socketio
+flask_cors
+dashscope

+ 10 - 0
tts/restart.sh

@@ -0,0 +1,10 @@
+# 检查是否已有 main.py 进程在运行
+if pgrep -f "main.py --name mytts" > /dev/null
+then
+    echo "Process is already running. Restarting..."
+    # 终止已有的 main.py 进程
+    pkill -f "main.py --name mytts"
+fi
+export DASHSCOPE_API_KEY="sk-15b84b8c16864b20b14d4c399be4a162"
+# 启动新的 main.py 进程
+nohup python -u main.py --name mytts &