yashasvi0409/Document_Intelligence
0
1# app/api.py ✅ (FULL UPDATED FILE)2# Works for BOTH cases:3# 1) Backend-only (Hugging Face Spaces) -> "/" returns JSON + use "/docs"4# 2) Backend + Frontend together -> serves index.html/answer.html if frontend folder exists5 6import os7from pathlib import Path8 9from fastapi import FastAPI, HTTPException10from fastapi.staticfiles import StaticFiles11from fastapi.responses import FileResponse, JSONResponse12from fastapi.middleware.cors import CORSMiddleware13 14# ✅ Router factory (must exist)15from routes import create_routes16 17# ✅ Vector store builder (must exist)18from vector_store import get_vector_store19 20 21BASE_DIR = Path(__file__).resolve().parent # .../app22PROJECT_DIR = BASE_DIR.parent # project root23 24# Try common folder names (your screenshots show "Frontend" sometimes)25FRONTEND_DIR_CANDIDATES = [26 PROJECT_DIR / "Frontend",27 PROJECT_DIR / "frontend",28 BASE_DIR / "Frontend",29 BASE_DIR / "frontend",30]31 32FRONTEND_DIR = next((p for p in FRONTEND_DIR_CANDIDATES if p.exists()), None)33 34app = FastAPI(title="Document Intelligence API")35 36# ✅ CORS (fine for demo; lock later)37app.add_middleware(38 CORSMiddleware,39 allow_origins=["*"],40 allow_credentials=True,41 allow_methods=["*"],42 allow_headers=["*"],43)44 45# -------------------------46# Health check47# -------------------------48@app.get("/health")49def health():50 return {"status": "ok"}51 52# -------------------------53# Serve frontend ONLY if folder exists54# -------------------------55if FRONTEND_DIR:56 # Serve static files (css/js/images) from the frontend folder57 # NOTE: Your HTML uses: <link rel="stylesheet" href="style.css">58 # That means index.html expects style.css in same directory.59 # So mounting "/" to that directory is the simplest.60 app.mount("/", StaticFiles(directory=str(FRONTEND_DIR), html=True), name="frontend")61 62 # Optional explicit routes (not required because html=True already serves index.html)63 @app.get("/index.html")64 def index_html():65 return FileResponse(str(FRONTEND_DIR / "index.html"))66 67 @app.get("/answer.html")68 def answer_html():69 return FileResponse(str(FRONTEND_DIR / "answer.html"))70 71else:72 # Backend-only mode (Hugging Face friendly)73 @app.get("/")74 def root():75 return JSONResponse(76 {77 "message": "Backend is running ✅",78 "hint": "Open /docs to test the API.",79 }80 )81 82# -------------------------83# Build vector store ONCE, with clear error if it fails84# -------------------------85try:86 vector_store = get_vector_store()87except Exception as e:88 # This makes the failure obvious in logs and avoids silent 500s89 raise RuntimeError(f"Vector store initialization failed: {e}")90 91# ✅ Register routes92# (create_routes should return an APIRouter with /ask-recruiter etc.)93app.include_router(create_routes(vector_store))