Spaces:
Running
Running
SilverElixir commited on
Commit ·
54c35f1
1
Parent(s): eb2b6ab
Fall back to Bing RSS and Google News when DuckDuckGo is empty, and log empty searches
Browse files- lumen_search.py +132 -13
- tests/test_lumen_search.py +60 -1
lumen_search.py
CHANGED
|
@@ -4,11 +4,15 @@ lumen_search.py — внешний веб-поиск для свежих зап
|
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
|
|
|
|
|
|
| 7 |
import html
|
| 8 |
import logging
|
| 9 |
import os
|
| 10 |
import re
|
|
|
|
| 11 |
import urllib.parse
|
|
|
|
| 12 |
|
| 13 |
import aiohttp
|
| 14 |
|
|
@@ -19,10 +23,13 @@ log = logging.getLogger("bot")
|
|
| 19 |
# DuckDuckGo lite: лёгкая HTML-выдача без JS и без ключа (api.duckduckgo.com отдаёт
|
| 20 |
# только instant-ответы и пуст на обычных новостях — прод 11.10.2026).
|
| 21 |
_DDG_LITE_URL = "https://lite.duckduckgo.com/lite/"
|
| 22 |
-
|
| 23 |
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
| 24 |
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36",
|
| 25 |
}
|
|
|
|
|
|
|
|
|
|
| 26 |
# Выдача чужая и грязная: режем число и длину, иначе раздует промпт и квоту токенов.
|
| 27 |
_DEFAULT_MAX_RESULTS = 5
|
| 28 |
_SNIPPET_MAX_CHARS = 300
|
|
@@ -159,17 +166,18 @@ def format_snippets_for_prompt(snippets: list[dict]) -> str:
|
|
| 159 |
|
| 160 |
async def _fetch_ddg_page(session: aiohttp.ClientSession, query: str, timeout: float) -> str:
|
| 161 |
budget = aiohttp.ClientTimeout(total=max(1.0, timeout))
|
| 162 |
-
async with session.post(_DDG_LITE_URL, data={"q": query}, headers=
|
| 163 |
if resp.status == 200:
|
| 164 |
return await resp.text()
|
| 165 |
-
async with session.get(_DDG_LITE_URL, params={"q": query}, headers=
|
| 166 |
resp.raise_for_status()
|
| 167 |
return await resp.text()
|
| 168 |
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
| 173 |
import bot
|
| 174 |
session = None
|
| 175 |
if getattr(bot, "bot", None) is not None:
|
|
@@ -179,21 +187,132 @@ async def _fetch_ddg_page_shared(query: str, timeout: float) -> str:
|
|
| 179 |
log.warning("[web-search] Shared HTTP session unavailable, using a one-off session: %s", exc.__class__.__name__)
|
| 180 |
if session is None:
|
| 181 |
async with aiohttp.ClientSession() as own:
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
|
| 186 |
async def fetch_web_snippets(query: str, *, timeout_sec: float | None = None, max_results: int | None = None) -> list[dict]:
|
| 187 |
-
"""Сниппеты
|
|
|
|
|
|
|
| 188 |
query = (query or "").strip()[:500]
|
| 189 |
if not query:
|
| 190 |
return []
|
| 191 |
timeout = timeout_sec if timeout_sec else web_search_timeout_sec()
|
| 192 |
limit = max_results if max_results else web_search_max_results()
|
|
|
|
|
|
|
| 193 |
try:
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
except Exception as exc:
|
| 196 |
-
# Внешний поиск — довесок
|
| 197 |
-
log.warning("[web-search]
|
| 198 |
return []
|
| 199 |
-
|
|
|
|
|
|
| 4 |
|
| 5 |
from __future__ import annotations
|
| 6 |
|
| 7 |
+
import asyncio
|
| 8 |
+
import contextlib
|
| 9 |
import html
|
| 10 |
import logging
|
| 11 |
import os
|
| 12 |
import re
|
| 13 |
+
import time
|
| 14 |
import urllib.parse
|
| 15 |
+
import xml.etree.ElementTree as ET
|
| 16 |
|
| 17 |
import aiohttp
|
| 18 |
|
|
|
|
| 23 |
# DuckDuckGo lite: лёгкая HTML-выдача без JS и без ключа (api.duckduckgo.com отдаёт
|
| 24 |
# только instant-ответы и пуст на обычных новостях — прод 11.10.2026).
|
| 25 |
_DDG_LITE_URL = "https://lite.duckduckgo.com/lite/"
|
| 26 |
+
_SEARCH_HEADERS = {
|
| 27 |
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
| 28 |
"(KHTML, like Gecko) Chrome/126.0 Safari/537.36",
|
| 29 |
}
|
| 30 |
+
_BING_SEARCH_URL = "https://www.bing.com/search"
|
| 31 |
+
_GOOGLE_NEWS_URL = "https://news.google.com/rss/search"
|
| 32 |
+
_CYRILLIC_RE = re.compile(r"[А-Яа-яЁё]")
|
| 33 |
# Выдача чужая и грязная: режем число и длину, иначе раздует промпт и квоту токенов.
|
| 34 |
_DEFAULT_MAX_RESULTS = 5
|
| 35 |
_SNIPPET_MAX_CHARS = 300
|
|
|
|
| 166 |
|
| 167 |
async def _fetch_ddg_page(session: aiohttp.ClientSession, query: str, timeout: float) -> str:
|
| 168 |
budget = aiohttp.ClientTimeout(total=max(1.0, timeout))
|
| 169 |
+
async with session.post(_DDG_LITE_URL, data={"q": query}, headers=_SEARCH_HEADERS, timeout=budget) as resp:
|
| 170 |
if resp.status == 200:
|
| 171 |
return await resp.text()
|
| 172 |
+
async with session.get(_DDG_LITE_URL, params={"q": query}, headers=_SEARCH_HEADERS, timeout=budget) as resp:
|
| 173 |
resp.raise_for_status()
|
| 174 |
return await resp.text()
|
| 175 |
|
| 176 |
|
| 177 |
+
@contextlib.asynccontextmanager
|
| 178 |
+
async def _search_session():
|
| 179 |
+
"""Общая сессия бота с прогретым DNS/TLS; разовая — только вне бота
|
| 180 |
+
(тесты, CLI). Новый ClientSession на каждый поиск стоил полного сетевого круга."""
|
| 181 |
import bot
|
| 182 |
session = None
|
| 183 |
if getattr(bot, "bot", None) is not None:
|
|
|
|
| 187 |
log.warning("[web-search] Shared HTTP session unavailable, using a one-off session: %s", exc.__class__.__name__)
|
| 188 |
if session is None:
|
| 189 |
async with aiohttp.ClientSession() as own:
|
| 190 |
+
yield own
|
| 191 |
+
else:
|
| 192 |
+
yield session
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def parse_rss_snippets(xml_page: str, max_results: int = _DEFAULT_MAX_RESULTS) -> list[dict]:
|
| 196 |
+
"""RSS-выдача поисковиков в те же (title, url, snippet); битый XML — пусто."""
|
| 197 |
+
if not xml_page:
|
| 198 |
+
return []
|
| 199 |
+
try:
|
| 200 |
+
root = ET.fromstring(xml_page)
|
| 201 |
+
except ET.ParseError:
|
| 202 |
+
return []
|
| 203 |
+
out: list[dict] = []
|
| 204 |
+
seen: set[str] = set()
|
| 205 |
+
for item in root.iter("item"):
|
| 206 |
+
url = (item.findtext("link") or "").strip()
|
| 207 |
+
title = _clean_text(item.findtext("title") or "", _SNIPPET_MAX_CHARS)
|
| 208 |
+
snippet = _clean_text(item.findtext("description") or "", _SNIPPET_MAX_CHARS)
|
| 209 |
+
if not url.startswith(("http://", "https://")) or url in seen:
|
| 210 |
+
continue
|
| 211 |
+
if not title and not snippet:
|
| 212 |
+
continue
|
| 213 |
+
seen.add(url)
|
| 214 |
+
out.append({"title": title, "url": url, "snippet": snippet})
|
| 215 |
+
if len(out) >= max_results:
|
| 216 |
+
break
|
| 217 |
+
return out
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _merge_snippets(groups: list[list[dict]], max_results: int) -> list[dict]:
|
| 221 |
+
"""Чередуем источники, чтобы один не вытеснил другой, и режем дубли по URL."""
|
| 222 |
+
out: list[dict] = []
|
| 223 |
+
seen: set[str] = set()
|
| 224 |
+
longest = max((len(group) for group in groups), default=0)
|
| 225 |
+
for index in range(longest):
|
| 226 |
+
for group in groups:
|
| 227 |
+
if index >= len(group):
|
| 228 |
+
continue
|
| 229 |
+
item = group[index]
|
| 230 |
+
url = item.get("url") or ""
|
| 231 |
+
if not url or url in seen:
|
| 232 |
+
continue
|
| 233 |
+
seen.add(url)
|
| 234 |
+
out.append(item)
|
| 235 |
+
if len(out) >= max_results:
|
| 236 |
+
return out
|
| 237 |
+
return out
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _search_locale(query: str) -> dict[str, str]:
|
| 241 |
+
if _CYRILLIC_RE.search(query):
|
| 242 |
+
return {"cc": "RU", "setlang": "ru"}
|
| 243 |
+
return {"cc": "US", "setlang": "en"}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
async def _bing_snippets(session: aiohttp.ClientSession, query: str, timeout: float, limit: int) -> list[dict]:
|
| 247 |
+
locale = _search_locale(query)
|
| 248 |
+
params = {"q": query, "format": "rss", "cc": locale["cc"], "setlang": locale["setlang"]}
|
| 249 |
+
budget = aiohttp.ClientTimeout(total=max(1.0, timeout))
|
| 250 |
+
async with session.get(_BING_SEARCH_URL, params=params, headers=_SEARCH_HEADERS, timeout=budget) as resp:
|
| 251 |
+
resp.raise_for_status()
|
| 252 |
+
return parse_rss_snippets(await resp.text(), limit)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
async def _google_news_snippets(session: aiohttp.ClientSession, query: str, timeout: float, limit: int) -> list[dict]:
|
| 256 |
+
if _CYRILLIC_RE.search(query):
|
| 257 |
+
hl, gl, ceid = "ru", "RU", "RU:ru"
|
| 258 |
+
else:
|
| 259 |
+
hl, gl, ceid = "en-US", "US", "US:en"
|
| 260 |
+
budget = aiohttp.ClientTimeout(total=max(1.0, timeout))
|
| 261 |
+
async with session.get(
|
| 262 |
+
_GOOGLE_NEWS_URL, params={"q": query, "hl": hl, "gl": gl, "ceid": ceid},
|
| 263 |
+
headers=_SEARCH_HEADERS, timeout=budget,
|
| 264 |
+
) as resp:
|
| 265 |
+
resp.raise_for_status()
|
| 266 |
+
return parse_rss_snippets(await resp.text(), limit)
|
| 267 |
|
| 268 |
|
| 269 |
async def fetch_web_snippets(query: str, *, timeout_sec: float | None = None, max_results: int | None = None) -> list[dict]:
|
| 270 |
+
"""Сниппеты из нескольких источников: DuckDuckGo lite, затем Bing RSS и
|
| 271 |
+
Google News параллельно. Источник упал или отдал пусто — пробуем следующий;
|
| 272 |
+
пусто у всех — [] и честная пометка на стороне вызывающего кода."""
|
| 273 |
query = (query or "").strip()[:500]
|
| 274 |
if not query:
|
| 275 |
return []
|
| 276 |
timeout = timeout_sec if timeout_sec else web_search_timeout_sec()
|
| 277 |
limit = max_results if max_results else web_search_max_results()
|
| 278 |
+
deadline = time.monotonic() + max(1.0, timeout)
|
| 279 |
+
diagnostics: dict[str, int] = {}
|
| 280 |
try:
|
| 281 |
+
async with _search_session() as session:
|
| 282 |
+
ddg_budget = max(1.0, min(4.0, deadline - time.monotonic()))
|
| 283 |
+
page = ""
|
| 284 |
+
try:
|
| 285 |
+
page = await _fetch_ddg_page(session, query, ddg_budget)
|
| 286 |
+
except Exception as exc:
|
| 287 |
+
log.warning("[web-search] DuckDuckGo fetch failed (query_len=%d): %s", len(query), exc.__class__.__name__)
|
| 288 |
+
ddg_items = parse_ddg_lite_html(page, limit) if page else []
|
| 289 |
+
diagnostics["ddg"] = len(ddg_items)
|
| 290 |
+
if ddg_items:
|
| 291 |
+
return ddg_items
|
| 292 |
+
diagnostics["ddg_page_chars"] = len(page)
|
| 293 |
+
|
| 294 |
+
remaining = deadline - time.monotonic()
|
| 295 |
+
if remaining <= 0.5:
|
| 296 |
+
diagnostics["bing"] = diagnostics["google_news"] = 0
|
| 297 |
+
else:
|
| 298 |
+
fetched = await asyncio.gather(
|
| 299 |
+
_bing_snippets(session, query, remaining, limit),
|
| 300 |
+
_google_news_snippets(session, query, remaining, limit),
|
| 301 |
+
return_exceptions=True,
|
| 302 |
+
)
|
| 303 |
+
for name, result in zip(("bing", "google_news"), fetched):
|
| 304 |
+
if isinstance(result, BaseException):
|
| 305 |
+
log.warning("[web-search] %s failed: %s", name, type(result).__name__)
|
| 306 |
+
diagnostics[name] = 0
|
| 307 |
+
else:
|
| 308 |
+
diagnostics[name] = len(result)
|
| 309 |
+
groups = [result for result in fetched if isinstance(result, list)]
|
| 310 |
+
merged = _merge_snippets(groups, limit)
|
| 311 |
+
if merged:
|
| 312 |
+
return merged
|
| 313 |
except Exception as exc:
|
| 314 |
+
# Внешний поиск — довесок: сеть легла — отвечаем с пометкой, а не падением.
|
| 315 |
+
log.warning("[web-search] Search failed open (query_len=%d): %s", len(query), exc.__class__.__name__)
|
| 316 |
return []
|
| 317 |
+
log.warning("[web-search] No snippets from any provider (query_len=%d): %s", len(query), diagnostics)
|
| 318 |
+
return []
|
tests/test_lumen_search.py
CHANGED
|
@@ -105,7 +105,8 @@ class _StubResp:
|
|
| 105 |
return self._text
|
| 106 |
|
| 107 |
def raise_for_status(self):
|
| 108 |
-
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
class _StubSession:
|
|
@@ -137,6 +138,64 @@ def _stub_aiohttp(resp=None, exc=None):
|
|
| 137 |
)
|
| 138 |
|
| 139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
def test_fetch_web_snippets_parses_stubbed_page(monkeypatch):
|
| 141 |
monkeypatch.setattr(lumen_search, "aiohttp", _stub_aiohttp(_StubResp(200, _DDG_FIXTURE)))
|
| 142 |
out = asyncio.run(lumen_search.fetch_web_snippets("что с ДЦ Яндекса"))
|
|
|
|
| 105 |
return self._text
|
| 106 |
|
| 107 |
def raise_for_status(self):
|
| 108 |
+
if self.status >= 400:
|
| 109 |
+
raise RuntimeError(f"http {self.status}")
|
| 110 |
|
| 111 |
|
| 112 |
class _StubSession:
|
|
|
|
| 138 |
)
|
| 139 |
|
| 140 |
|
| 141 |
+
class _RoutedSession:
|
| 142 |
+
"""Разные страницы по URL: DDG пустой, RSS-источники — со своими фикстурами."""
|
| 143 |
+
|
| 144 |
+
def __init__(self, pages):
|
| 145 |
+
self._pages = pages
|
| 146 |
+
self.requested = []
|
| 147 |
+
|
| 148 |
+
def _resp(self, url):
|
| 149 |
+
self.requested.append(url)
|
| 150 |
+
return _StubResp(200, self._pages.get(url, "<html></html>"))
|
| 151 |
+
|
| 152 |
+
def post(self, url, *args, **kwargs):
|
| 153 |
+
return self._resp(url)
|
| 154 |
+
|
| 155 |
+
def get(self, url, *args, **kwargs):
|
| 156 |
+
return self._resp(url)
|
| 157 |
+
|
| 158 |
+
async def __aenter__(self):
|
| 159 |
+
return self
|
| 160 |
+
|
| 161 |
+
async def __aexit__(self, *args):
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
_RSS_FIXTURE = """<?xml version="1.0" encoding="UTF-8"?>
|
| 166 |
+
<rss><channel>
|
| 167 |
+
<item><title>Свежая новость</title><link>https://example.com/fresh</link>
|
| 168 |
+
<description>Текст свежей новости</description></item>
|
| 169 |
+
<item><title>Дубль</title><link>https://example.com/fresh</link>
|
| 170 |
+
<description>Тот же адрес</description></item>
|
| 171 |
+
<item><title>Без ссылки</title><description>мусор</description></item>
|
| 172 |
+
</channel></rss>"""
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_parse_rss_snippets_reads_items_and_drops_duplicates():
|
| 176 |
+
out = lumen_search.parse_rss_snippets(_RSS_FIXTURE)
|
| 177 |
+
assert out == [{"title": "Свежая новость", "url": "https://example.com/fresh",
|
| 178 |
+
"snippet": "Текст свежей новости"}]
|
| 179 |
+
assert lumen_search.parse_rss_snippets("<rss><broken") == []
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_fetch_web_snippets_falls_back_to_rss_when_ddg_returns_empty(monkeypatch):
|
| 183 |
+
# Прод 28.10.2026: DuckDuckGo с адресов Space отдавал страницу без выдачи,
|
| 184 |
+
# и бот отвечал «поиск ничего не дал» — RSS-фолбэк обязан дать сниппеты.
|
| 185 |
+
session = _RoutedSession({
|
| 186 |
+
lumen_search._BING_SEARCH_URL: _RSS_FIXTURE,
|
| 187 |
+
lumen_search._GOOGLE_NEWS_URL: "",
|
| 188 |
+
})
|
| 189 |
+
monkeypatch.setattr(
|
| 190 |
+
lumen_search, "aiohttp",
|
| 191 |
+
SimpleNamespace(ClientSession=lambda *args, **kwargs: session,
|
| 192 |
+
ClientTimeout=aiohttp.ClientTimeout),
|
| 193 |
+
)
|
| 194 |
+
out = asyncio.run(lumen_search.fetch_web_snippets("свежие новости"))
|
| 195 |
+
assert [item["url"] for item in out] == ["https://example.com/fresh"]
|
| 196 |
+
assert lumen_search._BING_SEARCH_URL in session.requested
|
| 197 |
+
|
| 198 |
+
|
| 199 |
def test_fetch_web_snippets_parses_stubbed_page(monkeypatch):
|
| 200 |
monkeypatch.setattr(lumen_search, "aiohttp", _stub_aiohttp(_StubResp(200, _DDG_FIXTURE)))
|
| 201 |
out = asyncio.run(lumen_search.fetch_web_snippets("что с ДЦ Яндекса"))
|