File size: 1,415 Bytes
f912b02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}