File size: 6,091 Bytes
04d62ad | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | from fastapi import FastAPI, HTTPException, Request, UploadFile, File as FastAPIFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import os
import asyncio
from dotenv import load_dotenv
from google import genai
# Import routes
from routes.websocket import router as websocket_router
load_dotenv()
app = FastAPI(title="Gemini Multimodal API")
# --- 1. Get your secret API key ---
APP_API_KEY = os.environ.get("API_KEY", None)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Supported MIME types and extensions for upload validation
SUPPORTED_UPLOAD_MIME_TYPES = {
"application/pdf",
"text/plain",
"text/markdown",
"text/html",
"audio/mpeg",
"audio/mp3",
"audio/wav",
"audio/ogg",
"audio/flac",
"video/mp4",
"video/mpeg",
"video/webm",
"video/quicktime",
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
}
SUPPORTED_UPLOAD_EXTENSIONS = {
".pdf",
".txt",
".md",
".html",
".mp3",
".wav",
".ogg",
".flac",
".mp4",
".mpeg",
".webm",
".mov",
".jpeg",
".jpg",
".png",
".webp",
".gif",
}
# --- 2. A simple, password-protected landing page ---
@app.get("/", response_class=HTMLResponse)
async def landing_page(request: Request):
# If no API key is set in the environment, allow everyone.
if not APP_API_KEY:
return FileResponse("../frontend/index.html")
# Get the key from the URL's query parameters
api_key = request.query_params.get("api_key")
# Check if the provided key is valid
if api_key and api_key == APP_API_KEY:
# Key is valid! Serve the real application.
return FileResponse("../frontend/index.html")
else:
# Key is missing or invalid. Show a simple login page.
return """
<!DOCTYPE html>
<html>
<head>
<title>Access Required</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f0f0f0; }
.card { background: white; padding: 2rem; border-radius: 1rem; box-shadow: 0 4px 6px rgba(0,0,0,0.1); text-align: center; }
input, button { padding: 0.5rem; margin: 0.5rem; font-size: 1rem; }
.error { color: red; }
</style>
</head>
<body>
<div class="card">
<h2>🔐 Access to Voice Assistant</h2>
<p>This application is protected. Please enter the access key.</p>
<input type="password" id="apiKeyInput" placeholder="Enter API Key" autofocus>
<button onclick="login()">Submit</button>
<div id="errorMsg" class="error"></div>
</div>
<script>
function login() {
const key = document.getElementById('apiKeyInput').value;
if (key) {
// Redirect to the same page with the key in the URL
window.location.href = window.location.pathname + '?api_key=' + encodeURIComponent(key);
} else {
document.getElementById('errorMsg').innerText = 'Please enter a key.';
}
}
// Allow pressing "Enter" key to submit
document.getElementById('apiKeyInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') login();
});
</script>
</body>
</html>
"""
@app.post("/api/upload")
async def upload_file(file: UploadFile = FastAPIFile(...)):
"""Upload a file to Gemini Files API and return its reference"""
ext = os.path.splitext(file.filename or "")[1].lower()
mime = file.content_type or "application/octet-stream"
# Strict server-side validation
if ext not in SUPPORTED_UPLOAD_EXTENSIONS and mime not in SUPPORTED_UPLOAD_MIME_TYPES:
raise HTTPException(
status_code=415,
detail=f"Unsupported file type: {ext or mime}. "
f"Supported extensions: {', '.join(SUPPORTED_UPLOAD_EXTENSIONS)}",
)
try:
contents = await file.read()
if len(contents) == 0:
raise HTTPException(status_code=400, detail="Empty file")
api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
if not api_key:
raise HTTPException(status_code=500, detail="API key not configured")
temp_client = genai.Client(api_key=api_key)
# Run sync SDK upload in threadpool to avoid blocking event loop
file_obj = await asyncio.to_thread(
temp_client.files.upload,
file=contents,
config={"mime_type": mime},
)
return JSONResponse(
{
"success": True,
"uri": file_obj.uri,
"mime_type": file_obj.mime_type or mime,
"name": getattr(file_obj, "name", file.filename),
"size": len(contents),
}
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
# --- 3. Mount static files (these are now "inside" the protected zone) ---
# Users must have a valid key to load CSS, JS, etc., because these routes are checked by the middleware.
app.mount("/static", StaticFiles(directory="../frontend"), name="static")
# --- 4. Your existing WebSocket route (already protected by your previous logic) ---
app.include_router(websocket_router)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
|