File size: 2,515 Bytes
eef0607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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.")