Download app.py from michdubai/ddg: direct link, hf CLI and curl.
- Browser
- Download file 3.27 kB
-
https://huggingface.co/spaces/michdubai/ddg/resolve/main/app.py
- Command line
-
hf download hf://spaces/michdubai/ddg/app.py
-
curl -L -o app.py https://huggingface.co/spaces/michdubai/ddg/resolve/main/app.py
3.27 kB
| #!/usr/bin/env python3 | |
| import os | |
| import sys | |
| import re | |
| from fastapi import FastAPI, Query, Response, HTTPException | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import uvicorn | |
| app = FastAPI(title="Secure DuckDuckGo SearXNG Proxy") | |
| def log(message: str): | |
| print(f"[SEARCH-PROXY] {message}", file=sys.stdout, flush=True) | |
| # Secure Token Configuration from HF Secrets | |
| AUTH_TOKEN = os.getenv("INTERNAL_SEARCH_KEY", "your-super-secure-search-password") | |
| def home(): | |
| """Public root landing page.""" | |
| return { | |
| "status": "healthy", | |
| "engine": "DuckDuckGo-SearXNG-Proxy", | |
| "security": "Enabled (Root path locked)" | |
| } | |
| # CRITICAL FIX: Capture the token immediately after the root domain slash | |
| def searxng_compat_endpoint( | |
| token: str, | |
| q: str = Query(None), | |
| format: str = Query("json") | |
| ): | |
| """ | |
| Catches Open WebUI's direct root-level password paths cleanly. | |
| """ | |
| # Validate the token directly | |
| if token != AUTH_TOKEN: | |
| log(f"Unauthorized search attempt rejected. Received token: '{token}' does not match.") | |
| raise HTTPException(status_code=401, detail="Unauthorized: Invalid Token.") | |
| if not q: | |
| return {"results": [], "note": f"Token '{token}' verified successfully. Add 'q' parameter to search."} | |
| log(f"Authorized search request received: '{q}'") | |
| headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", | |
| "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", | |
| "Accept-Language": "en-US,en;q=0.5" | |
| } | |
| url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(q)}" | |
| try: | |
| response = requests.get(url, headers=headers, timeout=5) | |
| if response.status_code != 200: | |
| log(f"Error: DuckDuckGo returned status code {response.status_code}") | |
| return {"results": []} | |
| soup = BeautifulSoup(response.text, "html.parser") | |
| results = [] | |
| for row in soup.find_all('div', class_='result')[:8]: | |
| title_node = row.find('a', class_='result__url') | |
| snippet_node = row.find('a', class_='result__snippet') | |
| if title_node and snippet_node: | |
| raw_url = title_node.get('href', '') | |
| clean_url = raw_url | |
| if "//duckduckgo.com/l/?" in raw_url: | |
| match = re.search(r'uddg=([^&]+)', raw_url) | |
| if match: | |
| clean_url = requests.utils.unquote(match.group(1)) | |
| results.append({ | |
| "title": title_node.text.strip(), | |
| "url": clean_url, | |
| "content": snippet_node.text.strip() | |
| }) | |
| log(f"Successfully returned {len(results)} secured results.") | |
| return {"results": results} | |
| except Exception as e: | |
| log(f"Exception triggered during execution: {str(e)}") | |
| return {"results": []} | |
| if __name__ == "__main__": | |
| port = int(os.getenv("PORT", 7860)) | |
| uvicorn.run(app, host="0.0.0.0", port=port, workers=1) |