import os import httpx from fastapi import FastAPI, Request, HTTPException from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # Configuration # On HF Spaces, set GEMINI_API_KEY in the "Settings" -> "Repository secrets" tab API_KEY = os.getenv("GEMINI_API_KEY") # Enable CORS (Optional if serving from same origin, but good for dev) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) @app.post("/api/generate") async def proxy_generate(request: Request): if not API_KEY: raise HTTPException(status_code=500, detail="GEMINI_API_KEY not set on server.") try: # 1. Get the JSON payload from the React Frontend body = await request.json() # 2. Forward to Google Gemini API # We use the specific model version defined in your frontend code logic url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key={API_KEY}" async with httpx.AsyncClient(timeout=60.0) as client: response = await client.post( url, json=body, headers={"Content-Type": "application/json"} ) # 3. Return Google's response back to Frontend if response.status_code != 200: return JSONResponse(status_code=response.status_code, content=response.json()) return response.json() except Exception as e: print(f"Error: {e}") raise HTTPException(status_code=500, detail=str(e)) # Serve React App (After building) # We expect the React build output to be in a 'dist' folder if os.path.exists("dist"): app.mount("/assets", StaticFiles(directory="dist/assets"), name="assets") @app.get("/{catchall:path}") async def serve_react(catchall: str): # Serve index.html for any path not matched by API or assets # This handles client-side routing if you add it later if "." in catchall: # If asking for a file (e.g. favicon.ico) try to find it if os.path.exists(f"dist/{catchall}"): return FileResponse(f"dist/{catchall}") return FileResponse("dist/index.html") else: print("Warning: 'dist' folder not found. React frontend will not be served.")