File size: 4,706 Bytes
194469b 19ff40b 194469b 19ff40b 194469b 19ff40b 194469b 6968f16 194469b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """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(),
)
|