source/api/main.py
source-code api fastapi application
File Path: src/api/main.py
Purpose: FastAPI application setup, lifespan management, routing, and middleware configuration.
Overview
This module serves as the main entry point for the FastAPI application. It handles:
- Application lifespan (model loading/cleanup)
- CORS middleware configuration
- Static file serving
- Route definitions for the web interface
Call Graph
graph TD A[FastAPI Framework] --> B[lifespan] B --> C[load_onnx_model] D[Browser GET /] --> E[live_signs_ui] E --> F[FileResponse] G[Browser GET /favicon.ico] --> H[favicon] H --> F I[Chrome DevTools] --> J[chrome_devtools] J --> K[JSONResponse] style B fill:#e1f5ff style E fill:#e1f5ff style H fill:#e1f5ff style J fill:#e1f5ff
Dependencies
import os
from contextlib import asynccontextmanager
import fastapi
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFilesInternal Imports:
- websocket_router from
api.websocket - MODELS_DIR from
core.constants - load_onnx_model from
modelling.model
Functions
lifespan(app: fastapi.FastAPI)
function async context-manager
Type: Async context manager
Purpose: Manages application lifespan - loads ONNX model on startup and cleans up on shutdown.
Parameters:
app(fastapi.FastAPI): The FastAPI application instance
Yields: None (context manager)
Implementation:
@asynccontextmanager
async def lifespan(app: fastapi.FastAPI):
print("Loading model...")
ONNX_CHECKPOINT_FILENAME = (
os.environ.get("ONNX_CHECKPOINT_FILENAME") or "ONNX_CHECKPOINT_FILENAME"
)
onnx_checkpoint_path = os.path.join(MODELS_DIR, ONNX_CHECKPOINT_FILENAME)
app.state.onnx_model = load_onnx_model(onnx_checkpoint_path)
yield
print("Shutting down...")
del app.state.onnx_modelCalled By:
- FastAPI framework (automatic on startup/shutdown)
Calls:
- load_onnx_model() - Loads ONNX model from file
Side Effects:
- Sets
app.state.onnx_modelwith loaded ONNX inference session - Reads
ONNX_CHECKPOINT_FILENAMEfrom environment variables - Prints startup/shutdown messages to console
Related:
- ONNX_CHECKPOINT_FILENAME environment variable
- MODELS_DIR constant
live_signs_ui()
Type: FastAPI route handler
Route: GET / and GET /live-signs
Purpose: Serves the main HTML interface for live sign language recognition.
Parameters: None
Returns: FileResponse - HTML file response
Implementation:
@app.get("/")
@app.get("/live-signs")
async def live_signs_ui():
return FileResponse(os.path.join(static_assets_dir, "index.html"))Called By:
- Browser requests to
/or/live-signs
Calls:
FileResponse()- FastAPI response class
Returns:
- index.html file from static directory
Related:
- index.html - The served HTML file
- Web Interface Design
favicon()
Type: FastAPI route handler
Route: GET /favicon.ico
Purpose: Serves the favicon for the web interface.
Parameters: None
Returns: FileResponse - Favicon file response
Implementation:
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
return FileResponse(
path=os.path.join(static_assets_dir, "mediapipe-logo.ico"),
headers={"Content-Disposition": "attachment; filename=favicon.ico"},
)Called By:
- Browser automatic favicon requests
Calls:
FileResponse()- FastAPI response class
Notes:
- Excluded from API schema (
include_in_schema=False) - Uses MediaPipe logo as favicon
chrome_devtools()
Type: FastAPI route handler
Route: GET /.well-known/appspecific/com.chrome.devtools.json
Purpose: Provides Chrome DevTools configuration endpoint.
Parameters: None
Returns: JSONResponse - Empty JSON object
Implementation:
@app.get("/.well-known/appspecific/com.chrome.devtools.json", include_in_schema=False)
async def chrome_devtools():
return JSONResponse({})Called By:
- Chrome DevTools (automatic)
Calls:
JSONResponse()- FastAPI response class
Notes:
- Excluded from API schema
- Returns empty configuration
Application Configuration
FastAPI App Instance
app = fastapi.FastAPI(lifespan=lifespan)Configuration:
- Uses lifespan() context manager for startup/shutdown
CORS Middleware
origins = [os.environ.get("DOMAIN_NAME") or "DOMAIN_NAME"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)Configuration:
- Allowed origins from DOMAIN_NAME environment variable
- Allows credentials
- Allows all HTTP methods and headers
Related:
Static Files
static_assets_dir = "./static"
app.mount("/static", StaticFiles(directory=static_assets_dir, html=True), name="static")Configuration:
- Serves files from
./staticdirectory - Accessible at
/static/*URLs - HTML file serving enabled
Served Files:
- index.html
- live-signs.js
- styles.css
mediapipe-logo.ico
Router Inclusion
app.include_router(websocket_router)Includes:
- websocket_router - WebSocket routes for live sign detection
Usage
This module is not run directly. Instead, it’s imported by run.py:
# In run.py
uvicorn.run("api.main:app", host="0.0.0.0", port=8000, reload=True)Environment Variables Used
| Variable | Usage | Default |
|---|---|---|
| ONNX_CHECKPOINT_FILENAME | ONNX model filename | "ONNX_CHECKPOINT_FILENAME" |
| DOMAIN_NAME | CORS allowed origin | "DOMAIN_NAME" |
State Management
Application State
The application stores the ONNX model in app.state:
app.state.onnx_model: InferenceSessionSet By: lifespan() Used By: ws_live_signs()
Error Handling
- No explicit error handling in routes
- FastAPI handles exceptions automatically
- Model loading errors will prevent application startup
Related Documentation
Conceptual:
Source Code:
- websocket.py - WebSocket handler
- run.py - Application entry point
- model.py - Model loading functions
- constants.py - Configuration constants
Frontend:
- index.html - Main HTML interface
- live-signs.js - Client-side logic
File Location: src/api/main.py
Lines of Code: 61
Last Updated: 2026-01-27