Spaces:
Sleeping
Sleeping
| import logging | |
| import os | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import JSONResponse, RedirectResponse | |
| from pathlib import Path | |
| from app.routers import rag | |
| # Setup logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s - %(levelname)s - %(message)s", | |
| handlers=[ | |
| logging.StreamHandler(), | |
| logging.FileHandler("logs/app.log"), | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Create the FastAPI app | |
| app = FastAPI( | |
| title="RAG Research Assistant API", | |
| description="API for a Retrieval Augmented Generation system for research papers", | |
| version="1.0.0", | |
| ) | |
| # Configure CORS settings | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # In production, replace with specific origins | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Include routers | |
| app.include_router(rag.router) | |
| # Root path handler - add this for Hugging Face Spaces | |
| async def root(): | |
| """Root endpoint that redirects to docs""" | |
| return { | |
| "message": "Welcome to the RAG Research Assistant API", | |
| "documentation": "/docs", | |
| "endpoints": { | |
| "rag": "/rag/query", | |
| "health": "/health" | |
| } | |
| } | |
| # Mount static files if frontend exists | |
| frontend_build_path = Path("../frontend/build") | |
| if frontend_build_path.exists(): | |
| app.mount("/static", StaticFiles(directory=str(frontend_build_path)), name="frontend") | |
| async def health_check(): | |
| """Simple health check endpoint""" | |
| return {"status": "healthy"} | |
| async def startup_event(): | |
| """Startup event handler""" | |
| # Ensure logs directory exists | |
| Path("logs").mkdir(exist_ok=True) | |
| logger.info("Application started") | |
| async def shutdown_event(): | |
| """Shutdown event handler""" | |
| logger.info("Application shut down") | |
| if __name__ == "__main__": | |
| import uvicorn | |
| # Determine port from environment or use default | |
| port = int(os.environ.get("PORT", 7860)) | |
| # Run the application using Uvicorn | |
| uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=True) |