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 StaticFiles

Internal Imports:

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_model

Called By:

  • FastAPI framework (automatic on startup/shutdown)

Calls:

Side Effects:

  • Sets app.state.onnx_model with loaded ONNX inference session
  • Reads ONNX_CHECKPOINT_FILENAME from environment variables
  • Prints startup/shutdown messages to console

Related:


live_signs_ui()

function route get

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:

Related:


favicon()

function route get

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()

function route get

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 ./static directory
  • Accessible at /static/* URLs
  • HTML file serving enabled

Served Files:

Router Inclusion

app.include_router(websocket_router)

Includes:

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

VariableUsageDefault
ONNX_CHECKPOINT_FILENAMEONNX model filename"ONNX_CHECKPOINT_FILENAME"
DOMAIN_NAMECORS allowed origin"DOMAIN_NAME"

State Management

Application State

The application stores the ONNX model in app.state:

app.state.onnx_model: InferenceSession

Set 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

Conceptual:

Source Code:

Frontend:


File Location: src/api/main.py

Lines of Code: 61

Last Updated: 2026-01-27