Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from .api.router import api_router | |
| from .api.debug import router as debug_router | |
| def get_application() -> FastAPI: | |
| app = FastAPI( | |
| title="ChatSMITH Backend", | |
| description="FastAPI backend for ChatSMITH pipeline and auth orchestration", | |
| version="0.1.0", | |
| ) | |
| origins = [ | |
| "http://localhost:5173", | |
| "http://127.0.0.1:5173", | |
| ] | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=origins, # use ["*"] for dev if desired | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| app.include_router(api_router, prefix="/api") | |
| app.include_router(debug_router, prefix="/api") | |
| # Serve static files (Frontend) | |
| import os | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| # Determine absolute path to dist folder | |
| # In Docker (WORKDIR /app), this is /app/frontend/dist | |
| # Locally, it depends where we run from. We'll rely on relative path from root. | |
| DIST_DIR = os.path.join(os.getcwd(), "frontend", "dist") | |
| if os.path.exists(DIST_DIR): | |
| app.mount("/assets", StaticFiles(directory=os.path.join(DIST_DIR, "assets")), name="assets") | |
| # Catch-all for SPA routing (must be last) | |
| from fastapi.responses import HTMLResponse | |
| async def serve_spa(full_path: str): | |
| # If API request fell through to here, return 404 | |
| if full_path.startswith("api/"): | |
| return {"detail": "Not Found"} | |
| # Use index.html for all other routes (SPA) | |
| index_path = os.path.join(DIST_DIR, "index.html") | |
| if os.path.exists(index_path): | |
| # READ and INJECT runtime env vars | |
| try: | |
| with open(index_path, "r", encoding="utf-8") as f: | |
| content = f.read() | |
| # Prepare env vars to inject | |
| # Note: We map SECRET env vars to VITE_ PUBLIC vars for the frontend | |
| supabase_url = (os.getenv("SUPABASE_URL") or "").strip() | |
| supabase_key = (os.getenv("SUPABASE_ANON_KEY") or "").strip() | |
| env_script = f""" | |
| <script> | |
| window.__ENV__ = {{ | |
| VITE_SUPABASE_URL: "{supabase_url}", | |
| VITE_SUPABASE_ANON_KEY: "{supabase_key}", | |
| VITE_API_BASE_URL: "/api" | |
| }}; | |
| </script> | |
| """ | |
| # Inject before </head> | |
| content = content.replace("</head>", f"{env_script}</head>") | |
| return HTMLResponse(content=content) | |
| except Exception as e: | |
| print(f"Error serving SPA: {e}") | |
| return FileResponse(index_path) # Fallback | |
| return {"detail": "Frontend not found (build missing)"} | |
| else: | |
| print(f"⚠️ Frontend dist not found at {DIST_DIR}. Serving API only.") | |
| return app | |
| app = get_application() | |
| def health(): | |
| return {"status": "ok", "version": "debug-v2"} | |