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 """ Access Required

🔐 Access to Voice Assistant

This application is protected. Please enter the access key.

""" @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)