Spaces:
Sleeping
Sleeping
Download main.py from HFShishir/leaseguard-api: direct link, hf CLI and curl.
- Browser
- Download file 4.03 kB
-
https://huggingface.co/spaces/HFShishir/leaseguard-api/resolve/main/main.py
- Command line
-
hf download hf://spaces/HFShishir/leaseguard-api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/HFShishir/leaseguard-api/resolve/main/main.py
4.03 kB
| import time | |
| import logging | |
| import warnings | |
| import os | |
| # Suppress third-party warnings to clean up backend terminal | |
| warnings.filterwarnings("ignore", category=UserWarning, module="langchain_core") | |
| warnings.filterwarnings("ignore", message=".*Core Pydantic V1.*") | |
| warnings.filterwarnings("ignore", message=".*HF_TOKEN.*") | |
| warnings.filterwarnings("ignore", category=DeprecationWarning) | |
| warnings.filterwarnings("ignore", category=PendingDeprecationWarning) | |
| warnings.filterwarnings("ignore", category=UserWarning) | |
| os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1" | |
| os.environ["TOKENIZERS_PARALLELISM"] = "false" | |
| # Suppress loggers | |
| logging.getLogger("huggingface_hub").setLevel(logging.ERROR) | |
| logging.getLogger("transformers").setLevel(logging.ERROR) | |
| logging.getLogger("sentence_transformers").setLevel(logging.ERROR) | |
| from collections import defaultdict | |
| from fastapi import FastAPI, Request, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from routers import analyze, share, compare, chat, auth | |
| from config import config | |
| from database import init_db | |
| # 1. Structured Logging Configuration | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", | |
| handlers=[logging.StreamHandler()] | |
| ) | |
| logger = logging.getLogger("leaseguard-api") | |
| # Initialize Database Schema | |
| try: | |
| init_db() | |
| logger.info("Database synchronized successfully.") | |
| except Exception as e: | |
| logger.error(f"Database initialization failed: {e}") | |
| # 2. Application Setup | |
| app = FastAPI( | |
| title="LeaseGuard AI API", | |
| description="Production-grade document audit & intelligence engine.", | |
| version="2.0.0", | |
| docs_url="/api/docs", | |
| redoc_url="/api/redoc" | |
| ) | |
| # 3. Security: CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["GET", "POST", "OPTIONS"], | |
| allow_headers=["*"], | |
| ) | |
| # 4. Global Exception Handler | |
| async def global_exception_handler(request: Request, exc: Exception): | |
| logger.exception(f"Unhandled error occurred: {exc}") | |
| return JSONResponse( | |
| status_code=500, | |
| content={"success": False, "detail": "Neural engine encountered an internal fault."} | |
| ) | |
| # 5. Middleware: Efficiency & Privacy | |
| RATE_LIMIT_STORE = defaultdict(list) | |
| RATE_LIMIT_MAX = 60 | |
| RATE_LIMIT_WINDOW = 60 | |
| async def security_and_telemetry(request: Request, call_next): | |
| start_time = time.time() | |
| client_ip = request.client.host | |
| # Rate Limiting (Simple In-Memory) | |
| now = time.time() | |
| RATE_LIMIT_STORE[client_ip] = [t for t in RATE_LIMIT_STORE[client_ip] if now - t < RATE_LIMIT_WINDOW] | |
| if len(RATE_LIMIT_STORE[client_ip]) >= RATE_LIMIT_MAX: | |
| return JSONResponse(status_code=429, content={"detail": "Rate limit exceeded. Slow down."}) | |
| RATE_LIMIT_STORE[client_ip].append(now) | |
| response = await call_next(request) | |
| # Security Headers | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| response.headers["X-Frame-Options"] = "DENY" | |
| response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" | |
| process_time = time.time() - start_time | |
| logger.info(f"REQ: {request.method} {request.url.path} | STATUS: {response.status_code} | {process_time:.3f}s") | |
| return response | |
| # 6. Routers | |
| app.include_router(auth.router) | |
| app.include_router(analyze.router) | |
| app.include_router(share.router) | |
| app.include_router(compare.router) | |
| app.include_router(chat.router) | |
| def health(): | |
| return { | |
| "status": "operational", | |
| "service": "LeaseGuard AI", | |
| "timestamp": time.time() | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| import sys | |
| # Windows reload fix: Ensure standard input is available for the reloader subprocess | |
| if os.name == 'nt' and sys.stdin is None: | |
| sys.stdin = open(os.devnull) | |
| uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True, workers=1) | |