import os import requests from fastapi import FastAPI, Form from fastapi.responses import JSONResponse app = FastAPI() # Secret key from Hugging Face Space -> Settings -> Variables and secrets SECRET_API_KEY = os.getenv("SECRET_API_KEY", "changeme") @app.post("/autocomplete") async def autocomplete(text: str = Form(...), api_key: str = Form(...)): # 🔑 Validate API key if api_key != SECRET_API_KEY: return JSONResponse( status_code=403, content={"status": False, "body": "Invalid API key."} ) # 📝 Validate input if not text.strip(): return JSONResponse( status_code=400, content={"status": False, "body": "Missing 'text' parameter."} ) try: url = f"https://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q={requests.utils.quote(text)}" resp = requests.get(url, timeout=5) if resp.status_code != 200: return {"status": False, "body": f"YouTube request failed: {resp.status_code}"} data = resp.json() if not isinstance(data, list) or len(data) < 2: return {"status": False, "body": "Invalid response format from YouTube"} suggestions = data[1] # second element is suggestion array return {"status": True, "body": suggestions} except Exception as e: return {"status": False, "body": str(e)}