initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,161 @@
|
||||
"""Web search and page content extraction client."""
|
||||
|
||||
import asyncio
|
||||
from html.parser import HTMLParser
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from homeagent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _HTMLTextExtractor(HTMLParser):
|
||||
"""HTML parser that strips scripts, styles, and chrome, extracting clean readable text."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._pieces: list[str] = []
|
||||
self._ignore_stack: list[str] = []
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
|
||||
tag_lower = tag.lower()
|
||||
if tag_lower in ("script", "style", "noscript", "svg", "head", "header", "footer", "nav", "aside"):
|
||||
self._ignore_stack.append(tag_lower)
|
||||
elif tag_lower in ("p", "div", "br", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "article", "section"):
|
||||
self._pieces.append("\n")
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
tag_lower = tag.lower()
|
||||
if self._ignore_stack and self._ignore_stack[-1] == tag_lower:
|
||||
self._ignore_stack.pop()
|
||||
elif tag_lower in ("p", "div", "br", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "article", "section"):
|
||||
self._pieces.append("\n")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if not self._ignore_stack:
|
||||
clean_text = data.strip()
|
||||
if clean_text:
|
||||
self._pieces.append(clean_text + " ")
|
||||
|
||||
def get_text(self) -> str:
|
||||
raw = "".join(self._pieces)
|
||||
# Collapse multiple empty lines and horizontal spaces
|
||||
raw = re.sub(r"[ \t]+", " ", raw)
|
||||
raw = re.sub(r"\n\s*\n\s*\n+", "\n\n", raw)
|
||||
return raw.strip()
|
||||
|
||||
|
||||
class WebSearchClient:
|
||||
"""Client for web searches and fetching page content."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.settings = get_settings()
|
||||
|
||||
async def search(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
|
||||
"""Search the web for query using the configured provider.
|
||||
|
||||
Returns:
|
||||
List of dicts: [{"title": ..., "url": ..., "snippet": ...}]
|
||||
"""
|
||||
provider = self.settings.WEB_SEARCH_PROVIDER.lower()
|
||||
|
||||
if provider == "tavily" and self.settings.TAVILY_API_KEY:
|
||||
return await self._search_tavily(query, max_results)
|
||||
elif provider == "searxng" and self.settings.SEARXNG_URL:
|
||||
return await self._search_searxng(query, max_results)
|
||||
|
||||
# Default: DuckDuckGo (ddgs)
|
||||
return await self._search_duckduckgo(query, max_results)
|
||||
|
||||
async def _search_duckduckgo(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
|
||||
def _ddg_sync() -> list[dict[str, str]]:
|
||||
from ddgs import DDGS
|
||||
|
||||
ddgs = DDGS()
|
||||
raw_results = list(ddgs.text(query, max_results=max_results))
|
||||
out: list[dict[str, str]] = []
|
||||
for item in raw_results:
|
||||
out.append({
|
||||
"title": item.get("title", "Без названия"),
|
||||
"url": item.get("href", ""),
|
||||
"snippet": item.get("body", ""),
|
||||
})
|
||||
return out
|
||||
|
||||
try:
|
||||
return await asyncio.to_thread(_ddg_sync)
|
||||
except Exception as e:
|
||||
logger.error("DuckDuckGo search error for '%s': %s", query, e)
|
||||
raise
|
||||
|
||||
async def _search_tavily(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
|
||||
api_key = self.settings.TAVILY_API_KEY.get_secret_value() if self.settings.TAVILY_API_KEY else ""
|
||||
url = "https://api.tavily.com/search"
|
||||
payload = {
|
||||
"api_key": api_key,
|
||||
"query": query,
|
||||
"max_results": max_results,
|
||||
"search_depth": "basic",
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.post(url, json=payload)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
out: list[dict[str, str]] = []
|
||||
for item in data.get("results", []):
|
||||
out.append({
|
||||
"title": item.get("title", "Без названия"),
|
||||
"url": item.get("url", ""),
|
||||
"snippet": item.get("content", ""),
|
||||
})
|
||||
return out
|
||||
|
||||
async def _search_searxng(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
|
||||
base_url = self.settings.SEARXNG_URL.rstrip("/") if self.settings.SEARXNG_URL else ""
|
||||
url = f"{base_url}/search"
|
||||
params = {"q": query, "format": "json"}
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
out: list[dict[str, str]] = []
|
||||
for item in data.get("results", [])[:max_results]:
|
||||
out.append({
|
||||
"title": item.get("title", "Без названия"),
|
||||
"url": item.get("url", ""),
|
||||
"snippet": item.get("content", ""),
|
||||
})
|
||||
return out
|
||||
|
||||
async def fetch_page(self, url: str, max_length: int = 4000) -> str:
|
||||
"""Fetch URL and extract clean text content."""
|
||||
headers = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/124.0.0.0 Safari/537.36 HomeAgent/1.0"
|
||||
),
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
}
|
||||
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True, headers=headers) as client:
|
||||
resp = await client.get(url)
|
||||
resp.raise_for_status()
|
||||
content_type = resp.headers.get("content-type", "").lower()
|
||||
|
||||
if "json" in content_type:
|
||||
text = resp.text
|
||||
elif "text" in content_type or "html" in content_type or not content_type:
|
||||
parser = _HTMLTextExtractor()
|
||||
parser.feed(resp.text)
|
||||
text = parser.get_text()
|
||||
else:
|
||||
text = f"[Бинарный контент или неподдерживаемый тип: {content_type}]"
|
||||
|
||||
if len(text) > max_length:
|
||||
text = text[:max_length] + "\n\n... [Контент обрезан из-за превышения длины]"
|
||||
|
||||
return text
|
||||
Reference in new issue
Block a user