ziadalaa7/Fake_Image_Detection
0
1"""
2FastAPI Application Entry Point.
3Main application factory and configuration.
4
5This module initializes the FastAPI application with middleware,
6routes, and global exception handlers.
7"""
8
9from fastapi import FastAPI, Request
10from fastapi.middleware.cors import CORSMiddleware
11from fastapi.responses import JSONResponse
12from fastapi.openapi.utils import get_openapi
13import logging
14
15# Import configuration and routes
16from core.config import (
17 PROJECT_NAME,
18 PROJECT_VERSION,
19 PROJECT_DESCRIPTION,
20 API_V1_STR,
21 CORS_ORIGINS
22)
23from api.routes import router as api_router
24
25# Configure logging
26logging.basicConfig(
27 level=logging.INFO,
28 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
29)
30logger = logging.getLogger(__name__)
31
32
33def create_app() -> FastAPI:
34 """
35 Create and configure the FastAPI application.
36
37 Returns:
38 FastAPI: Configured FastAPI application instance.
39 """
40
41 # Initialize FastAPI app
42 app = FastAPI(
43 title=PROJECT_NAME,
44 description=PROJECT_DESCRIPTION,
45 version=PROJECT_VERSION,
46 docs_url="/api/docs", # Swagger UI
47 redoc_url="/api/redoc", # ReDoc
48 openapi_url="/api/openapi.json"
49 )
50
51 # Add CORS middleware
52 app.add_middleware(
53 CORSMiddleware,
54 allow_origins=CORS_ORIGINS,
55 allow_credentials=True,
56 allow_methods=["*"],
57 allow_headers=["*"],
58 )
59
60 # Include API routes
61 app.include_router(api_router)
62
63 # Root endpoint
64 @app.get("/", tags=["Root"])
65 async def root():
66 """Root endpoint with API information."""
67 return {
68 "name": PROJECT_NAME,
69 "version": PROJECT_VERSION,
70 "description": PROJECT_DESCRIPTION,
71 "docs": "/api/docs",
72 "health": "/api/v1/health",
73 "predict": "/api/v1/predict"
74 }
75
76 # Global exception handler
77 @app.exception_handler(Exception)
78 async def global_exception_handler(request: Request, exc: Exception):
79 """Handle all unhandled exceptions."""
80 logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
81 return JSONResponse(
82 status_code=500,
83 content={
84 "error": "Internal server error",
85 "status_code": 500,
86 "details": str(exc)
87 }
88 )
89
90 # Startup event
91 @app.on_event("startup")
92 async def startup_event():
93 """Execute on application startup."""
94 logger.info(f"๐ Starting {PROJECT_NAME} v{PROJECT_VERSION}")
95 logger.info("๐ฆ Loading ML model...")
96 try:
97 from services.model_service import get_model_service
98 model_service = get_model_service()
99 logger.info("โ
ML model loaded successfully!")
100 except Exception as e:
101 logger.error(f"โ Failed to load model: {str(e)}")
102 raise
103
104 # Shutdown event
105 @app.on_event("shutdown")
106 async def shutdown_event():
107 """Execute on application shutdown."""
108 logger.info(f"๐ Shutting down {PROJECT_NAME}")
109
110 return app
111
112
113# Create the FastAPI application instance
114app = create_app()
115
116
117if __name__ == "__main__":
118 import uvicorn
119
120 uvicorn.run(
121 "main:app",
122 host="0.0.0.0",
123 port=7860,
124 reload=False,
125 log_level="info"
126 )