Spaces:
Runtime error
Runtime error
Download src/core/knowledge_memory.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 76.6 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/knowledge_memory.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/core/knowledge_memory.py
-
curl -L -o knowledge_memory.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/core/knowledge_memory.py
76.6 kB
"""Knowledge memory crawl/index/retrieval service."""
from __future__ import annotations
import hashlib
import io
import re
import threading
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import unquote, urlparse, urlunparse
from uuid import UUID
import httpx
from src.core.source_evidence import _is_safe_public_url
from src.db import KnowledgeRepository, get_db
from src.models import (
KnowledgeChunk,
KnowledgeCrawlPhase,
KnowledgeCrawlRun,
KnowledgeCrawlStatus,
KnowledgeCrawlTrigger,
KnowledgePage,
KnowledgeVersionState,
)
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger
logger = get_logger(__name__)
SCRIPT_RE = re.compile(r"(?is)<script.*?>.*?</script>")
STYLE_RE = re.compile(r"(?is)<style.*?>.*?</style>")
TAG_RE = re.compile(r"(?is)<[^>]+>")
TITLE_RE = re.compile(r"(?is)<title[^>]*>(.*?)</title>")
WS_RE = re.compile(r"\s+")
WORD_RE = re.compile(r"[a-z0-9]{3,}")
def _strip_html(raw: str) -> str:
cleaned = SCRIPT_RE.sub(" ", raw or "")
cleaned = STYLE_RE.sub(" ", cleaned)
cleaned = TAG_RE.sub(" ", cleaned)
return WS_RE.sub(" ", cleaned).strip()
def _extract_title(raw_html: str) -> str:
match = TITLE_RE.search(raw_html or "")
if not match:
return ""
value = WS_RE.sub(" ", str(match.group(1) or "")).strip()
return value[:280]
def _normalize_url(url: str) -> str:
raw = str(url or "").strip()
if not raw:
return ""
try:
parsed = urlparse(raw)
except Exception:
return ""
if parsed.scheme not in {"http", "https"}:
return ""
cleaned = parsed._replace(fragment="")
return urlunparse(cleaned).strip()
def _hash_text(value: str) -> str:
return hashlib.sha256(str(value or "").encode("utf-8")).hexdigest()
def _tokenize(value: str) -> List[str]:
return WORD_RE.findall(str(value or "").lower())
def _estimate_tokens(value: str) -> int:
return max(1, int(len(str(value or "")) / 4))
def _sparse_embedding(value: str, max_terms: int = 80) -> Dict[str, float]:
tokens = _tokenize(value)
if not tokens:
return {}
counts: Dict[str, int] = {}
for token in tokens:
counts[token] = counts.get(token, 0) + 1
ordered = sorted(counts.items(), key=lambda item: item[1], reverse=True)[:max_terms]
norm = sum(freq * freq for _, freq in ordered) ** 0.5 or 1.0
return {token: float(freq) / norm for token, freq in ordered}
def _sparse_cosine(left: Dict[str, float], right: Dict[str, float]) -> float:
if not left or not right:
return 0.0
if len(left) > len(right):
left, right = right, left
score = 0.0
for token, value in left.items():
score += float(value) * float(right.get(token, 0.0))
return float(score)
# Render free tier (512MB) cannot host more than ONE Chromium instance at
# a time without OOMing the FastAPI worker. Use a process-wide semaphore
# to serialize browser-fallback fetches across crawl runs. Tunable via env
# `KNOWLEDGE_BROWSER_MAX_CONCURRENCY` for paid tiers with more headroom.
def _build_browser_semaphore() -> threading.Semaphore:
cap = max(env_int("KNOWLEDGE_BROWSER_MAX_CONCURRENCY", 1), 1)
return threading.Semaphore(cap)
_BROWSER_SEMAPHORE: threading.Semaphore = _build_browser_semaphore()
class KnowledgeMemoryService:
"""Persistent source-memory service with crawl + lexical retrieval."""
def __init__(self):
self._lock = threading.Lock()
self._running_runs: set[str] = set()
@property
def crawl_enabled(self) -> bool:
return env_bool("KNOWLEDGE_CRAWL_ENABLED", True)
@property
def browser_fallback_enabled(self) -> bool:
return env_bool("KNOWLEDGE_BROWSER_FALLBACK_ENABLED", True)
@property
def embeddings_enabled(self) -> bool:
return env_bool("KNOWLEDGE_EMBEDDINGS_ENABLED", False)
def start_crawl_for_source_version(
self,
*,
workspace_id: UUID,
source_id: UUID,
source_version_id: UUID,
trigger: KnowledgeCrawlTrigger,
created_by: Optional[str],
run_async: bool = True,
) -> KnowledgeCrawlRun:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
# Single-flight per source: if any run is currently QUEUED or
# RUNNING for this source, skip starting a duplicate. Two
# parallel crawl runs on the same source list saturate Render
# free tier RAM (each browser_fallback pass spawns a Chromium).
existing = repo.list_crawl_runs_for_source(source_id, workspace_id, limit=20)
in_flight = [
r for r in existing
if r.status in (KnowledgeCrawlStatus.QUEUED, KnowledgeCrawlStatus.RUNNING)
]
if in_flight:
logger.info(
"knowledge_crawl: skipping duplicate start (run already in flight)",
extra={
"source_id": str(source_id),
"in_flight_run_ids": [str(r.id) for r in in_flight],
},
)
return in_flight[0]
run = repo.create_crawl_run(
KnowledgeCrawlRun(
workspace_id=workspace_id,
source_id=source_id,
source_version_id=source_version_id,
trigger=trigger,
status=KnowledgeCrawlStatus.QUEUED,
phase=KnowledgeCrawlPhase.HTTP_FETCH,
totals={
"total": 0,
"success": 0,
"failed": 0,
"unreadable": 0,
"indexed_pages": 0,
"indexed_chunks": 0,
},
created_by=created_by,
)
)
if not self.crawl_enabled:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.CANCELLED.value,
"completed_at": datetime.now(),
"totals": {**(run.totals or {}), "failed": int((run.totals or {}).get("failed", 0))},
},
)
return run
if run_async:
thread = threading.Thread(
target=self._run_crawl_guarded,
kwargs={"run_id": run.id, "browser_fallback": False},
daemon=True,
name=f"knowledge-crawl-{run.id}",
)
thread.start()
else:
self._run_crawl_guarded(run.id, browser_fallback=False)
return run
def start_browser_fallback(self, run_id: UUID) -> None:
thread = threading.Thread(
target=self._run_crawl_guarded,
kwargs={"run_id": run_id, "browser_fallback": True},
daemon=True,
name=f"knowledge-browser-fallback-{run_id}",
)
thread.start()
def recover_orphan_runs(self) -> int:
"""Riprende i crawl run lasciati in queued/running da un crash o restart.
Da chiamare al boot del processo. RUNNING viene riportato a QUEUED
(l'avanzamento committato turno-per-turno è preservato sui chunk indicizzati,
ma il run riparte dal task scheduler interno). Idempotente.
Single-flight per source_id: se lo stesso source ha N run orphan
(capita quando l'utente cliccava 'Reindicizza' due volte prima del
single-flight check in start_crawl_for_source_version), recupera
solo il più recente e marca gli altri come CANCELLED. Evita il
problema OOM su Render free tier dove 2 Chromium paralleli sui
stessi URL saturavano la RAM.
"""
if not self.crawl_enabled:
return 0
statuses = [KnowledgeCrawlStatus.QUEUED.value, KnowledgeCrawlStatus.RUNNING.value]
recovered = 0
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
try:
orphans = repo.list_orphan_crawl_runs(statuses)
except Exception:
logger.exception("knowledge-recovery: list_orphan_crawl_runs failed")
return 0
# Dedup per source: keep the newest, cancel the rest.
from collections import defaultdict
by_source: Dict[str, List[KnowledgeCrawlRun]] = defaultdict(list)
for run in orphans:
by_source[str(run.source_id)].append(run)
keep: List[KnowledgeCrawlRun] = []
duplicates: List[KnowledgeCrawlRun] = []
for source_id, runs in by_source.items():
runs.sort(key=lambda r: r.created_at or datetime.min, reverse=True)
keep.append(runs[0])
duplicates.extend(runs[1:])
if duplicates:
logger.warning(
"knowledge-recovery: cancelling duplicate orphan runs",
extra={
"kept": [str(r.id) for r in keep],
"cancelled": [str(r.id) for r in duplicates],
},
)
for dup in duplicates:
try:
repo.update_crawl_run(
dup.id,
dup.workspace_id,
{
"status": KnowledgeCrawlStatus.CANCELLED.value,
"completed_at": datetime.now(),
"totals": {
**(dup.totals or {}),
"error": "cancelled_duplicate_orphan",
},
},
)
except Exception:
logger.exception(
"knowledge-recovery: cancel duplicate failed",
extra={"run_id": str(dup.id)},
)
for run in keep:
if run.status == KnowledgeCrawlStatus.RUNNING:
try:
repo.update_crawl_run(
run.id,
run.workspace_id,
{"status": KnowledgeCrawlStatus.QUEUED.value},
)
except Exception:
logger.exception(
"knowledge-recovery: reset RUNNING->QUEUED failed",
extra={"run_id": str(run.id)},
)
continue
try:
session.commit()
except Exception:
session.rollback()
for run in keep:
run_key = str(run.id)
with self._lock:
if run_key in self._running_runs:
continue
logger.info(
"knowledge-recovery: respawning crawl run",
extra={"run_id": str(run.id), "previous_status": run.status.value},
)
thread = threading.Thread(
target=self._run_crawl_guarded,
kwargs={"run_id": run.id, "browser_fallback": False},
daemon=True,
name=f"knowledge-crawl-recover-{run.id}",
)
thread.start()
recovered += 1
return recovered
def _run_crawl_guarded(self, run_id: UUID, browser_fallback: bool) -> None:
"""Background-thread entry point. Catches and *persists* exceptions so
that silent failures (the daemon dying without trace) become visible
on the KnowledgeCrawlRun row instead of vanishing.
"""
run_key = str(run_id)
with self._lock:
if run_key in self._running_runs:
return
self._running_runs.add(run_key)
try:
if not browser_fallback:
delay_ms = max(env_int("KNOWLEDGE_CRAWL_START_DELAY_MS", 600), 0)
if delay_ms:
time.sleep(delay_ms / 1000.0)
logger.info(
"knowledge_crawl: starting",
extra={"run_id": run_key, "browser_fallback": browser_fallback},
)
self.run_crawl(run_id=run_id, browser_fallback=browser_fallback)
logger.info("knowledge_crawl: completed", extra={"run_id": run_key})
except Exception as exc:
logger.exception(
"knowledge_crawl: run failed",
extra={"run_id": run_key, "error": str(exc)[:300]},
)
# Persist the failure on the run row so the operator can see
# *why* the crawl never produced chunks.
try:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
run = repo.get_crawl_run(run_id)
if run:
summary = dict(run.summary or {})
summary["fatal_error"] = str(exc)[:1000]
summary["traceback_excerpt"] = tb.splitlines()[-1][:300] if tb else ""
repo.update_crawl_run(
run_id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.FAILED.value,
"completed_at": datetime.now(),
"summary": summary,
},
)
except Exception as inner: # pragma: no cover
_emit(f"could not persist failure for run={run_id}: {inner}")
finally:
with self._lock:
self._running_runs.discard(run_key)
def run_crawl(self, *, run_id: UUID, browser_fallback: bool = False) -> Optional[KnowledgeCrawlRun]:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
run = repo.get_crawl_run(run_id)
if not run:
return None
if browser_fallback:
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.RUNNING.value,
"phase": KnowledgeCrawlPhase.BROWSER_FALLBACK.value,
},
)
else:
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.RUNNING.value,
"phase": KnowledgeCrawlPhase.HTTP_FETCH.value,
"started_at": datetime.now(),
},
)
source_version = repo.get_version(run.source_id, run.source_version_id, run.workspace_id)
if not source_version:
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.FAILED.value,
"completed_at": datetime.now(),
"totals": {
"total": 0,
"success": 0,
"failed": 1,
"unreadable": 0,
"indexed_pages": 0,
"indexed_chunks": 0,
"error": "source_version_not_found",
},
},
)
return repo.get_crawl_run(run.id)
rows = list((source_version.parsed_payload or {}).get("rows", []) or [])
urls: List[str] = []
for row in rows:
normalized = _normalize_url(str(row.get("source_url", "") or ""))
if normalized:
urls.append(normalized)
dedup_urls = list(dict.fromkeys(urls))
if browser_fallback:
unreadable_pages = repo.list_pages_for_run_unreadable(run)
dedup_urls = [page.url_canonical for page in unreadable_pages if page.url_canonical]
if browser_fallback:
previous = dict(run.totals or {})
totals = {
"total": int(previous.get("total") or len(dedup_urls)),
"success": int(previous.get("success") or 0),
"failed": int(previous.get("failed") or 0),
"unreadable": int(previous.get("unreadable") or len(dedup_urls)),
"indexed_pages": int(previous.get("indexed_pages") or 0),
"indexed_chunks": int(previous.get("indexed_chunks") or 0),
}
else:
totals = {
"total": len(dedup_urls),
"success": 0,
"failed": 0,
"unreadable": 0,
"indexed_pages": 0,
"indexed_chunks": 0,
}
repo.update_crawl_run(run.id, run.workspace_id, {"totals": totals})
cancelled = False
for index, url in enumerate(dedup_urls):
# Check for an external cancel signal every N iterations.
# The /cancel endpoint sets status=CANCELLED on the DB row;
# the worker thread only notices that on the next probe.
# Probing every iteration would double DB load on huge lists,
# so we batch — 10 URLs ≈ a few seconds of work.
if index % 10 == 0:
fresh = repo.get_crawl_run(run.id, run.workspace_id)
if fresh and fresh.status == KnowledgeCrawlStatus.CANCELLED:
cancelled = True
break
if browser_fallback:
fetch_data = self._fetch_url_browser(url)
fetch_method = "browser"
else:
fetch_data = self._fetch_url_http(url)
fetch_method = "http"
page = KnowledgePage(
workspace_id=run.workspace_id,
source_id=run.source_id,
source_version_id=run.source_version_id,
url=url,
url_canonical=url,
title=str(fetch_data.get("title") or "")[:280],
content_type=str(fetch_data.get("content_type") or "")[:250],
http_status=fetch_data.get("http_status"),
fetch_status=str(fetch_data.get("status") or "unknown"),
fetch_method=fetch_method,
content_hash=fetch_data.get("content_hash"),
raw_chars=int(fetch_data.get("raw_chars") or 0),
cleaned_text=str(fetch_data.get("text") or ""),
fetched_at=datetime.now(),
error=str(fetch_data.get("error") or "")[:1000] or None,
)
persisted_page = repo.upsert_page(page)
ok_status = str(fetch_data.get("status") or "")
if ok_status in {"ok", "browser_ok", "file_extract"}:
totals["success"] += 1
if browser_fallback and totals["unreadable"] > 0:
totals["unreadable"] -= 1
chunks = self._build_chunks_for_page(
workspace_id=run.workspace_id,
source_id=run.source_id,
source_version_id=run.source_version_id,
page_id=persisted_page.id,
text=page.cleaned_text,
)
saved_chunks = repo.replace_chunks_for_page(
persisted_page.id,
run.workspace_id,
chunks,
)
totals["indexed_pages"] += 1
totals["indexed_chunks"] += len(saved_chunks)
elif ok_status in {"unreadable_http", "empty_content"}:
if not browser_fallback:
totals["unreadable"] += 1
else:
totals["failed"] += 1
repo.update_crawl_run(run.id, run.workspace_id, {"totals": dict(totals)})
# Commit after every page so:
# (1) live progress is visible via the API
# (2) we don't hold a SQLite lock for the entire crawl
# (which can take many minutes on a 800+ URL list)
# (3) on a daemon crash we don't lose pages already fetched.
try:
session.commit()
except Exception:
session.rollback()
if cancelled:
# Operator-requested stop — finalize as CANCELLED, never
# auto-trigger fallback, never recurse. Page/chunk progress
# already committed up to the cancel point is preserved.
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": KnowledgeCrawlStatus.CANCELLED.value,
"phase": KnowledgeCrawlPhase.HTTP_FETCH.value,
"completed_at": datetime.now(),
"totals": {**totals, "error": "cancelled_by_operator"},
},
)
logger.info(
"knowledge_crawl: cancelled by operator",
extra={"run_id": str(run.id), "processed": index},
)
return repo.get_crawl_run(run.id)
final_status = KnowledgeCrawlStatus.COMPLETED.value
final_phase = KnowledgeCrawlPhase.INDEXING.value
should_auto_browser = (
(not browser_fallback)
and totals["unreadable"] > 0
and self.browser_fallback_enabled
and env_bool("KNOWLEDGE_CRAWL_AUTO_BROWSER_FALLBACK", True)
)
if (not browser_fallback) and totals["unreadable"] > 0:
final_status = (
KnowledgeCrawlStatus.AWAITING_BROWSER_FALLBACK.value
if self.browser_fallback_enabled and not should_auto_browser
else (
KnowledgeCrawlStatus.RUNNING.value
if should_auto_browser
else KnowledgeCrawlStatus.COMPLETED.value
)
)
final_phase = (
KnowledgeCrawlPhase.BROWSER_FALLBACK.value
if should_auto_browser
else KnowledgeCrawlPhase.HTTP_FETCH.value
)
repo.update_crawl_run(
run.id,
run.workspace_id,
{
"status": final_status,
"phase": final_phase,
"completed_at": (
None if should_auto_browser else datetime.now()
),
"totals": totals,
},
)
# Auto-chain browser fallback OUTSIDE the DB session: a second
# invocation of run_crawl() reopens its own session. This is
# important because the SPA-heavy URL lists in the wild produce
# ~70% unreadable on http_fetch, and forcing the operator to
# click the fallback button on every run is friction with no
# safety value.
if should_auto_browser:
logger.info(
"knowledge_crawl: auto-triggering browser fallback",
extra={
"run_id": str(run_id),
"unreadable": totals["unreadable"],
"indexed_pages": totals["indexed_pages"],
},
)
try:
return self.run_crawl(run_id=run_id, browser_fallback=True)
except Exception:
logger.exception(
"knowledge_crawl: auto browser fallback failed",
extra={"run_id": str(run_id)},
)
# Fall through and return the http-only result; the operator
# can still retry the fallback manually.
# Frequency-based boilerplate cleanup automatico DOPO che il run
# è realmente terminato. Si attiva quando lo status finale è
# COMPLETED e nessun browser-fallback è pendente: vale sia nel
# path http-only sia nell'inner call dell'auto-browser-fallback
# (che è la chiamata che porta il run a COMPLETED quando il
# fallback è eseguito).
# Best-effort: errori qui non fanno fallire il run.
if (
final_status == KnowledgeCrawlStatus.COMPLETED.value
and not should_auto_browser
and env_bool("KNOWLEDGE_AUTO_BOILERPLATE_CLEANUP", True)
):
try:
outcome = self.cleanup_source_boilerplate(
workspace_id=run.workspace_id,
source_id=run.source_id,
dry_run=False,
)
logger.info(
"knowledge_crawl: post-crawl boilerplate cleanup applied",
extra={
"run_id": str(run.id),
"source_id": str(run.source_id),
"blocks_detected": outcome["totals"]["boilerplate_blocks_detected"],
"pages_modified": outcome["totals"]["pages_modified"],
"chars_removed": outcome["totals"]["chars_removed"],
"chunks_before": outcome["totals"]["chunks_before"],
"chunks_after": outcome["totals"]["chunks_after"],
},
)
except Exception:
logger.exception(
"knowledge_crawl: post-crawl boilerplate cleanup failed",
extra={"run_id": str(run.id), "source_id": str(run.source_id)},
)
with db.get_session() as session:
repo = KnowledgeRepository(session)
return repo.get_crawl_run(run_id)
def _fetch_url_http(self, url: str) -> Dict[str, Any]:
if not _is_safe_public_url(url):
return {"status": "blocked_unsafe_url", "error": "unsafe_or_private_url"}
timeout_seconds = max(env_int("KNOWLEDGE_CRAWL_TIMEOUT_SECONDS", 12), 2)
max_bytes = max(env_int("KNOWLEDGE_CRAWL_MAX_BYTES", 2_000_000), 32_000)
min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)
retries = max(env_int("KNOWLEDGE_CRAWL_HTTP_RETRIES", 2), 0)
last_error = ""
for attempt in range(retries + 1):
try:
with httpx.Client(timeout=timeout_seconds, follow_redirects=True) as client:
response = client.get(
url,
headers={
"User-Agent": "AI-Tester-KnowledgeCrawler/1.0",
"Accept": "text/html,application/pdf,application/json,text/plain,*/*;q=0.1",
},
)
raw_bytes = response.content or b""
if len(raw_bytes) > max_bytes:
return {
"status": "too_large",
"http_status": int(response.status_code),
"content_type": (response.headers.get("content-type") or "").lower(),
"error": f"content_too_large>{max_bytes}",
}
content_type = (response.headers.get("content-type") or "").lower()
if int(response.status_code) >= 400:
return {
"status": "http_error",
"http_status": int(response.status_code),
"content_type": content_type,
"error": f"http_{int(response.status_code)}",
}
title = ""
text = ""
if "application/pdf" in content_type or url.lower().endswith(".pdf"):
text = self._extract_text_from_pdf_bytes(raw_bytes)
title = urlparse(url).path.rsplit("/", 1)[-1]
elif "application/json" in content_type:
decoded = raw_bytes.decode("utf-8", errors="replace")
compact = WS_RE.sub(" ", decoded).strip()
text = compact[:80000]
title = urlparse(url).hostname or "JSON source"
else:
decoded = raw_bytes.decode("utf-8", errors="replace")
title = _extract_title(decoded) or (urlparse(url).hostname or "")
text = _strip_html(decoded)[:80000]
if len(text.strip()) < min_chars:
return {
"status": "unreadable_http",
"http_status": int(response.status_code),
"content_type": content_type,
"title": title,
"text": text,
"raw_chars": len(text),
"error": "insufficient_readable_text",
}
return {
"status": "ok",
"http_status": int(response.status_code),
"content_type": content_type,
"title": title,
"text": text,
"raw_chars": len(text),
"content_hash": _hash_text(text),
}
except Exception as exc:
last_error = str(exc)[:220]
if attempt < retries:
time.sleep(0.3 * (attempt + 1))
continue
return {"status": "fetch_error", "error": last_error or "unknown_fetch_error"}
def _fetch_url_browser(self, url: str) -> Dict[str, Any]:
"""SPA-aware browser fetch. Tries crawl4ai first (better extraction
on JS-rendered sites), falls back to a minimal Playwright sync
path if crawl4ai is missing or fails.
Wrapped in a process-wide semaphore (_BROWSER_SEMAPHORE) so that
even when two crawl runs are active in parallel, only one Chromium
instance is alive at a time on tight-RAM hosts (Render free tier).
Both paths share the same return contract so callers don't care
which one ran:
{ status: ok|browser_ok|browser_failed|... ,
title, text, raw_chars, content_hash, http_status,
content_type, error? }
"""
if not self.browser_fallback_enabled:
return {"status": "browser_failed", "error": "browser_fallback_disabled"}
if not _is_safe_public_url(url):
return {"status": "blocked_unsafe_url", "error": "unsafe_or_private_url"}
# Acquire a slot. With max_concurrency=1 (default) this serializes
# all Chromium spawns. With higher caps it caps the number of
# concurrent browsers — useful on paid tiers with more RAM.
timeout_s = max(env_int("KNOWLEDGE_BROWSER_QUEUE_WAIT_S", 600), 30)
if not _BROWSER_SEMAPHORE.acquire(timeout=timeout_s):
return {
"status": "browser_failed",
"error": "browser_semaphore_timeout",
}
try:
# Primary path: crawl4ai if available and not disabled by env.
if env_bool("KNOWLEDGE_CRAWL_USE_CRAWL4AI", True):
try:
from crawl4ai import AsyncWebCrawler # type: ignore[import-not-found] # noqa: F401
return self._fetch_with_crawl4ai(url)
except ImportError:
logger.warning(
"knowledge_crawl: crawl4ai not installed, falling back to "
"Playwright sync. pip install crawl4ai to enable."
)
except Exception as exc:
logger.warning(
"knowledge_crawl: crawl4ai failed, falling back to Playwright sync",
extra={"url": url, "error": str(exc)[:200]},
)
# Fallback path: minimal Playwright sync, kept as safety net for
# the rare case crawl4ai blows up on a specific URL.
return self._fetch_with_playwright_sync(url)
finally:
_BROWSER_SEMAPHORE.release()
def _fetch_with_crawl4ai(self, url: str) -> Dict[str, Any]:
"""Run crawl4ai's AsyncWebCrawler synchronously by spinning up a
short-lived event loop. The caller is sync (`run_crawl()`),
keeping the rest of the pipeline stable while we benefit from
crawl4ai's smart Markdown extraction."""
import asyncio
from crawl4ai import AsyncWebCrawler, CrawlerRunConfig # type: ignore[import-not-found]
from crawl4ai.async_configs import BrowserConfig # type: ignore[import-not-found]
timeout_ms = max(env_int("KNOWLEDGE_BROWSER_FALLBACK_TIMEOUT_MS", 30000), 5000)
min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)
async def _run() -> Dict[str, Any]:
browser_config = BrowserConfig(
headless=True,
java_script_enabled=True,
user_agent="AI-Tester-KnowledgeCrawler/2.0 (+crawl4ai)",
# Render free/starter has tight RAM — disable heavy features
# we don't need for content extraction.
light_mode=True,
)
run_config = CrawlerRunConfig(
page_timeout=timeout_ms,
wait_until="domcontentloaded",
# Drop common nav/footer/cookie noise by tag heuristics —
# crawl4ai's default markdown filter is good enough for
# operator-curated link lists.
excluded_tags=["nav", "footer", "header", "aside", "form", "script", "style"],
remove_overlay_elements=True,
word_count_threshold=10,
)
async with AsyncWebCrawler(config=browser_config) as crawler:
return await crawler.arun(url=url, config=run_config)
try:
try:
loop = asyncio.get_event_loop()
if loop.is_running():
# Inside an already-running loop (rare from sync caller,
# but defensive). Spin a separate thread.
raise RuntimeError("nested_loop")
except RuntimeError:
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(_run())
finally:
loop.close()
if not result or not getattr(result, "success", False):
err = (
str(getattr(result, "error_message", "") or "")[:220]
if result
else "no_result"
)
return {"status": "browser_failed", "error": err or "crawl4ai_failed"}
# crawl4ai returns markdown (string) and metadata
text = (getattr(result, "markdown", "") or "").strip()
if not text:
# Last-resort: cleaned plain text from the crawler.
text = (getattr(result, "cleaned_html", "") or "").strip()
text = WS_RE.sub(" ", text).strip()
metadata = getattr(result, "metadata", None) or {}
title = str(metadata.get("title") or "")[:280]
http_status = int(getattr(result, "status_code", 0) or 200)
if len(text) < min_chars:
return {
"status": "browser_failed",
"title": title,
"text": text,
"raw_chars": len(text),
"error": "insufficient_readable_text_browser",
}
return {
"status": "browser_ok",
"http_status": http_status,
"content_type": "text/markdown",
"title": title,
"text": text[:80000],
"raw_chars": len(text),
"content_hash": _hash_text(text),
}
except Exception as exc:
return {"status": "browser_failed", "error": f"crawl4ai:{str(exc)[:200]}"}
def _fetch_with_playwright_sync(self, url: str) -> Dict[str, Any]:
"""Legacy Playwright sync path. Kept as safety net behind crawl4ai."""
try:
from playwright.sync_api import sync_playwright
except Exception:
return {"status": "browser_failed", "error": "playwright_not_available"}
timeout_ms = max(env_int("KNOWLEDGE_BROWSER_FALLBACK_TIMEOUT_MS", 30000), 5000)
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url, wait_until="networkidle", timeout=timeout_ms)
title = str(page.title() or "")
text = str(
page.evaluate(
"() => document && document.body ? (document.body.innerText || '') : ''"
)
or ""
)
browser.close()
cleaned = WS_RE.sub(" ", text).strip()
min_chars = max(env_int("KNOWLEDGE_CRAWL_MIN_TEXT_CHARS", 120), 20)
if len(cleaned) < min_chars:
return {
"status": "browser_failed",
"title": title[:280],
"text": cleaned,
"raw_chars": len(cleaned),
"error": "insufficient_readable_text_browser",
}
return {
"status": "browser_ok",
"http_status": 200,
"content_type": "text/html",
"title": title[:280],
"text": cleaned[:80000],
"raw_chars": len(cleaned),
"content_hash": _hash_text(cleaned),
}
except Exception as exc:
return {"status": "browser_failed", "error": str(exc)[:220]}
def _extract_text_from_pdf_bytes(self, payload: bytes) -> str:
try:
from pypdf import PdfReader
except Exception:
return ""
try:
reader = PdfReader(io.BytesIO(payload))
except Exception:
return ""
chunks: List[str] = []
for page in reader.pages:
text = WS_RE.sub(" ", str(page.extract_text() or "")).strip()
if text:
chunks.append(text)
return "\n".join(chunks)[:80000]
def _build_chunks_for_page(
self,
*,
workspace_id: UUID,
source_id: UUID,
source_version_id: UUID,
page_id: UUID,
text: str,
) -> List[KnowledgeChunk]:
chunk_size = max(env_int("KNOWLEDGE_CHUNK_SIZE_CHARS", 1200), 200)
overlap = max(env_int("KNOWLEDGE_CHUNK_OVERLAP_CHARS", 180), 0)
compact = WS_RE.sub(" ", str(text or "")).strip()
if not compact:
return []
if len(compact) <= chunk_size:
compact_chunks = [compact]
else:
compact_chunks = []
cursor = 0
while cursor < len(compact):
end = min(cursor + chunk_size, len(compact))
chunk = compact[cursor:end].strip()
if chunk:
compact_chunks.append(chunk)
if end >= len(compact):
break
cursor = max(0, end - overlap)
dedup = {}
for idx, chunk in enumerate(compact_chunks):
chunk_hash = _hash_text(chunk)
if chunk_hash in dedup:
continue
dedup[chunk_hash] = KnowledgeChunk(
workspace_id=workspace_id,
page_id=page_id,
source_id=source_id,
source_version_id=source_version_id,
chunk_index=idx,
chunk_text=chunk,
token_estimate=_estimate_tokens(chunk),
chunk_hash=chunk_hash,
embedding_json=_sparse_embedding(chunk) if self.embeddings_enabled else None,
)
return list(dedup.values())
def cleanup_source_boilerplate(
self,
*,
workspace_id: UUID,
source_id: Optional[UUID] = None,
dry_run: bool = True,
freq_threshold: Optional[float] = None,
boundary_threshold: Optional[float] = None,
head_window: Optional[int] = None,
tail_window: Optional[int] = None,
min_pages: Optional[int] = None,
) -> Dict[str, Any]:
"""Frequency-based + boundary heuristics boilerplate cleanup.
Per ciascuna source (filtrata o tutte della workspace), considera SOLO
la version ACTIVE: identifica i blocchi che si ripetono tra le pagine,
li rimuove dal `cleaned_text`, ricostruisce i chunks. Tutto in
transazione single per ogni source. Se `dry_run=True`, non scrive,
ritorna solo lo stimato.
Le soglie usano default ragionevoli (env-overridabili) se i parametri
non sono passati esplicitamente.
"""
from src.core.boilerplate_detector import (
BoilerplatePage,
detect_boilerplate_blocks,
detect_common_prefixes,
detect_repeated_substrings,
strip_boilerplate,
strip_common_prefixes,
strip_repeated_substrings,
)
ft = float(freq_threshold) if freq_threshold is not None else float(env_int("KNOWLEDGE_BOILERPLATE_FREQ_PCT", 70)) / 100.0
bt = float(boundary_threshold) if boundary_threshold is not None else float(env_int("KNOWLEDGE_BOILERPLATE_BOUNDARY_PCT", 50)) / 100.0
hw = int(head_window) if head_window is not None else env_int("KNOWLEDGE_BOILERPLATE_HEAD_WINDOW", 5)
tw = int(tail_window) if tail_window is not None else env_int("KNOWLEDGE_BOILERPLATE_TAIL_WINDOW", 5)
mp = int(min_pages) if min_pages is not None else env_int("KNOWLEDGE_BOILERPLATE_MIN_PAGES", 5)
db = get_db()
summary: Dict[str, Any] = {
"dry_run": dry_run,
"freq_threshold": ft,
"boundary_threshold": bt,
"sources": [],
"totals": {
"pages_processed": 0,
"pages_modified": 0,
"blocks_removed_from_pages": 0,
"chars_removed": 0,
"chunks_before": 0,
"chunks_after": 0,
"boilerplate_blocks_detected": 0,
},
}
with db.get_session() as session:
repo = KnowledgeRepository(session)
if source_id is not None:
source = repo.get_source(source_id, workspace_id)
source_iter = [source] if source else []
else:
source_iter = list(repo.list_sources(workspace_id))
for source in source_iter:
versions = repo.list_versions(source.id, workspace_id)
active = next(
(v for v in versions if v.state == KnowledgeVersionState.ACTIVE),
None,
)
if not active:
continue
pages = repo.list_pages_for_source_version(active.id, workspace_id)
source_entry: Dict[str, Any] = {
"source_id": str(source.id),
"source_name": source.name,
"version_id": str(active.id),
"pages": len(pages),
"skipped_reason": None,
"boilerplate_blocks": [],
"pages_modified": 0,
"blocks_removed_from_pages": 0,
"chars_removed": 0,
"chunks_before": 0,
"chunks_after": 0,
}
if len(pages) < mp:
source_entry["skipped_reason"] = f"too_few_pages ({len(pages)} < {mp})"
summary["sources"].append(source_entry)
continue
# Frequency analysis a 2 livelli:
# 1) per HOST: cattura header/footer del sito intero.
# 2) per (HOST, primo path-segment): cattura header/footer di
# SEZIONE — siti grandi (cultura.regione.campania.it) hanno
# sotto-portali con loro propria intestazione che si ripete
# solo nelle pagine di quella sezione, sotto soglia globale.
# Le fingerprint trovate vengono unite e applicate insieme.
from urllib.parse import urlparse
from collections import defaultdict as _dd
def _page_groups(pages_in: List[Any]) -> Tuple[Dict[str, List[Any]], Dict[str, List[Any]]]:
by_host: Dict[str, List[Any]] = _dd(list)
by_section: Dict[str, List[Any]] = _dd(list)
for p in pages_in:
host = ""
path = ""
try:
parsed = urlparse(p.url or p.url_canonical or "")
host = (parsed.hostname or "").lower()
path = parsed.path or ""
except Exception:
host, path = "", ""
host_key = host or "_unknown"
by_host[host_key].append(p)
# Primo segmento del path, se non vuoto.
seg = ""
for token in (path or "").split("/"):
t = token.strip()
if t:
seg = t.lower()
break
if seg:
by_section[f"{host_key}/{seg}"].append(p)
return by_host, by_section
groups_host, groups_section = _page_groups(pages)
merged_fingerprints: Set[str] = set()
merged_samples: Dict[str, str] = {}
merged_counts: Dict[str, int] = {}
merged_reasons: Dict[str, str] = {}
pages_analyzed_total = 0
def _run_detection(group_label: str, group_pages: List[Any]) -> None:
nonlocal pages_analyzed_total
if len(group_pages) < mp:
return
sub_report = detect_boilerplate_blocks(
[BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in group_pages],
freq_threshold=ft,
boundary_threshold=bt,
head_window=hw,
tail_window=tw,
min_pages=mp,
)
pages_analyzed_total += sub_report.pages_analyzed
for fp in sub_report.boilerplate_fingerprints:
merged_fingerprints.add(fp)
merged_samples.setdefault(fp, sub_report.sample_by_fingerprint.get(fp, ""))
merged_counts[fp] = merged_counts.get(fp, 0) + sub_report.page_count_by_fingerprint.get(fp, 0)
if fp not in merged_reasons:
merged_reasons[fp] = f"{group_label}:{sub_report.reason_by_fingerprint.get(fp, '?')}"
# 1° passaggio: per host (header/footer del sito intero).
for host, host_pages in groups_host.items():
_run_detection(host if host != "_unknown" else "no-host", host_pages)
# 2° passaggio: per (host, sezione) — cattura header di
# sotto-portali. Le fingerprint duplicate vengono ignorate
# dal set.
for section_key, section_pages in groups_section.items():
_run_detection(section_key, section_pages)
# 3° passaggio: COMMON PREFIX detection per (host, sezione).
# Cattura header densi dove titolo+menu sono concatenati
# senza separatori sintattici (no newline, no punctuation):
# il blocco-detector li tratta come unico blocco unico per
# pagina, quindi non li rileva come ricorrenti. Il common-
# prefix invece confronta i primi N char di ciascuna pagina
# del gruppo e individua l'header condiviso. Solo per gruppi
# con ≥ mp pagine.
common_prefixes_by_group: Dict[str, List[str]] = {}
for section_key, section_pages in groups_section.items():
if len(section_pages) < mp:
continue
prefixes = detect_common_prefixes(
[BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in section_pages],
threshold=bt, # boundary threshold (default 0.5): più permissivo del 70%
min_pages=mp,
)
if prefixes:
common_prefixes_by_group[section_key] = prefixes
for px in prefixes:
# Rappresento il prefix come fingerprint speciale
# per visibilità in source_entry. Sample = primi 200
# char.
fp_key = f"__prefix__::{section_key}::{px[:64]}"
if fp_key not in merged_samples:
merged_samples[fp_key] = px[:200]
merged_counts[fp_key] = sum(
1 for p in section_pages
if (p.cleaned_text or '').strip().lower().startswith(px[:80])
)
merged_reasons[fp_key] = f"{section_key}:common_prefix:{len(px)}chars"
# Mappa pagina -> lista prefissi applicabili: per ogni pagina
# trovo a quale section_key appartiene, e prendo i prefissi di
# quel gruppo.
prefix_for_page: Dict[str, List[str]] = {}
for section_key, section_pages in groups_section.items():
if section_key not in common_prefixes_by_group:
continue
pxs = common_prefixes_by_group[section_key]
for p in section_pages:
prefix_for_page.setdefault(str(p.id), []).extend(pxs)
# 4° passaggio: SHINGLING (substring ripetuti). Cattura
# menu/header/footer concatenati a contenuto unico per pagina
# (es. titolo + menu + content): nessuno dei tre detector
# precedenti li prende perché il blocco "titolo + menu" ha
# fingerprint unica per pagina e il prefisso è anch'esso
# unico (il titolo cambia). Lo shingling trova frasi/menu di
# 10 parole ripetuti in ≥ 50% delle pagine del gruppo,
# ovunque si trovino. Lavoro solo su (host, sezione) per non
# esplodere su workspace globale (≥10k pagine).
shingles_for_page: Dict[str, List[str]] = {}
for section_key, section_pages in groups_section.items():
if len(section_pages) < mp:
continue
shingles = detect_repeated_substrings(
[BoilerplatePage(page_id=str(p.id), cleaned_text=p.cleaned_text or "") for p in section_pages],
n_words=10,
threshold=bt,
min_pages=mp,
)
if not shingles:
continue
for p in section_pages:
shingles_for_page.setdefault(str(p.id), []).extend(shingles)
# Registra il primo shingle per source_entry visibility
fp_key = f"__shingle__::{section_key}"
if fp_key not in merged_samples and shingles:
merged_samples[fp_key] = shingles[0][:200]
merged_counts[fp_key] = len(shingles)
merged_reasons[fp_key] = f"{section_key}:shingles:{len(shingles)}"
source_entry["pages_analyzed"] = pages_analyzed_total
source_entry["hosts"] = sorted([h for h in groups_host.keys() if groups_host[h]])
source_entry["boilerplate_blocks"] = [
{
"fingerprint_hash": str(abs(hash(fp)) % 10_000_000),
"sample": (merged_samples.get(fp, "") or "")[:200],
"page_count": merged_counts.get(fp, 0),
"reason": merged_reasons.get(fp, ""),
}
for fp in sorted(
merged_fingerprints,
key=lambda f: merged_counts.get(f, 0),
reverse=True,
)
]
summary["totals"]["boilerplate_blocks_detected"] += len(merged_fingerprints)
# Continua se ALMENO uno dei tre detector (block / prefix /
# shingle) ha trovato qualcosa. La presenza di common_prefix
# o shingles_for_page è sufficiente anche se merged_fingerprints
# è vuoto.
has_block_fp = bool(merged_fingerprints)
has_prefixes = bool(common_prefixes_by_group)
has_shingles = bool(shingles_for_page)
if not (has_block_fp or has_prefixes or has_shingles):
source_entry["skipped_reason"] = "no_boilerplate_detected"
summary["sources"].append(source_entry)
continue
fps = merged_fingerprints
# Solo il conteggio serve: usiamo COUNT(*) invece di caricare
# tutti i chunk con embedding_json (~6 KB/chunk). Fix egress
# 2026-05-22 — vedi pg_stat_statements (26.6M rows con
# questa query).
chunks_before = repo.count_chunks_for_source_version(active.id, workspace_id)
source_entry["chunks_before"] = chunks_before
summary["totals"]["chunks_before"] += chunks_before
chunks_after = chunks_before # in dry_run rimane invariato
for page in pages:
summary["totals"]["pages_processed"] += 1
original = page.cleaned_text or ""
if not original:
continue
# Apply in cascata: prefix → block → shingle. L'ordine
# conta poco (sono idempotenti su input pulito), ma
# prefix per primo riduce drasticamente il testo da
# processare nei passaggi successivi.
after_prefix = original
page_prefixes = prefix_for_page.get(str(page.id), [])
if page_prefixes:
after_prefix = strip_common_prefixes(after_prefix, page_prefixes)
after_blocks = strip_boilerplate(after_prefix, fps)
page_shingles = shingles_for_page.get(str(page.id), [])
cleaned = (
strip_repeated_substrings(after_blocks, page_shingles)
if page_shingles
else after_blocks
)
if cleaned == original:
continue
delta_chars = len(original) - len(cleaned)
source_entry["chars_removed"] += delta_chars
source_entry["pages_modified"] += 1
summary["totals"]["chars_removed"] += delta_chars
summary["totals"]["pages_modified"] += 1
# Conteggio blocchi rimossi: differenza tra blocchi-pagina
# nell'originale e nel pulito (proxy ragionevole, non
# serve esattezza chirurgica).
from src.core.boilerplate_detector import _split_blocks # type: ignore
delta_blocks = max(len(_split_blocks(original)) - len(_split_blocks(cleaned)), 0)
source_entry["blocks_removed_from_pages"] += delta_blocks
summary["totals"]["blocks_removed_from_pages"] += delta_blocks
if not dry_run:
page.cleaned_text = cleaned
repo.upsert_page(page)
new_chunks = self._build_chunks_for_page(
workspace_id=workspace_id,
source_id=source.id,
source_version_id=active.id,
page_id=page.id,
text=cleaned,
)
repo.replace_chunks_for_page(page.id, workspace_id, new_chunks)
if not dry_run:
# Stesso fix egress di chunks_before: count diretto.
chunks_after = repo.count_chunks_for_source_version(active.id, workspace_id)
source_entry["chunks_after"] = chunks_after
summary["totals"]["chunks_after"] += chunks_after
summary["sources"].append(source_entry)
if not dry_run:
session.commit()
return summary
def build_session_memory_snapshot(
self,
*,
workspace_id: UUID,
bot_id: UUID,
) -> Dict[str, Any]:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
bindings = repo.list_active_source_versions_for_bot(
workspace_id,
bot_id,
include_workspace_fallback=False,
)
source_version_ids: List[str] = []
crawl_run_ids: List[str] = []
indexed_pages = 0
indexed_chunks = 0
for item in bindings:
version = item["version"]
source_version_ids.append(str(version.id))
latest = repo.get_latest_crawl_run_for_source_version(version.id, workspace_id)
if latest:
crawl_run_ids.append(str(latest.id))
stats = repo.get_memory_stats_for_source_version(version.id, workspace_id)
indexed_pages += int(stats.get("indexed_pages") or 0)
indexed_chunks += int(stats.get("indexed_chunks") or 0)
return {
"source_version_ids": source_version_ids,
"crawl_run_ids": crawl_run_ids,
"memory_status": {
"sources_count": len(bindings),
"indexed_pages": indexed_pages,
"indexed_chunks": indexed_chunks,
"ready": indexed_chunks > 0,
},
}
def retrieve(
self,
*,
workspace_id: UUID,
bot_id: UUID,
query: str,
top_k: int = 5,
source_scope: str = "linked_only",
) -> List[Dict[str, Any]]:
query_tokens = _tokenize(query)
if not query_tokens:
return []
query_embedding = _sparse_embedding(query) if self.embeddings_enabled else {}
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
bindings = repo.list_active_source_versions_for_bot(
workspace_id,
bot_id,
include_workspace_fallback=(source_scope == "workspace_fallback"),
)
scored: List[Tuple[float, Dict[str, Any]]] = []
for item in bindings:
source = item["source"]
version = item["version"]
pages = repo.list_pages_for_source_version(version.id, workspace_id)
page_map = {str(page.id): page for page in pages}
chunks = repo.list_chunks_for_source_version(version.id, workspace_id)
for chunk in chunks:
score = self._lexical_score(query_tokens, chunk.chunk_text)
if score <= 0:
continue
semantic_score = 0.0
if self.embeddings_enabled:
stored_embedding = {}
if isinstance(chunk.embedding_json, dict):
stored_embedding = {
str(key): float(val)
for key, val in chunk.embedding_json.items()
if str(key) and isinstance(val, (int, float))
}
if not stored_embedding:
stored_embedding = _sparse_embedding(chunk.chunk_text)
semantic_score = _sparse_cosine(query_embedding, stored_embedding)
score = (score * 0.7) + (semantic_score * 0.3)
page = page_map.get(str(chunk.page_id))
scored.append(
(
score,
{
"source_id": str(source.id),
"source_name": source.name,
"version_id": str(version.id),
"page_id": str(chunk.page_id),
"chunk_id": str(chunk.id),
"url": page.url if page else "",
"title": (page.title if page else "") or source.name,
# 1500 (era 360): il judge fa match semantico
# sull'intero snippet. Con 360 char il match
# falliva su chunks lunghi dove il keyword del
# claim era oltre la soglia. 1500 copre la
# gran parte dei chunk integralmente senza
# esplodere la dimensione del prompt.
"snippet": chunk.chunk_text[:1500],
"score": round(float(score), 4),
"semantic_score": round(float(semantic_score), 4),
},
)
)
scored.sort(key=lambda item: item[0], reverse=True)
return [item[1] for item in scored[: max(1, top_k)]]
def search_chunks(
self,
*,
workspace_id: UUID,
query: str,
bot_id: Optional[UUID] = None,
top_k: int = 10,
min_score: float = 0.0,
) -> Dict[str, Any]:
"""Manual semantic search across active knowledge chunks.
Pensata per audit/verifica manuale dell'operatore: data una query,
ritorna i chunk più rilevanti delle source ATTIVE filtrate per bot
(o cross-bot se bot_id è None). Non chiama LLM, è cheap come la
search interna del judge.
Stesso scoring di retrieve(): lexical (0.7) + semantic sparse (0.3)
quando embeddings_enabled. Solo versioni is_active=true.
"""
import time as _time
started_at = _time.perf_counter()
query_tokens = _tokenize(query)
if not query_tokens:
return {
"results": [],
"stats": {
"total_chunks_scanned": 0,
"sources_scanned": 0,
"took_ms": 0,
"embeddings_enabled": self.embeddings_enabled,
},
}
query_embedding = _sparse_embedding(query) if self.embeddings_enabled else {}
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
if bot_id is not None:
bindings = repo.list_active_source_versions_for_bot(
workspace_id, bot_id, include_workspace_fallback=False
)
else:
# Cross-bot: enumera tutte le source della workspace, prendi
# SOLO la version ACTIVE di ciascuna. Coerente con il caso
# bot-scoped che usa list_active_source_versions_for_bot.
bindings = []
for source in repo.list_sources(workspace_id):
versions = repo.list_versions(source.id, workspace_id)
active = next(
(v for v in versions if v.state == KnowledgeVersionState.ACTIVE),
None,
)
if active:
bindings.append({"source": source, "version": active})
sources_scanned = len(bindings)
total_chunks_scanned = 0
scored: List[Dict[str, Any]] = []
for item in bindings:
source = item["source"]
version = item["version"]
pages = repo.list_pages_for_source_version(version.id, workspace_id)
page_map = {str(page.id): page for page in pages}
chunks = repo.list_chunks_for_source_version(version.id, workspace_id)
total_chunks_scanned += len(chunks)
for chunk in chunks:
lex = self._lexical_score(query_tokens, chunk.chunk_text)
if lex <= 0:
continue
sem = 0.0
if self.embeddings_enabled:
stored = (
chunk.embedding_json
if isinstance(chunk.embedding_json, dict)
else {}
)
if stored:
stored = {
str(k): float(v)
for k, v in stored.items()
if str(k) and isinstance(v, (int, float))
}
if not stored:
stored = _sparse_embedding(chunk.chunk_text)
sem = _sparse_cosine(query_embedding, stored)
score = (lex * 0.7) + (sem * 0.3)
else:
score = lex
if score < min_score:
continue
page = page_map.get(str(chunk.page_id)) if chunk.page_id else None
source_type_value = (
source.source_type.value
if hasattr(source.source_type, "value")
else str(source.source_type)
)
scored.append(
{
"source_id": str(source.id),
"source_name": source.name,
"source_type": source_type_value,
"version_id": str(version.id),
"version_label": version.version_label or "",
"chunk_id": str(chunk.id),
"chunk_text": chunk.chunk_text,
"score": round(float(score), 4),
"lexical_score": round(float(lex), 4),
"semantic_score": round(float(sem), 4),
"page_id": str(chunk.page_id) if chunk.page_id else None,
"page_url": page.url if page else None,
"page_title": (page.title if page else None) or source.name,
}
)
scored.sort(key=lambda r: r["score"], reverse=True)
top = scored[: max(1, int(top_k or 10))]
took_ms = int((_time.perf_counter() - started_at) * 1000)
return {
"results": top,
"stats": {
"total_chunks_scanned": total_chunks_scanned,
"sources_scanned": sources_scanned,
"took_ms": took_ms,
"embeddings_enabled": self.embeddings_enabled,
},
}
def collect_topic_candidates(
self,
*,
workspace_id: UUID,
bot_id: UUID,
max_topics: int = 80,
) -> Dict[str, Any]:
db = get_db()
with db.get_session() as session:
repo = KnowledgeRepository(session)
bindings = repo.list_active_source_versions_for_bot(
workspace_id,
bot_id,
include_workspace_fallback=False,
)
topics: List[Dict[str, str]] = []
seen = set()
pages_count = 0
chunks_count = 0
for item in bindings:
source = item["source"]
version = item["version"]
pages = repo.list_pages_for_source_version(version.id, workspace_id)
# Solo il conteggio dei chunk serve: COUNT(*) invece di
# SELECT * + len(). Le pages restano caricate perché il loop
# sotto usa `page.title` e `page.cleaned_text`.
# Fix egress 2026-05-22.
pages_count += len(pages)
chunks_count += repo.count_chunks_for_source_version(version.id, workspace_id)
for page in pages:
label = str(page.title or "").strip()
if not label:
label = self._topic_from_url(page.url_canonical or page.url)
if not label:
label = source.name
key = re.sub(r"[^a-z0-9]+", " ", label.lower()).strip()
if not key or key in seen:
continue
seen.add(key)
preview = str(page.cleaned_text or "").strip()
topics.append(
{
"topic": label[:120],
"title": (page.title or label)[:140],
"source_url": page.url_canonical or page.url,
"detail": preview[:220],
}
)
if len(topics) >= max_topics:
break
if len(topics) >= max_topics:
break
return {
"topic_candidates": topics,
"sources_count": len(bindings),
"pages_count": pages_count,
"chunks_count": chunks_count,
}
def _lexical_score(self, query_tokens: List[str], chunk_text: str) -> float:
"""Lexical relevance score: density of query tokens + n-gram boost.
Vecchia formula: `density + 0.2 * (len(chunk)/1200)` premiava i
chunk LUNGHI a parità di density. Risultato: il boilerplate del
sito ("Skip to main content REGIONE CAMPANIA...") con tutti i
token del menu vinceva contro un chunk specifico breve che
conteneva *letteralmente* la query (es. "Monastero del Deserto").
Nuova formula:
- `density` = overlap / len(query_tokens) — invariato.
- `phrase_bonus` = +1.0 se la query (>= 2 token) compare LETTERALMENTE
nel chunk: questo è il segnale più forte di rilevanza e ribalta
il vantaggio dei boilerplate. Case-insensitive.
- `length_penalty` = leggera penalità per chunk MOLTO lunghi
(oltre 2500 char): tipici dei header/menu indicizzati intero.
"""
chunk_tokens = _tokenize(chunk_text)
if not chunk_tokens:
return 0.0
token_set = set(chunk_tokens)
overlap = sum(1 for token in query_tokens if token in token_set)
if overlap <= 0:
return 0.0
density = overlap / max(len(query_tokens), 1)
# n-gram boost: phrase match LETTERALE (case-insensitive) è il
# segnale di rilevanza più forte. Lo applichiamo per query che
# rappresentano nomi propri / entità (≥ 2 token significativi).
phrase_bonus = 0.0
if len(query_tokens) >= 2:
chunk_lower = chunk_text.lower()
phrase = " ".join(query_tokens).lower()
if phrase in chunk_lower:
phrase_bonus = 1.0
else:
# Anche bigrammi: se gli ultimi 2 token consecutivi compaiono
# consecutivi nel chunk, +0.4 (es. "del Deserto" preserva
# parte della struttura della frase).
for i in range(len(query_tokens) - 1):
bigram = " ".join(query_tokens[i:i+2]).lower()
if bigram in chunk_lower:
phrase_bonus = max(phrase_bonus, 0.4)
# Penalty leggera per chunk boilerplate molto lunghi (>2500 char).
length_penalty = 0.0
if len(chunk_text) > 2500:
length_penalty = -0.1
# Boilerplate detection: chunks che sono header/footer/menù del sito
# contengono spesso TUTTI i nomi di luoghi (per la navigazione) e
# vincono falsamente il match anche su query specifiche. Pattern
# tipici di Campania Divina e siti turistici simili. La penalità è
# forte (-1.0) per spostare questi chunks ben sotto i contenuti reali.
chunk_lower_full = chunk_text.lower()
BOILERPLATE_MARKERS = (
"skip to main content",
"where to go things to do travel ideas",
"lingua corrente: en eng",
"powered by:",
"covid-19 ultimo dpcm",
"musei e parchi archeologici",
"enogast", # "Enogastronomia" tipico tag-cloud footer
"talk to the a", # "Talk to the AI Agent"
"english español français", # menu lingue multi-language
"deutsch italiano cerca search",
"cerca search home campania",
"associazione alessandro scarlatti", # tipico elenchi-archivio
"biblioteche coinvolti nel progetto",
"connette patrimoni provenienti",
)
boiler_hits = sum(1 for m in BOILERPLATE_MARKERS if m in chunk_lower_full)
boilerplate_penalty = -1.0 * boiler_hits if boiler_hits else 0.0
return float(density + phrase_bonus + length_penalty + boilerplate_penalty)
def _topic_from_url(self, url: str) -> str:
raw_url = str(url or "").strip()
if not raw_url:
return ""
try:
parsed = urlparse(raw_url)
parts = [part for part in parsed.path.split("/") if part]
except Exception:
return ""
for token in reversed(parts):
cleaned = re.sub(r"\.[a-z0-9]{2,5}$", "", token.lower())
cleaned = unquote(cleaned).replace("-", " ").replace("_", " ").strip()
if len(cleaned) >= 4:
return cleaned.title()
return parsed.hostname or ""
knowledge_memory_service = KnowledgeMemoryService()
"""Knowledge memory crawl/index/retrieval service."""
from __future__ import annotations
import hashlib
import io
import re
import threading
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import unquote, urlparse, urlunparse
from uuid import UUID
import httpx
from src.core.source_evidence import _is_safe_public_url
from src.db import KnowledgeRepository, get_db
from src.models import (
KnowledgeChunk,
KnowledgeCrawlPhase,
KnowledgeCrawlRun,
KnowledgeCrawlStatus,
KnowledgeCrawlTrigger,
KnowledgePage,
KnowledgeVersionState,
)
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger
logger = get_logger(__name__)
SCRIPT_RE = re.compile(r"(?is)<script.*?>.*?</script>")
STYLE_RE = re.compile(r"(?is)<style.*?>.*?</style>")
TAG_RE = re.compile(r"(?is)<[^>]+>")
TITLE_RE = re.compile(r"(?is)<title[^>]*>(.*?)</title>")
WS_RE = re.compile(r"\s+")
WORD_RE = re.compile(r"[a-z0-9]{3,}")
def _strip_html(raw: str) -> str:
cleaned = SCRIPT_RE.sub(" ", raw or "")
cleaned = STYLE_RE.sub(" ", cleaned)
cleaned = TAG_RE.sub(" ", cleaned)
return WS_RE.sub(" ", cleaned).strip()
def _extract_title(raw_html: str) -> str:
match = TITLE_RE.search(raw_html or "")
if not match:
return ""
value = WS_RE.sub(" ", str(match.group(1) or "")).strip()
return value[:280]
def _normalize_url(url: str) -> str:
raw = str(url or "").strip()
if not raw:
return ""
try:
parsed = urlparse(raw)
except Exception:
return ""
if parsed.scheme not in {"http", "https"}:
return ""
cleaned = parsed._replace(fragment="")
return urlunparse(cleaned).strip()
def _hash_text(value: str) -> str:
return hashlib.sha256(str(value or "").encode("utf-8")).hexdigest()
def _tokenize(value: str) -> List[str]:
return WORD_RE.findall(str(value or "").lower())
def _estimate_tokens(value: str) -> int:
return max(1, int(len(str(value or "")) / 4))
def _sparse_embedding(value: str, max_terms: int = 80) -> Dict[str, float]:
tokens = _tokenize(value)
if not tokens:
return {}
counts: Dict[str, int] = {}
for token in tokens:
counts[token] = counts.get(token, 0) + 1
ordered = sorted(counts.items(), key=lambda item: item[1], reverse=True)[:max_terms]
norm = sum(freq * freq for _, freq in ordered) ** 0.5 or 1.0
return {token: float(freq) / norm for token, freq in ordered}
def _sparse_cosine(left: Dict[str, float], right: Dict[str, float]) -> float:
if not left or not right:
return 0.0
if len(left) > len(right):
left, right = right, left
score = 0.0
for token, value in left.items():