Update app.py
Browse files
app.py
CHANGED
|
@@ -1,51 +1,111 @@
|
|
| 1 |
-
import os, json, time
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
from fastapi
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
app
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
with EVENTS.open("a", encoding="utf-8") as f:
|
| 19 |
-
f.write(json.dumps(ev, ensure_ascii=False) + "\n")
|
| 20 |
|
| 21 |
@app.get("/health")
|
| 22 |
-
|
| 23 |
-
return {
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
while True:
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, json, asyncio, time
|
| 2 |
+
from typing import Optional
|
| 3 |
+
import httpx
|
| 4 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Body
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from fastapi.responses import JSONResponse
|
| 7 |
+
|
| 8 |
+
FILES_DIR = os.environ.get("FILES_DIR", "/tmp/brain_app/files")
|
| 9 |
+
TTS_WS_TARGET = os.environ.get("TTS_WS_TARGET", "")
|
| 10 |
+
TTS_HTTP_TARGET = os.environ.get("TTS_HTTP_TARGET", "")
|
| 11 |
+
STT_WS_TARGET = os.environ.get("STT_WS_TARGET", "")
|
| 12 |
+
|
| 13 |
+
app = FastAPI(title="Brain Proxy")
|
| 14 |
+
app.add_middleware(
|
| 15 |
+
CORSMiddleware,
|
| 16 |
+
allow_origins=[""], allow_headers=[""], allow_methods=["*"], allow_credentials=True,
|
| 17 |
+
)
|
|
|
|
|
|
|
| 18 |
|
| 19 |
@app.get("/health")
|
| 20 |
+
def health():
|
| 21 |
+
return {
|
| 22 |
+
"ok": True,
|
| 23 |
+
"service": "brain",
|
| 24 |
+
"files_dir": FILES_DIR,
|
| 25 |
+
"tts_ws_target": TTS_WS_TARGET,
|
| 26 |
+
"tts_http_target": TTS_HTTP_TARGET,
|
| 27 |
+
"stt_ws_target": STT_WS_TARGET,
|
| 28 |
+
"time": time.time(),
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
# ---------- HTTP proxy to TTS /speak ----------
|
| 32 |
+
@app.post("/speak")
|
| 33 |
+
async def speak_proxy(body: dict = Body(...)):
|
| 34 |
+
if not TTS_HTTP_TARGET:
|
| 35 |
+
return JSONResponse({"ok": False, "error": "TTS HTTP target not configured"}, 500)
|
| 36 |
+
try:
|
| 37 |
+
async with httpx.AsyncClient(timeout=60) as client:
|
| 38 |
+
r = await client.post(TTS_HTTP_TARGET, json=body)
|
| 39 |
+
r.raise_for_status()
|
| 40 |
+
return JSONResponse(r.json(), r.status_code)
|
| 41 |
+
except httpx.HTTPError as e:
|
| 42 |
+
return JSONResponse({"ok": False, "error": f"TTS proxy failed: {e}"}, 502)
|
| 43 |
+
|
| 44 |
+
# ---------- WS proxy helpers ----------
|
| 45 |
+
async def _bridge_ws(client_ws: WebSocket, upstream_url: str):
|
| 46 |
+
import websockets
|
| 47 |
+
|
| 48 |
+
# Establish upstream connection
|
| 49 |
+
try:
|
| 50 |
+
upstream = await websockets.connect(upstream_url, ping_interval=None, max_size=8_000_000)
|
| 51 |
+
except Exception as e:
|
| 52 |
+
await client_ws.send_json({"event":"error","error":f"Upstream connect failed: {repr(e)}"})
|
| 53 |
+
await client_ws.close()
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
async def c2u():
|
| 57 |
+
# client -> upstream (pass text or bytes)
|
| 58 |
+
try:
|
| 59 |
while True:
|
| 60 |
+
msg = await client_ws.receive()
|
| 61 |
+
if "bytes" in msg and msg["bytes"] is not None:
|
| 62 |
+
await upstream.send(msg["bytes"])
|
| 63 |
+
elif "text" in msg and msg["text"] is not None:
|
| 64 |
+
await upstream.send(msg["text"])
|
| 65 |
+
else:
|
| 66 |
+
# ignore pings/others
|
| 67 |
+
pass
|
| 68 |
+
except WebSocketDisconnect:
|
| 69 |
+
pass
|
| 70 |
+
finally:
|
| 71 |
+
try:
|
| 72 |
+
await upstream.close()
|
| 73 |
+
except Exception:
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
async def u2c():
|
| 77 |
+
# upstream -> client (pass text or binary)
|
| 78 |
+
try:
|
| 79 |
+
while True:
|
| 80 |
+
msg = await upstream.recv()
|
| 81 |
+
if isinstance(msg, (bytes, bytearray)):
|
| 82 |
+
await client_ws.send_bytes(msg)
|
| 83 |
+
else:
|
| 84 |
+
await client_ws.send_text(msg)
|
| 85 |
+
except Exception:
|
| 86 |
+
pass
|
| 87 |
+
finally:
|
| 88 |
+
try:
|
| 89 |
+
await client_ws.close()
|
| 90 |
+
except Exception:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
# run both directions
|
| 94 |
+
await asyncio.gather(c2u(), u2c())
|
| 95 |
+
|
| 96 |
+
# ---------- WS endpoints the client will use ----------
|
| 97 |
+
@app.websocket("/ws/tts_proxy")
|
| 98 |
+
async def ws_tts_proxy(ws: WebSocket):
|
| 99 |
+
await ws.accept()
|
| 100 |
+
if not TTS_WS_TARGET:
|
| 101 |
+
await ws.send_json({"event":"error","error":"TTS WS target not configured"})
|
| 102 |
+
await ws.close(); return
|
| 103 |
+
await _bridge_ws(ws, TTS_WS_TARGET)
|
| 104 |
+
|
| 105 |
+
@app.websocket("/ws/stt_proxy")
|
| 106 |
+
async def ws_stt_proxy(ws: WebSocket):
|
| 107 |
+
await ws.accept()
|
| 108 |
+
if not STT_WS_TARGET:
|
| 109 |
+
await ws.send_json({"event":"error","error":"STT WS target not configured"})
|
| 110 |
+
await ws.close(); return
|
| 111 |
+
await _bridge_ws(ws, STT_WS_TARGET)
|