feat(sources): primary-source discovery via searxng and local llm

This commit is contained in:
kpa39l
2026-11-01 18:03:20 +00:00
parent fba0e395b6
commit 13a6d0647e
25 changed files with 1339 additions and 4 deletions
+112 -1
View File
@@ -24,7 +24,7 @@ except ImportError:
from web.publish import impl_approve
from web import queue
from config import PUBLISH_QUEUE_LIVE, PUBLISH_SLOTS, PUBLISH_TZ
from config import FIND_SOURCES_ENABLED, PUBLISH_QUEUE_LIVE, PUBLISH_SLOTS, PUBLISH_TZ
# CRUD источников: работа с sources.yaml (источник истины) + БД синк
from sources.sources import (
@@ -494,6 +494,8 @@ def candidates(request: Request, direction: str = "", status: str = "", own: str
conn.execute("UPDATE posts SET is_read=1 WHERE id=? AND is_read=0", (sel["id"],))
sel["is_read"] = 1
conn.commit()
from sources.find import list_candidates as _list_candidates
src_candidates = _list_candidates(conn, sel["id"]) if sel and sel["id"] else []
conn.close()
# строка параметров фильтров для ссылок (выбор поста, смена группировки)
qs = []
@@ -509,6 +511,7 @@ def candidates(request: Request, direction: str = "", status: str = "", own: str
# правая деталь (например, после HX-действия): перерисовываем карточку выбранного поста
frag = tpl.get_template("_detail_candidates.html").render(
selected=sel, group_by=group_by, direction=direction, own=own, q=q,
src_candidates=src_candidates, find_enabled=FIND_SOURCES_ENABLED,
)
return HTMLResponse(frag)
frag = tpl.get_template("_candidates_list.html").render(
@@ -522,6 +525,7 @@ def candidates(request: Request, direction: str = "", status: str = "", own: str
q=q, group_by=group_by, selected=sel, error=error, did=did, filters_qs=filters_qs,
directions=DIRECTIONS, STATUS_LABELS=STATUS_LABELS, STATUS_COLORS=STATUS_COLORS,
post_sources=_post_sources(sel),
src_candidates=src_candidates, find_enabled=FIND_SOURCES_ENABLED,
)
return HTMLResponse(html)
@@ -551,6 +555,8 @@ def selected(request: Request, direction: str = "", own: str = "", q: str = "",
conn.execute("UPDATE posts SET is_read=1 WHERE id=? AND is_read=0", (sel["id"],))
sel["is_read"] = 1
conn.commit()
from sources.find import list_candidates as _list_candidates
src_candidates = _list_candidates(conn, sel["id"]) if sel and sel["id"] else []
conn.close()
qs = []
for k, v in (("direction", direction), ("own", own), ("q", q)):
@@ -571,6 +577,7 @@ def selected(request: Request, direction: str = "", own: str = "", q: str = "",
q=q, group_by=group_by, selected=sel, error=error, did=did, filters_qs=filters_qs,
directions=DIRECTIONS, STATUS_LABELS=STATUS_LABELS, STATUS_COLORS=STATUS_COLORS,
post_sources=_post_sources(sel),
src_candidates=src_candidates, find_enabled=FIND_SOURCES_ENABLED,
)
return HTMLResponse(html)
@@ -640,6 +647,28 @@ def candidates_bulk(request: Request, action: str = Form(...), ids: list[int] =
conn.commit()
conn.close()
return _htmx_or_redirect(request, back)
if action == "find-sources":
# поиск источников по отмеченным постам: бюджет по времени, чтобы не упасть в таймаут
import time as _time
import sources.find as finder
budget = 60.0
started = _time.monotonic()
done, errs = 0, []
for r in rows:
if _time.monotonic() - started > budget:
break
try:
finder.find_sources(conn, dict(r))
done += 1
except Exception as e:
errs.append(f"{r['id']}({e})")
conn.close()
left = max(0, len(rows) - done - len(errs))
q = f"&did=found:{done}" + (f"&error=find_partial:{quote(','.join(map(str, errs))[:120])}" if errs else "")
if left:
q += f"&note=left:{left}"
return RedirectResponse(url=f"/{src}?group_by={group_by}{q}", status_code=302)
if action == "enqueue":
# поставить отмеченные посты в план публикации (каждый получает следующий слот)
ok, errs = 0, []
@@ -964,6 +993,85 @@ def plan_publish_now(post_id: int, request: Request):
return RedirectResponse(url="/published", status_code=302)
# ---------- Поиск первоисточников (change find-post-sources) ----------
def _render_sources_panel(request: Request, post_id: int, did: str = "", error: str = "") -> HTMLResponse:
"""Фрагмент блока «🔎 Источники» для карточки поста (htmx outerHTML)."""
from sources.find import list_candidates
conn = _db()
post = conn.execute("SELECT * FROM posts WHERE id=?", (post_id,)).fetchone()
candidates = list_candidates(conn, post_id) if post else []
conn.close()
html = tpl.get_template("_post_sources.html").render(
post=dict(post) if post else {"id": post_id},
candidates=candidates, error=error, did=did, enabled=FIND_SOURCES_ENABLED,
)
return HTMLResponse(html)
@app.get("/posts/{post_id}/sources")
def post_sources_panel(post_id: int, request: Request):
_require_auth(request)
return _render_sources_panel(request, post_id)
@app.post("/posts/{post_id}/find-sources")
def post_find_sources(post_id: int, request: Request):
"""Поиск первоисточников поста: текст → SearXNG → ранжирование локальной моделью."""
_require_auth(request)
if not FIND_SOURCES_ENABLED:
return _render_sources_panel(request, post_id, error="поиск источников выключен (FIND_SOURCES_ENABLED=0)")
import sources.find as finder
conn = _db()
post = conn.execute("SELECT * FROM posts WHERE id=?", (post_id,)).fetchone()
if not post:
conn.close()
return _render_sources_panel(request, post_id, error="пост не найден")
res = finder.find_sources(conn, dict(post))
conn.close()
err = "; ".join(res.get("errors") or [])[:200]
if res.get("cached"):
did = "уже искали — показываю найденное (отклоните лишнее и нажмите снова, чтобы обновить)"
else:
did = f"добавлено {res['added']}"
if res.get("from_text"):
did += f" ({res['from_text']} — из текста)"
if res.get("queries"):
did += f", запросов: {len(res['queries'])}"
return _render_sources_panel(request, post_id, did=did, error=err)
@app.post("/posts/{post_id}/sources/{sid}/accept")
def post_source_accept(post_id: int, sid: int, request: Request):
"""Добавить найденный источник в реестр (sources.yaml + БД)."""
_require_auth(request)
import sources.find as finder
conn = _db()
ok, res = finder.accept_candidate(conn, post_id, sid)
conn.close()
if not ok:
hints = {"no_feed": "у сайта не найдена RSS-лента — добавьте вручную на /sources",
"bad_address": "не удалось разобрать адрес"}
return _render_sources_panel(request, post_id, error=hints.get(res, res))
if str(res).startswith("exists:"):
return _render_sources_panel(request, post_id, did=f"источник уже есть: {res.split(':', 1)[1]}")
return _render_sources_panel(request, post_id, did=f"источник добавлен: {res}")
@app.post("/posts/{post_id}/sources/{sid}/reject")
def post_source_reject(post_id: int, sid: int, request: Request):
_require_auth(request)
import sources.find as finder
conn = _db()
finder.reject_candidate(conn, post_id, sid)
conn.close()
return _render_sources_panel(request, post_id, did="кандидат отклонён")
@app.post("/posts/{post_id}/approve")
async def approve(post_id: int, request: Request,
group_by: str = Form(""), direction: str = Form(""), own: str = Form(""), q: str = Form(""),
@@ -1116,10 +1224,13 @@ def sources_page(request: Request):
dir_rows = conn.execute(
"SELECT DISTINCT direction FROM sources WHERE direction IS NOT NULL AND direction != '' ORDER BY direction"
).fetchall()
from web.search import stats_today
search_stats = stats_today(conn)
conn.close()
directions = sorted(set(DIRECTIONS) | {r[0] for r in dir_rows})
html = tpl.get_template("sources.html").render(
request=request, sources=sources, directions=directions,
search_stats=search_stats, find_enabled=FIND_SOURCES_ENABLED,
did=request.query_params.get("did", ""),
)
return HTMLResponse(html)
+31
View File
@@ -31,5 +31,36 @@ def migrate() -> None:
# план публикации: наивное локальное время 'YYYY-MM-DD HH:MM:SS' в PUBLISH_TZ
conn.execute("ALTER TABLE posts ADD COLUMN scheduled_at TEXT")
conn.commit()
# Поиск первоисточников: кэш поисковых запросов и кандидаты в источники
conn.execute(
"CREATE TABLE IF NOT EXISTS search_cache ("
" query TEXT PRIMARY KEY,"
" created_at TEXT NOT NULL,"
" payload TEXT NOT NULL)"
)
conn.execute(
"CREATE TABLE IF NOT EXISTS post_source_suggestions ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" post_id INTEGER NOT NULL,"
" url TEXT NOT NULL,"
" domain TEXT,"
" kind TEXT,"
" title TEXT,"
" snippet TEXT,"
" score REAL,"
" reason TEXT,"
" status TEXT DEFAULT 'suggested',"
" created_at TEXT,"
" UNIQUE(post_id, url))"
)
conn.execute("CREATE INDEX IF NOT EXISTS idx_pss_post ON post_source_suggestions(post_id)")
# Кэш сгенерированных запросов на пост: повторный поиск не тратит вызов модели
conn.execute(
"CREATE TABLE IF NOT EXISTS post_query_cache ("
" post_id INTEGER PRIMARY KEY,"
" created_at TEXT NOT NULL,"
" queries TEXT NOT NULL)"
)
conn.commit()
finally:
conn.close()
+65
View File
@@ -0,0 +1,65 @@
# Локальная модель (Ollama): запросы к qwen3 с JSON-ответом.
#
# Зачем отдельный модуль: `classifier/classify.py:call_ollama` ходит в OpenAI-совместимый
# /v1/chat/completions, который (замерено 2026-11-01) тратит 8.5 с и 303 токена на простую
# задачу, потому что рассуждения идут отдельным полем `reasoning`. Нативный /api/chat
# с think=false + format="json" даёт тот же ответ за 1.7 с и 61 токен.
import json
import re
import httpx
from config import OLLAMA_MODEL, OLLAMA_URL
THINK_RE = re.compile(r"</think(?:ing)?>", re.I)
def parse_json_response(text: str) -> dict:
"""Достаёт JSON из ответа модели.
Qwen3 может примешивать блок рассуждений в текст ответа даже с think=false
(зависит от сборки модели): срезаем всё до закрывающего тега, убираем ```-обёртки,
и если json.loads всё равно падает — берём первый сбалансированный {...}.
"""
t = (text or "").strip()
m = THINK_RE.search(t)
if m:
t = t[m.end():].strip()
if t.startswith("```"):
t = re.sub(r"^```[a-zA-Z]*\s*", "", t)
t = re.sub(r"\s*```$", "", t).strip()
try:
return json.loads(t)
except json.JSONDecodeError:
start = t.find("{")
if start < 0:
raise
depth = 0
for i, ch in enumerate(t[start:], start):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return json.loads(t[start:i + 1])
raise
def chat_json(prompt: str, *, num_predict: int = 700, temperature: float = 0.2,
timeout: float = 120.0) -> dict:
"""Запрос к локальной модели с гарантией JSON-ответа (нативный API Ollama)."""
response = httpx.post(
f"{OLLAMA_URL}/api/chat",
timeout=timeout,
json={
"model": OLLAMA_MODEL,
"messages": [{"role": "user", "content": prompt}],
"stream": False,
"think": False,
"format": "json",
"options": {"temperature": temperature, "num_predict": num_predict},
},
)
response.raise_for_status()
content = ((response.json().get("message") or {}).get("content") or "")
return parse_json_response(content)
+102
View File
@@ -0,0 +1,102 @@
# Поиск через локальный SearXNG (JSON-API) с кэшем в SQLite.
#
# Внутри SearXNG подключён платный движок `yandex api` (плюс бесплатные seznam/gmx/wikipedia),
# поэтому каждый уникальный запрос кэшируется на SEARCH_CACHE_TTL_H часов: повторный поиск
# по тому же посту не стоит денег.
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
import httpx
from config import SEARCH_CACHE_TTL_H, SEARXNG_URL
from web.queue import fmt, now_local
log = logging.getLogger(__name__)
SEARCH_TIMEOUT = 30.0
def _normalize(items: list[dict], limit: int) -> list[dict]:
out = []
seen = set()
for item in items:
url = (item.get("url") or "").strip()
if not url or url in seen:
continue
seen.add(url)
domain = (urlparse(url).netloc or "").lower().removeprefix("www.")
out.append({
"title": (item.get("title") or "").strip(),
"url": url,
"domain": domain,
"engine": item.get("engine") or "",
"snippet": (item.get("content") or "").strip()[:400],
})
if len(out) >= limit:
break
return out
def cache_get(conn, query: str) -> list[dict] | None:
"""Результаты из кэша, если запись свежее TTL (иначе None)."""
row = conn.execute("SELECT created_at, payload FROM search_cache WHERE query=?", (query,)).fetchone()
if not row:
return None
try:
created = now_local().__class__.strptime(row["created_at"][:19], "%Y-%m-%d %H:%M:%S")
except (ValueError, TypeError):
return None
if now_local() - created > timedelta(hours=SEARCH_CACHE_TTL_H):
return None
try:
return json.loads(row["payload"])
except json.JSONDecodeError:
return None
def cache_put(conn, query: str, results: list[dict]) -> None:
conn.execute(
"INSERT INTO search_cache (query, created_at, payload) VALUES (?,?,?) "
"ON CONFLICT(query) DO UPDATE SET created_at=excluded.created_at, payload=excluded.payload",
(query, fmt(now_local()), json.dumps(results, ensure_ascii=False)),
)
conn.commit()
def search(conn, query: str, limit: int = 8) -> list[dict]:
"""Поиск через SearXNG с кэшем. Сетевые ошибки пробрасываются как SearchError."""
cached = cache_get(conn, query)
if cached is not None:
return cached[:limit]
try:
resp = httpx.get(
f"{SEARXNG_URL}/search",
params={"q": query, "format": "json"},
timeout=SEARCH_TIMEOUT,
)
resp.raise_for_status()
data = resp.json()
except (httpx.HTTPError, json.JSONDecodeError) as exc:
raise SearchError(f"searxng: {exc}") from exc
unresponsive = data.get("unresponsive_engines") or []
if unresponsive:
log.info("searxng unresponsive for %r: %s", query, unresponsive)
results = _normalize(data.get("results") or [], limit)
if results:
cache_put(conn, query, results)
return results
def stats_today(conn) -> int:
"""Сколько уникальных поисковых запросов сделано за текущие сутки."""
today = now_local().strftime("%Y-%m-%d")
row = conn.execute(
"SELECT COUNT(*) c FROM search_cache WHERE created_at >= ?", (today + " 00:00:00",)
).fetchone()
return int(row["c"] if row else 0)
class SearchError(RuntimeError):
pass
+5
View File
@@ -15,3 +15,8 @@
}
[x-cloak] { display: none !important; }
/* htmx-индикатор (в htmx это только классы, стилей в комплекте нет) */
.htmx-indicator { display: none; }
.htmx-request .htmx-indicator,
.htmx-request.htmx-indicator { display: inline; }
File diff suppressed because one or more lines are too long
+4
View File
@@ -49,6 +49,10 @@
{% endif %}
</div>
{% with post = selected, candidates = src_candidates, did = '', error = '', enabled = find_enabled %}
{% include "_post_sources.html" %}
{% endwith %}
<hr class="border-neutral-200 my-1 shrink-0">
<div x-data="{ tab: '{{ 'tr' if selected.translated_text else 'orig' }}' }" class="flex flex-col grow" style="min-height:0;">
<div class="flex items-center justify-between shrink-0 mb-2 gap-2">
+50
View File
@@ -0,0 +1,50 @@
{# Блок «🔎 Источники» в карточке поста (кандидат и отобранный).
Рендерится и как часть страницы, и как htmx-фрагмент (hx-target="#sources-panel", outerHTML). #}
<div id="sources-panel" class="border-t border-neutral-200 pt-2 mt-2 shrink-0">
<div class="flex items-center justify-between gap-2 mb-1">
<span class="text-sm font-medium">🔎 Источники</span>
{% if enabled %}
<form hx-post="/posts/{{ post.id }}/find-sources" hx-target="#sources-panel" hx-swap="outerHTML"
hx-indicator="#src-spin" hx-disabled-elt="find button" method="post"
action="/posts/{{ post.id }}/find-sources">
<button class="btn btn-xs btn-outline" type="submit"
title="Найти первоисточник: ссылки из текста, затем поиск и оценка локальной моделью">Найти источники</button>
<span id="src-spin" class="htmx-indicator text-xs text-neutral-500">⏳ ищу…</span>
</form>
{% endif %}
</div>
{% if did %}<div class="text-xs text-green-700 mb-1">✅ {{ did }}</div>{% endif %}
{% if error %}<div class="text-xs text-red-600 mb-1">⚠ {{ error }}</div>{% endif %}
{% if candidates %}
<div class="flex flex-col gap-1 overflow-y-auto" style="max-height: 12rem;">
{% for c in candidates %}
<div class="flex items-start gap-2 text-xs border border-neutral-200 rounded-md px-2 py-1">
<div class="grow min-w-0">
<div class="flex items-center gap-1 flex-wrap">
<span class="badge badge-{{ 'info' if c.kind == 'telegram' else 'neutral' }}">{{ c.kind }}</span>
{% if c.score is not none %}<span class="badge badge-{{ 'success' if c.score >= 0.7 else 'warning' }}">{{ '%.1f'|format(c.score) }}</span>{% endif %}
<a href="{{ c.url }}" target="_blank" class="no-underline font-medium truncate">{{ c.domain or c.url }}</a>
</div>
<div class="text-neutral-600 truncate">{{ c.title or '' }}</div>
{% if c.reason %}<div class="text-neutral-500">{{ c.reason }}</div>{% endif %}
{% if c.snippet %}<details class="text-neutral-500"><summary class="cursor-pointer">сниппет</summary>{{ c.snippet }}</details>{% endif %}
</div>
<div class="flex flex-col gap-1 shrink-0">
<form hx-post="/posts/{{ post.id }}/sources/{{ c.id }}/accept" hx-target="#sources-panel" hx-swap="outerHTML"
method="post" action="/posts/{{ post.id }}/sources/{{ c.id }}/accept">
<button class="btn btn-xs btn-success" type="submit" title="Добавить в реестр источников (Telegram-канал или RSS-лента)">➕</button>
</form>
<form hx-post="/posts/{{ post.id }}/sources/{{ c.id }}/reject" hx-target="#sources-panel" hx-swap="outerHTML"
method="post" action="/posts/{{ post.id }}/sources/{{ c.id }}/reject">
<button class="btn btn-xs btn-outline text-red-600" type="submit" title="Не источник — больше не предлагать">❌</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="text-xs text-neutral-500">Источники не искали. «Найти источники» — ссылки из текста, затем поиск.</div>
{% endif %}
</div>
+1
View File
@@ -67,6 +67,7 @@
<div class="join w-full flex-wrap">
<button class="join-item flex-1 btn btn-sm btn-info" name="action" value="process">🤖 Обработать моделью</button>
<button class="join-item flex-1 btn btn-sm" name="action" value="enqueue">🗓 В очередь</button>
<button class="join-item flex-1 btn btn-sm" name="action" value="find-sources">🔎 Источники</button>
<button class="join-item flex-1 btn btn-sm" name="action" value="rewrite">✍️ Переписать</button>
<button class="join-item flex-1 btn btn-sm btn-success" name="action" value="approve">✅ Опубликовать</button>
<button class="join-item flex-1 btn btn-sm btn-outline text-red-600" name="action" value="reject">🚫 Отклонить</button>
+3
View File
@@ -94,6 +94,9 @@
</form>
{% endif %}
</div>
{% with post = selected, candidates = src_candidates, did = '', error = '', enabled = find_enabled %}
{% include "_post_sources.html" %}
{% endwith %}
<!-- Резюме — сразу под кнопками -->
{% if selected.summary %}
<div class="shrink-0 mb-2">
+3
View File
@@ -3,6 +3,9 @@
{% block content %}
<h4 class="text-xl font-semibold mb-4 flex items-center gap-2 flex-wrap">📡 Источники
<a href="/crawlers" class="btn btn-sm btn-outline">Статус краулеров →</a>
{% if find_enabled %}
<span class="text-sm text-neutral-500 font-normal">поисковых запросов за сутки: <b>{{ search_stats }}</b></span>
{% endif %}
</h4>
{% if did %}