feat(sources): primary-source discovery via searxng and local llm
This commit is contained in:
+112
-1
@@ -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"¬e=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)
|
||||
|
||||
Reference in New Issue
Block a user