Spaces:
Sleeping
Sleeping
add audio api
Browse files
app.py
CHANGED
|
@@ -1,10 +1,12 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import JSONResponse
|
| 4 |
from utils.validators import ChatRequest, ChatResponse
|
| 5 |
from utils.logger import log
|
| 6 |
from modules.travel_assistant import TravelAssistant
|
| 7 |
import traceback
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# --- FastAPI 应用设置 ---
|
| 10 |
app = FastAPI(
|
|
@@ -146,6 +148,57 @@ async def reset_session(session_id: str):
|
|
| 146 |
detail="Failed to reset session"
|
| 147 |
)
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
@app.get("/api/debug/sessions")
|
| 150 |
async def debug_sessions():
|
| 151 |
"""调试:查看所有会话状态"""
|
|
@@ -198,6 +251,8 @@ async def cleanup_sessions(max_age_hours: int = 24):
|
|
| 198 |
except Exception as e:
|
| 199 |
log.error(f"❌ Cleanup error: {e}")
|
| 200 |
raise HTTPException(status_code=500, detail="Failed to cleanup sessions")
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# --- 全局异常处理 ---
|
| 203 |
@app.exception_handler(Exception)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, UploadFile
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from fastapi.responses import JSONResponse
|
| 4 |
from utils.validators import ChatRequest, ChatResponse
|
| 5 |
from utils.logger import log
|
| 6 |
from modules.travel_assistant import TravelAssistant
|
| 7 |
import traceback
|
| 8 |
+
import tempfile
|
| 9 |
+
import shutil
|
| 10 |
|
| 11 |
# --- FastAPI 应用设置 ---
|
| 12 |
app = FastAPI(
|
|
|
|
| 148 |
detail="Failed to reset session"
|
| 149 |
)
|
| 150 |
|
| 151 |
+
@app.post("/api/transcribe-audio")
|
| 152 |
+
async def transcribe_audio_endpoint(file: UploadFile = File(...)):
|
| 153 |
+
"""
|
| 154 |
+
接收音频文件,进行语音转文本,并返回转录结果。
|
| 155 |
+
"""
|
| 156 |
+
# 1. 检查核心服务是否就绪
|
| 157 |
+
if not SERVICE_READY or not assistant:
|
| 158 |
+
raise HTTPException(
|
| 159 |
+
status_code=503,
|
| 160 |
+
detail="Service Unavailable: Backend assistant failed to initialize."
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# 2. 检查上传的是否是音频文件 (基础检查)
|
| 164 |
+
if not file.content_type.startswith("audio/"):
|
| 165 |
+
raise HTTPException(
|
| 166 |
+
status_code=400,
|
| 167 |
+
detail=f"Invalid file type: {file.content_type}. Please upload an audio file."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
tmp_path = None
|
| 171 |
+
try:
|
| 172 |
+
# 3. 创建一个带正确后缀的临时文件,以便模型能识别
|
| 173 |
+
# 例如,如果上传 a.wav, 临时文件也会是 xxx.wav
|
| 174 |
+
suffix = os.path.splitext(file.filename)[1]
|
| 175 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 176 |
+
# 将上传的文件内容写入临时文件
|
| 177 |
+
shutil.copyfileobj(file.file, tmp)
|
| 178 |
+
tmp_path = tmp.name
|
| 179 |
+
|
| 180 |
+
log.info(f"音频文件已临时保存到: {tmp_path}")
|
| 181 |
+
|
| 182 |
+
# 4. 调用 TravelAssistant 中的转录方法
|
| 183 |
+
transcribed_text = assistant.transcribe_audio(audio_path=tmp_path)
|
| 184 |
+
|
| 185 |
+
log.info(f"音频转录成功,内容: {transcribed_text[:50]}...")
|
| 186 |
+
|
| 187 |
+
# 5. 将转录文本作为 JSON 返回
|
| 188 |
+
return {"transcription": transcribed_text}
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
log.error(f"❌ Audio transcription error: {e}", exc_info=True)
|
| 192 |
+
raise HTTPException(
|
| 193 |
+
status_code=500,
|
| 194 |
+
detail="Internal Server Error: Failed to transcribe audio."
|
| 195 |
+
)
|
| 196 |
+
finally:
|
| 197 |
+
# 6. 无论成功与否,都确保清理临时文件
|
| 198 |
+
if tmp_path and os.path.exists(tmp_path):
|
| 199 |
+
os.remove(tmp_path)
|
| 200 |
+
log.info(f"临时文件已清理: {tmp_path}")
|
| 201 |
+
|
| 202 |
@app.get("/api/debug/sessions")
|
| 203 |
async def debug_sessions():
|
| 204 |
"""调试:查看所有会话状态"""
|
|
|
|
| 251 |
except Exception as e:
|
| 252 |
log.error(f"❌ Cleanup error: {e}")
|
| 253 |
raise HTTPException(status_code=500, detail="Failed to cleanup sessions")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
|
| 257 |
# --- 全局异常处理 ---
|
| 258 |
@app.exception_handler(Exception)
|