cazyundee commited on
Commit
84090f0
·
verified ·
1 Parent(s): f0a025b

Add SearXNG search resource

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py CHANGED
@@ -3,6 +3,9 @@ import platform
3
  import sys
4
  import shutil
5
  import tempfile
 
 
 
6
  import torch
7
  import spaces
8
  import torchaudio
@@ -12,6 +15,9 @@ from einops import rearrange
12
  from huggingface_hub import login
13
  from stable_audio_3 import StableAudioModel
14
  from contextlib import asynccontextmanager
 
 
 
15
 
16
  for _stream in (sys.stdout, sys.stderr):
17
  if hasattr(_stream, "reconfigure"):
@@ -141,6 +147,18 @@ API_RESOURCES = {
141
  "model": "small-music | small-sfx",
142
  },
143
  "output": "WAV audio file",
 
 
 
 
 
 
 
 
 
 
 
 
144
  }
145
  }
146
 
@@ -189,6 +207,84 @@ def _get_runtime_specs():
189
  }
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  # ---------------------------------------------------------------------------
193
  # Model cache
194
  # ---------------------------------------------------------------------------
@@ -289,6 +385,16 @@ def _patched_create_app(blocks, **kwargs):
289
  def _specs():
290
  return JSONResponse({**API_SPECS, "runtime": _get_runtime_specs()})
291
 
 
 
 
 
 
 
 
 
 
 
292
  _log("Respite API discovery routes injected")
293
  return fa_app
294
 
 
3
  import sys
4
  import shutil
5
  import tempfile
6
+ import subprocess
7
+ import time
8
+ import threading
9
  import torch
10
  import spaces
11
  import torchaudio
 
15
  from huggingface_hub import login
16
  from stable_audio_3 import StableAudioModel
17
  from contextlib import asynccontextmanager
18
+ import urllib.request
19
+ import urllib.parse
20
+ import json as _json
21
 
22
  for _stream in (sys.stdout, sys.stderr):
23
  if hasattr(_stream, "reconfigure"):
 
147
  "model": "small-music | small-sfx",
148
  },
149
  "output": "WAV audio file",
150
+ },
151
+ "web_search": {
152
+ "name": "Web search",
153
+ "description": "Search the web using a self-hosted SearXNG metasearch engine.",
154
+ "endpoint": "/respite/search",
155
+ "method": "GET",
156
+ "input": {
157
+ "q": "string (search query)",
158
+ "categories": "string (general, images, news, etc.)",
159
+ "max_results": "integer (1-50, default 10)",
160
+ },
161
+ "output": "JSON with title, url, content, engine, score per result",
162
  }
163
  }
164
 
 
207
  }
208
 
209
 
210
+ # ---------------------------------------------------------------------------
211
+ # SearXNG local instance
212
+ # ---------------------------------------------------------------------------
213
+
214
+ SEARXNG_PORT = 8888
215
+ SEARXNG_BASE = f"http://127.0.0.1:{SEARXNG_PORT}"
216
+ _searxng_process = None
217
+
218
+
219
+ def _start_searxng():
220
+ """Start SearXNG as a background subprocess."""
221
+ global _searxng_process
222
+ settings_path = os.path.join(os.path.dirname(__file__), "searxng_settings.yml")
223
+ if not os.path.exists(settings_path):
224
+ _log("SearXNG settings not found, search disabled")
225
+ return False
226
+
227
+ try:
228
+ _searxng_process = subprocess.Popen(
229
+ [sys.executable, "-m", "searx.webapp"],
230
+ env={**os.environ, "SEARXNG_SETTINGS_PATH": settings_path},
231
+ stdout=subprocess.PIPE,
232
+ stderr=subprocess.PIPE,
233
+ )
234
+ # Wait for SearXNG to start
235
+ for _ in range(30):
236
+ time.sleep(1)
237
+ try:
238
+ req = urllib.request.Request(
239
+ f"{SEARXNG_BASE}/search?q=test&format=json",
240
+ headers={"User-Agent": "RespiteAPI/1.0"},
241
+ )
242
+ urllib.request.urlopen(req, timeout=3)
243
+ _log("SearXNG started successfully")
244
+ return True
245
+ except Exception:
246
+ continue
247
+ _log("SearXNG failed to start within 30s")
248
+ return False
249
+ except Exception as e:
250
+ _log(f"SearXNG start failed: {e}")
251
+ return False
252
+
253
+
254
+ def _search_web(query, categories="general", max_results=10):
255
+ """Query the local SearXNG instance."""
256
+ params = {
257
+ "q": query,
258
+ "format": "json",
259
+ "categories": categories,
260
+ "language": "en",
261
+ }
262
+ url = f"{SEARXNG_BASE}/search?{urllib.parse.urlencode(params)}"
263
+ req = urllib.request.Request(url, headers={"User-Agent": "RespiteAPI/1.0"})
264
+ resp = urllib.request.urlopen(req, timeout=10)
265
+ data = _json.loads(resp.read())
266
+ results = []
267
+ for r in data.get("results", [])[:max_results]:
268
+ results.append({
269
+ "title": r.get("title", ""),
270
+ "url": r.get("url", ""),
271
+ "content": r.get("content", ""),
272
+ "engine": r.get("engine", ""),
273
+ "score": r.get("score", 0),
274
+ })
275
+ return {
276
+ "query": query,
277
+ "results": results,
278
+ "total_results": len(data.get("results", [])),
279
+ "categories": data.get("infoboxes", []),
280
+ }
281
+
282
+
283
+ # Start SearXNG in background thread so it doesn't block Gradio startup
284
+ _searxng_thread = threading.Thread(target=_start_searxng, daemon=True)
285
+ _searxng_thread.start()
286
+
287
+
288
  # ---------------------------------------------------------------------------
289
  # Model cache
290
  # ---------------------------------------------------------------------------
 
385
  def _specs():
386
  return JSONResponse({**API_SPECS, "runtime": _get_runtime_specs()})
387
 
388
+ @fa_app.get("/respite/search")
389
+ def _search(q: str = "", categories: str = "general", max_results: int = 10):
390
+ if not q:
391
+ return JSONResponse({"error": "Missing query parameter 'q'"}, status_code=400)
392
+ try:
393
+ results = _search_web(q, categories=categories, max_results=max_results)
394
+ return JSONResponse(results)
395
+ except Exception as e:
396
+ return JSONResponse({"error": str(e)}, status_code=502)
397
+
398
  _log("Respite API discovery routes injected")
399
  return fa_app
400