88 lines
2.5 KiB
Python
88 lines
2.5 KiB
Python
"""
|
||
语音交互网页 - 主入口
|
||
"""
|
||
|
||
import os
|
||
import uvicorn
|
||
import aiohttp
|
||
from fastapi import FastAPI
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import FileResponse, Response
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
# 导入后端服务
|
||
from server import app as api_app
|
||
|
||
# 确保音频缓存目录存在
|
||
os.makedirs("audio_cache", exist_ok=True)
|
||
|
||
# 主应用
|
||
app = FastAPI(title="Voice Chat Web")
|
||
|
||
# CORS
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
|
||
# ChatTTS 音频代理(解决 HTTPS 页面访问 HTTP 资源问题)
|
||
@app.get("/chattts/audio/{filename}")
|
||
async def proxy_chattts_audio(filename: str):
|
||
"""代理 ChatTTS 音频文件"""
|
||
chattts_url = os.getenv("CHATTTS_URL", "http://192.168.2.5:12002")
|
||
|
||
try:
|
||
async with aiohttp.ClientSession() as session:
|
||
async with session.get(
|
||
f"{chattts_url}/audio/{filename}",
|
||
timeout=aiohttp.ClientTimeout(total=30)
|
||
) as resp:
|
||
if resp.status != 200:
|
||
return Response(content=b'{"detail":"Audio not found"}', status_code=404, media_type="application/json")
|
||
|
||
audio_data = await resp.read()
|
||
return Response(
|
||
content=audio_data,
|
||
media_type="audio/wav",
|
||
headers={"Cache-Control": "public, max-age=3600"}
|
||
)
|
||
except Exception as e:
|
||
return Response(content=f'{"detail":"{str(e)}"}'.encode(), status_code=500, media_type="application/json")
|
||
|
||
|
||
# 挂载音频文件目录(Edge TTS 生成的 MP3)
|
||
app.mount("/audio", StaticFiles(directory="audio_cache"), name="audio")
|
||
|
||
# 挂载 API
|
||
app.mount("/api", api_app)
|
||
|
||
# 静态文件
|
||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||
|
||
|
||
@app.get("/")
|
||
async def index():
|
||
"""主页(原版)"""
|
||
return FileResponse("static/index.html")
|
||
|
||
|
||
@app.get("/tts")
|
||
async def tts_page():
|
||
"""TTS版本页面"""
|
||
return FileResponse("static/tts.html")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
PORT = int(os.getenv("PORT", "19019"))
|
||
SSL_KEY = os.getenv("SSL_KEY", "key.pem")
|
||
SSL_CERT = os.getenv("SSL_CERT", "cert.pem")
|
||
|
||
# 检查是否有 SSL 证书
|
||
if os.path.exists(SSL_KEY) and os.path.exists(SSL_CERT):
|
||
uvicorn.run(app, host="0.0.0.0", port=PORT, ssl_keyfile=SSL_KEY, ssl_certfile=SSL_CERT)
|
||
else:
|
||
uvicorn.run(app, host="0.0.0.0", port=PORT) |