Download backend/app.py from michdubai/audio: direct link, hf CLI and curl.
- Browser
- Download file 6.09 kB
-
https://huggingface.co/spaces/michdubai/audio/resolve/main/backend/app.py
- Command line
-
hf download hf://spaces/michdubai/audio/backend/app.py
-
curl -L -o app.py https://huggingface.co/spaces/michdubai/audio/resolve/main/backend/app.py
6.09 kB
| 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 --- | |
| 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> | |
| """ | |
| 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) | |