Spaces:
Sleeping
Sleeping
Download main.py from DunaevStudio/Search: direct link, hf CLI and curl.
- Browser
- Download file 5.58 kB
-
https://huggingface.co/spaces/DunaevStudio/Search/resolve/main/main.py
- Command line
-
hf download hf://spaces/DunaevStudio/Search/main.py
-
curl -L -o main.py https://huggingface.co/spaces/DunaevStudio/Search/resolve/main/main.py
5.58 kB
| import os, time, json, hashlib, contextlib | |
| from typing import List, Optional, AsyncIterator | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| import httpx | |
| import redis.asyncio as aioredis | |
| import structlog | |
| structlog.configure( | |
| processors=[ | |
| structlog.processors.add_log_level, | |
| structlog.processors.TimeStamper(fmt="iso"), | |
| structlog.dev.ConsoleRenderer() | |
| ] | |
| ) | |
| logger = structlog.get_logger() | |
| REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0") | |
| SEARXNG_URL = os.getenv("SEARXNG_URL", "http://localhost:8080") | |
| CACHE_TTL = int(os.getenv("CACHE_TTL", "7200")) | |
| RATE_LIMIT = int(os.getenv("RATE_LIMIT", "10")) | |
| RATE_WINDOW = int(os.getenv("RATE_WINDOW", "60")) | |
| TIMEOUT = float(os.getenv("TIMEOUT", "10.0")) | |
| async def lifespan(app: FastAPI) -> AsyncIterator[None]: | |
| global redis_client | |
| redis_client = aioredis.from_url(REDIS_URL, decode_responses=True) | |
| await redis_client.ping() | |
| logger.info("system_started", status="ok") | |
| yield | |
| if redis_client: | |
| await redis_client.aclose() | |
| app = FastAPI(title="Design Search API", version="1.0.0", lifespan=lifespan) | |
| app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) | |
| redis_client: Optional[aioredis.Redis] = None | |
| class SearchReq(BaseModel): | |
| query: str | |
| limit: int = 5 | |
| class Result(BaseModel): | |
| title: str | |
| url: str | |
| snippet: Optional[str] = None | |
| def get_client_ip(request: Request) -> str: | |
| forwarded = request.headers.get("X-Forwarded-For") | |
| if forwarded: | |
| return forwarded.split(",")[0].strip() | |
| return request.client.host | |
| async def check_rate(ip: str) -> bool: | |
| key = f"ratelimit:{ip}" | |
| now = time.time() | |
| pipe = redis_client.pipeline() | |
| pipe.zremrangebyscore(key, 0, now - RATE_WINDOW) | |
| pipe.zadd(key, {str(now): now}) | |
| pipe.zcard(key) | |
| pipe.expire(key, RATE_WINDOW) | |
| _, _, count, _ = await pipe.execute() | |
| return count <= RATE_LIMIT | |
| async def get_cache(query: str) -> Optional[List[Result]]: | |
| h = hashlib.sha256(query.encode("utf-8")).hexdigest() | |
| data = await redis_client.get(f"cache:{h}") | |
| if not data: | |
| return None | |
| try: | |
| items = json.loads(data) | |
| return [Result(**item) for item in items] | |
| except Exception: | |
| return None | |
| async def set_cache(query: str, results: List[Result]): | |
| h = hashlib.sha256(query.encode("utf-8")).hexdigest() | |
| payload = [r.model_dump() for r in results] | |
| await redis_client.setex(f"cache:{h}", CACHE_TTL, json.dumps(payload, ensure_ascii=False)) | |
| async def search(req: SearchReq, request: Request): | |
| ip = get_client_ip(request) | |
| if not await check_rate(ip): | |
| raise HTTPException(429, "Rate limit exceeded. Подождите 60 секунд.") | |
| q = req.query.strip() | |
| if not q: | |
| raise HTTPException(400, "Пустой запрос") | |
| cached = await get_cache(q) | |
| if cached: | |
| logger.info("cache_hit", query=q) | |
| return cached | |
| params = { | |
| "q": q, | |
| "format": "json", | |
| "language": "ru", | |
| "categories": "general", | |
| "limit": req.limit, | |
| } | |
| # Ждём готовности SearXNG (до 30 секунд) | |
| for _ in range(30): | |
| try: | |
| async with httpx.AsyncClient(timeout=2.0) as test_client: | |
| test_resp = await test_client.get(f"{SEARXNG_URL}/healthz") | |
| if test_resp.status_code == 200: | |
| break | |
| except: | |
| await asyncio.sleep(1) | |
| async with httpx.AsyncClient(timeout=TIMEOUT) as client: | |
| try: | |
| resp = await client.get(f"{SEARXNG_URL}/search", params=params) | |
| if resp.status_code == 404: | |
| logger.error("searxng_404", url=f"{SEARXNG_URL}/search", query=q) | |
| raise HTTPException(502, "Поисковый сервис не настроен (404)") | |
| if resp.status_code != 200: | |
| logger.error("search_http_error", status=resp.status_code, query=q) | |
| raise HTTPException(502, f"Поисковый сервис вернул ошибку {resp.status_code}") | |
| data = resp.json() | |
| except httpx.RequestError as e: | |
| logger.error("search_request_error", error=str(e), query=q) | |
| raise HTTPException(502, "Поисковый сервис недоступен") | |
| except ValueError: | |
| logger.error("search_non_json_response", query=q) | |
| raise HTTPException(502, "Некорректный ответ от поискового сервиса") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error("search_unexpected_error", error=str(e), query=q) | |
| raise HTTPException(502, "Внутренняя ошибка поиска") | |
| results = [] | |
| for r in data.get("results", [])[:req.limit]: | |
| results.append(Result( | |
| title=(r.get("title") or "Без заголовка").strip(), | |
| url=(r.get("url") or "").strip(), | |
| snippet=(r.get("content") or "")[:200].strip() | |
| )) | |
| if results: | |
| await set_cache(q, results) | |
| logger.info("search_success", results=len(results), query=q) | |
| return results | |
| def health(): | |
| return {"status": "ok", "version": "1.0.0"} | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |