Absboy's picture
Update main.py
b454051 verified
Raw History Blame Contribute Delete
2.28 kB
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.responses import HTMLResponse, Response
import uvicorn
import asyncio
import os
app = FastAPI()
# In-memory binary storage for performance
latest_frame_bytes = b""
viewers = set()
@app.websocket("/ws/client")
async def client_endpoint(websocket: WebSocket):
global latest_frame_bytes
await websocket.accept()
try:
while True:
# Receive image data as binary bytes (faster than base64)
data = await websocket.receive_bytes()
latest_frame_bytes = data
# Broadcast binary to all connected viewers
if viewers:
await asyncio.gather(
*[viewer.send_bytes(data) for viewer in viewers],
return_exceptions=True
)
except WebSocketDisconnect:
print("Client disconnected")
@app.websocket("/ws/admin")
async def admin_endpoint(websocket: WebSocket):
await websocket.accept()
viewers.add(websocket)
try:
if latest_frame_bytes:
await websocket.send_bytes(latest_frame_bytes)
while True:
# Just to keep the connection alive
await websocket.receive_text()
except WebSocketDisconnect:
viewers.discard(websocket)
print("Admin disconnected")
# --- REST API Endpoints ---
@app.post("/api/upload")
async def upload_frame(request: Request):
"""API endpoint to upload a frame via POST request"""
global latest_frame_bytes
data = await request.body()
latest_frame_bytes = data
if viewers:
for viewer in viewers:
try:
await viewer.send_bytes(data)
except:
pass
return {"status": "success"}
@app.get("/api/view")
async def view_frame():
"""API endpoint to view the latest frame as a direct image"""
if latest_frame_bytes:
return Response(content=latest_frame_bytes, media_type="image/jpeg")
return {"error": "no frame available"}
@app.get("/")
async def get():
with open("index.html", "r") as f:
return HTMLResponse(f.read())
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)