facerecog / app.py
kamau1's picture
Enhanced the documentation by addign a quickstart and also debugging the swagger ui
6968f16
Raw History Blame Contribute Delete
4.71 kB
"""FastAPI Face Recognition API main application."""
import logging
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import AsyncGenerator
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from config import settings
from database import supabase_client
from exceptions import (
BaseAPIException,
base_api_exception_handler,
general_exception_handler,
)
from models import HealthCheck
# Configure logging
logging.basicConfig(
level=getattr(logging, settings.LOG_LEVEL.upper()),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator[None, None]:
"""Application lifespan manager."""
# Startup
logger.info("Starting Face Recognition API...")
# Test database connection
try:
is_healthy = await supabase_client.health_check()
if is_healthy:
logger.info("Database connection established successfully")
else:
logger.warning("Database connection test failed")
except Exception as e:
logger.error(f"Database connection error: {e}")
logger.info("Application startup complete")
yield
# Shutdown
logger.info("Shutting down Face Recognition API...")
# Create FastAPI app
app_config = {
"title": settings.APP_NAME,
"version": settings.APP_VERSION,
"description": "A FastAPI application for face recognition using DeepFace and Supabase",
"lifespan": lifespan,
}
# Hide docs in production
if not settings.SHOW_DOCS:
app_config["openapi_url"] = None
app_config["docs_url"] = None
app_config["redoc_url"] = None
app = FastAPI(**app_config)
# Configure templates and static files
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
allow_methods=settings.CORS_ALLOW_METHODS,
allow_headers=settings.CORS_ALLOW_HEADERS,
)
# Add exception handlers
app.add_exception_handler(BaseAPIException, base_api_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log all HTTP requests."""
start_time = datetime.now(timezone.utc)
# Log request
logger.info(
f"Request: {request.method} {request.url.path} "
f"from {request.client.host if request.client else 'unknown'}"
)
# Process request
response = await call_next(request)
# Calculate duration
duration = (datetime.now(timezone.utc) - start_time).total_seconds()
# Log response
logger.info(
f"Response: {response.status_code} for {request.method} {request.url.path} "
f"in {duration:.3f}s"
)
return response
@app.get("/", include_in_schema=False)
async def root(request: Request):
"""Serve the main HTML page."""
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/quickstart", include_in_schema=False)
async def quickstart(request: Request):
"""Serve the quickstart HTML page."""
return templates.TemplateResponse("quickstart.html", {"request": request})
@app.get("/health", response_model=HealthCheck, tags=["Health"])
async def health_check() -> HealthCheck:
"""Health check endpoint."""
# Test database connection
try:
is_db_healthy = await supabase_client.health_check()
status = "healthy" if is_db_healthy else "degraded"
except Exception:
status = "unhealthy"
return HealthCheck(
status=status,
timestamp=datetime.now(timezone.utc),
version=settings.APP_VERSION,
environment=settings.ENVIRONMENT,
)
# Import and include routers
# Note: Import here to avoid circular imports
try:
from faces.router import router as faces_router
app.include_router(
faces_router,
prefix="/api/v1/faces",
tags=["Face Recognition"],
)
logger.info("Face recognition routes registered")
except ImportError as e:
logger.warning(f"Could not import face recognition routes: {e}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.RELOAD and settings.is_development,
log_level=settings.LOG_LEVEL.lower(),
)