refac: audio error handling

This commit is contained in:
Timothy Jaeryang Baek 2025-07-06 14:20:38 +04:00
parent 44754e4c4a
commit 0a1f9966ef

View file

@ -328,6 +328,7 @@ async def speech(request: Request, user=Depends(get_verified_user)):
log.exception(e) log.exception(e)
raise HTTPException(status_code=400, detail="Invalid JSON payload") raise HTTPException(status_code=400, detail="Invalid JSON payload")
r = None
if request.app.state.config.TTS_ENGINE == "openai": if request.app.state.config.TTS_ENGINE == "openai":
payload["model"] = request.app.state.config.TTS_MODEL payload["model"] = request.app.state.config.TTS_MODEL
@ -336,7 +337,7 @@ async def speech(request: Request, user=Depends(get_verified_user)):
async with aiohttp.ClientSession( async with aiohttp.ClientSession(
timeout=timeout, trust_env=True timeout=timeout, trust_env=True
) as session: ) as session:
async with session.post( r = await session.post(
url=f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech", url=f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
json=payload, json=payload,
headers={ headers={
@ -354,14 +355,15 @@ async def speech(request: Request, user=Depends(get_verified_user)):
), ),
}, },
ssl=AIOHTTP_CLIENT_SESSION_SSL, ssl=AIOHTTP_CLIENT_SESSION_SSL,
) as r: )
r.raise_for_status()
async with aiofiles.open(file_path, "wb") as f: r.raise_for_status()
await f.write(await r.read())
async with aiofiles.open(file_body_path, "w") as f: async with aiofiles.open(file_path, "wb") as f:
await f.write(json.dumps(payload)) await f.write(await r.read())
async with aiofiles.open(file_body_path, "w") as f:
await f.write(json.dumps(payload))
return FileResponse(file_path) return FileResponse(file_path)
@ -369,18 +371,18 @@ async def speech(request: Request, user=Depends(get_verified_user)):
log.exception(e) log.exception(e)
detail = None detail = None
try: status_code = 500
if r.status != 200: detail = f"Open WebUI: Server Connection Error"
res = await r.json()
if "error" in res: if r is not None:
detail = f"External: {res['error'].get('message', '')}" status_code = r.status
except Exception: res = await r.json()
detail = f"External: {e}" if "error" in res:
detail = f"External: {res['error'].get('message', '')}"
raise HTTPException( raise HTTPException(
status_code=getattr(r, "status", 500) if r else 500, status_code=status_code,
detail=detail if detail else "Open WebUI: Server Connection Error", detail=detail,
) )
elif request.app.state.config.TTS_ENGINE == "elevenlabs": elif request.app.state.config.TTS_ENGINE == "elevenlabs":