86 lines
No EOL
2.6 KiB
Python
86 lines
No EOL
2.6 KiB
Python
from fastapi import FastAPI, Request #type: ignore
|
|
from fastapi.middleware.cors import CORSMiddleware #type: ignore
|
|
from fastapi.responses import JSONResponse #type: ignore
|
|
import time
|
|
import uvicorn #type: ignore
|
|
|
|
from .config import settings, connect_to_mongo, close_mongo_connection, connect_to_redis, close_redis_connection
|
|
from .api.v1 import auth, documents, indices, chat, admin
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title="Contract Analysis API",
|
|
description="FastAPI backend for intelligent contract analysis and document Q&A",
|
|
version="2.0.0",
|
|
docs_url="/docs" if settings.debug else None,
|
|
redoc_url="/redoc" if settings.debug else None,
|
|
)
|
|
|
|
# Add CORS middleware
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.cors_origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# Add request timing middleware
|
|
@app.middleware("http")
|
|
async def add_process_time_header(request: Request, call_next):
|
|
start_time = time.time()
|
|
response = await call_next(request)
|
|
process_time = time.time() - start_time
|
|
response.headers["X-Process-Time"] = str(process_time)
|
|
return response
|
|
|
|
# Exception handlers
|
|
@app.exception_handler(Exception)
|
|
async def global_exception_handler(request: Request, exc: Exception):
|
|
if settings.debug:
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"detail": str(exc), "type": type(exc).__name__}
|
|
)
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"detail": "Internal server error"}
|
|
)
|
|
|
|
# Startup and shutdown events
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
await connect_to_mongo()
|
|
await connect_to_redis()
|
|
print("✅ Application startup complete")
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
await close_mongo_connection()
|
|
await close_redis_connection()
|
|
print("✅ Application shutdown complete")
|
|
|
|
# Include routers
|
|
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
|
|
app.include_router(documents.router, prefix="/api/v1/documents", tags=["documents"])
|
|
app.include_router(indices.router, prefix="/api/v1/indices", tags=["indices"])
|
|
app.include_router(chat.router, prefix="/api/v1/chat", tags=["chat"])
|
|
app.include_router(admin.router, prefix="/api/v1/admin", tags=["admin"])
|
|
|
|
# Health check endpoint
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "healthy", "version": "2.0.0"}
|
|
|
|
# Root endpoint
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": "Contract Analysis API", "version": "2.0.0"}
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(
|
|
"app.main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=settings.debug
|
|
) |