Download application.py from Muxperts/Rankmate: direct link, hf CLI and curl.
- Browser
- Download file 4.49 kB
-
https://huggingface.co/spaces/Muxperts/Rankmate/resolve/main/application.py
- Command line
-
hf download hf://spaces/Muxperts/Rankmate/application.py
-
curl -L -o application.py https://huggingface.co/spaces/Muxperts/Rankmate/resolve/main/application.py
4.49 kB
| import os | |
| import socket | |
| import webbrowser | |
| import time | |
| import uvicorn | |
| import secrets | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI | |
| from fastapi.staticfiles import StaticFiles | |
| from threading import Thread | |
| # --- Security & Sessions --- | |
| from starlette.middleware.sessions import SessionMiddleware | |
| # β FIX: Add Proxy Middleware import | |
| from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware | |
| # Import database instance | |
| from database.db_connection import db_instance | |
| # Import custom utilities | |
| try: | |
| from src.utils import start_periodic_cleanup, cleanup_artifacts_directory | |
| except ImportError as e: | |
| print(f"β [STARTUP ERROR] Failed to import modules: {e}") | |
| raise | |
| # --- Import Routers from the 'api' folder --- | |
| from api.routes import router as api_router | |
| from api.auth import router as auth_router | |
| from api.ui import router as ui_router | |
| # Define lifespan for startup and shutdown events | |
| async def lifespan(app: FastAPI): | |
| print("\n" + "="*60) | |
| print("π’ [LIFECYCLE] Starting up application lifecycle...") | |
| try: | |
| print("π’ [DATABASE] Attempting to connect to MongoDB...") | |
| db_instance.connect() | |
| print("β [DATABASE] MongoDB connection successful.") | |
| except Exception as e: | |
| print(f"β [DATABASE] Connection failed on startup: {e}") | |
| print("π’ [BACKGROUND] Initializing periodic cleanup tasks...") | |
| start_periodic_cleanup() | |
| print("π’ [BACKGROUND] Cleaning up legacy artifacts directory...") | |
| cleanup_artifacts_directory() | |
| print("β [LIFECYCLE] Application startup complete.") | |
| print("="*60 + "\n") | |
| yield | |
| print("\n" + "="*60) | |
| print("π΄ [LIFECYCLE] Shutting down application lifecycle...") | |
| print("π΄ [DATABASE] Closing MongoDB database connection...") | |
| db_instance.close() | |
| print("β [LIFECYCLE] Application shutdown complete.") | |
| print("="*60 + "\n") | |
| # Initialize FastAPI app | |
| app = FastAPI(title="Student Performance Analyzer", lifespan=lifespan) | |
| # Fetch the secret key (Emergency Fix: Removed hardcoded fallback) | |
| SECRET_KEY = os.environ.get("SECRET_KEY") | |
| if not SECRET_KEY: | |
| print("β οΈ [SECURITY] SECRET_KEY environment variable is missing. Using a volatile random key.") | |
| SECRET_KEY = secrets.token_hex(32) | |
| # Session middleware (Emergency Fix: https_only must be a boolean, not a string) | |
| app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, same_site="none", https_only=True) | |
| app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*") | |
| # Static files | |
| app.mount("/static", StaticFiles(directory="static"), name="static") | |
| # Routers | |
| print("π’ [ROUTING] Mounting application routers (auth, ui, api)...") | |
| app.include_router(auth_router) | |
| app.include_router(ui_router) | |
| app.include_router(api_router) | |
| async def health(): | |
| return {"status": "healthy"} | |
| def find_free_port(): | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| s.bind(('', 0)) | |
| s.listen(1) | |
| port = s.getsockname()[1] | |
| return port | |
| def is_port_available(port): | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
| try: | |
| s.bind(('', port)) | |
| return True | |
| except socket.error: | |
| return False | |
| if __name__ == "__main__": | |
| port = 8000 | |
| if not is_port_available(port): | |
| port = find_free_port() | |
| print("=" * 60) | |
| print(f"β οΈ [SERVER] PORT 8000 WAS ALREADY IN USE. Using alternative port: {port}") | |
| print("=" * 60) | |
| print("=" * 60) | |
| print(f"π [SERVER] Student Performance Analyzer is starting!") | |
| print(f"π [SERVER] Opening browser at: http://localhost:{port}") | |
| print("=" * 60) | |
| def open_browser(): | |
| time.sleep(2) | |
| try: | |
| webbrowser.open_new(f"http://localhost:{port}") | |
| print("β [BROWSER] Browser opened successfully") | |
| except Exception as e: | |
| print(f"β [BROWSER] Could not open browser automatically: {e}") | |
| browser_thread = Thread(target=open_browser, daemon=True) | |
| browser_thread.start() | |
| try: | |
| print("π’ [SERVER] Starting Uvicorn server...") | |
| uvicorn.run("application:app", host="127.0.0.1", port=port, log_level="warning", reload=True) | |
| except KeyboardInterrupt: | |
| print("\nπ [SERVER] Server stopped by user (KeyboardInterrupt)") | |
| except Exception as e: | |
| print(f"\nβ [SERVER] Application crash: {e}") |