File size: 3,985 Bytes
0787642 c3f3ef3 0787642 3f90d3e 0787642 c3f3ef3 0787642 c3f3ef3 3f90d3e 0787642 3f90d3e 9df74e4 3f90d3e 0787642 c3f3ef3 0787642 3f90d3e 9df74e4 3f90d3e 0787642 698fdb6 0787642 3f90d3e 9df74e4 3f90d3e 0787642 3f90d3e 9df74e4 3f90d3e 9df74e4 0787642 3f90d3e 9df74e4 3f90d3e 9df74e4 0787642 3f90d3e 9df74e4 0787642 3f90d3e 9df74e4 0787642 9df74e4 3f90d3e 0787642 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HuggingFace Spaces 应用程序
只提供WebSocket服务,没有任何UI界面
"""
import asyncio
import os
import logging
import sys
import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from tts_websocket_server import TTSWebsocketServer
# 配置日志
logging.basicConfig(
level=logging.WARNING,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger("edge-tts-app")
# 创建 FastAPI 应用
app = FastAPI()
# 添加 CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 从环境变量获取 API 密钥
API_KEY = os.environ.get("API_KEY")
logger.warning(f"API 密钥已加载: {'已设置' if API_KEY else '未设置'}")
print(f"API 密钥已加载: {'已设置' if API_KEY else '未设置'}")
# 创建一个测试路由,用于检查 API 密钥
@app.get("/api-key-status")
async def api_key_status():
return {"api_key_set": API_KEY is not None}
# 创建一个简单的首页路由
@app.get("/")
async def root():
return {"message": "WebSocket服务已启动,请使用WebSocket连接"}
# 创建 WebSocket 路由
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
logger.warning("收到 WebSocket 连接请求")
print("收到 WebSocket 连接请求")
# 严格验证 API 密钥
if API_KEY:
# 从查询参数获取 API 密钥,只接受 API_KEY 参数名
query_params = dict(websocket.query_params)
client_api_key = query_params.get('API_KEY')
logger.warning(f"客户端提供的 API_KEY: {client_api_key}")
logger.warning(f"服务器的 API_KEY: {API_KEY}")
print(f"客户端提供的 API_KEY: {client_api_key}")
print(f"服务器的 API_KEY: {API_KEY}")
# 验证密钥
if not client_api_key:
logger.warning("API 密钥验证失败: 未提供密钥")
print("API 密钥验证失败: 未提供密钥")
try:
await websocket.close(code=4003, reason="无效的 API 密钥")
except Exception as e:
logger.error(f"关闭 WebSocket 连接时出错: {str(e)}")
print(f"关闭 WebSocket 连接时出错: {str(e)}")
return
if client_api_key != API_KEY:
logger.warning(f"API 密钥验证失败: 密钥不匹配")
print(f"API 密钥验证失败: 密钥不匹配")
try:
await websocket.close(code=4003, reason="无效的 API 密钥")
except Exception as e:
logger.error(f"关闭 WebSocket 连接时出错: {str(e)}")
print(f"关闭 WebSocket 连接时出错: {str(e)}")
return
logger.warning("API 密钥验证成功")
print("API 密钥验证成功")
else:
logger.warning("未设置 API 密钥,跳过验证")
print("未设置 API 密钥,跳过验证")
# 接受连接并处理
try:
await websocket.accept()
logger.warning("WebSocket 连接已接受")
print("WebSocket 连接已接受")
ws_server = TTSWebsocketServer()
await ws_server._handle_connection(websocket, "/ws")
except WebSocketDisconnect:
logger.warning("WebSocket 连接已断开")
print("WebSocket 连接已断开")
except Exception as e:
logger.error(f"WebSocket 处理错误: {str(e)}")
print(f"WebSocket 处理错误: {str(e)}")
if websocket.client_state != 0: # 检查连接是否仍然打开
await websocket.close(code=1011, reason="服务器内部错误")
# 启动服务器
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |