diff --git "a/backend/knowledge_base.py" "b/backend/knowledge_base.py" new file mode 100644 --- /dev/null +++ "b/backend/knowledge_base.py" @@ -0,0 +1,2342 @@ +""" +knowledge_base.py β€” Document indexing (PDF/TXT/MD/DOCX + HuggingFace +datasets) into ChromaDB, the optional visual (image-based PDF) index via +byaldi, and retrieval helpers used by the chat tabs. +""" + +import base64 +import hashlib +import json +import re +import time +from collections import defaultdict +from difflib import SequenceMatcher +from collections import Counter +from io import BytesIO +from pathlib import Path +from typing import Optional + +from PIL import Image + +from smolagents import Tool + +from backend import model_registry as mr +from backend import models +from backend.hardware import DEVICE +from backend.paths import third_party_dir +from ui.i18n import LANGUAGES + +import os +import sys + +_visual_retriever = None +_visual_retriever_id = None + + +def _add_poppler_to_path(): + if sys.platform != "win32": + return + for poppler_dir in [third_party_dir() / "poppler", + Path.cwd() / "third_party" / "poppler", Path.cwd() / "poppler"]: + if poppler_dir.exists(): + for pdfinfo_file in poppler_dir.rglob("pdfinfo.exe"): + bin_dir = pdfinfo_file.parent + bin_str = str(bin_dir) + if bin_str not in os.environ["PATH"]: + os.environ["PATH"] = bin_str + os.pathsep + os.environ["PATH"] + print(f"[Poppler] Found local Poppler at: {bin_str}") + return + + possible_paths = [ + Path(sys.prefix) / "Library" / "bin", + Path(sys.prefix) / "bin", + Path(os.environ.get("LOCALAPPDATA", "")) / "scoop" / "apps" / "poppler" / "current" / "bin", + Path(os.environ.get("USERPROFILE", "")) / "scoop" / "apps" / "poppler" / "current" / "bin", + Path(r"C:\poppler\Library\bin"), + Path(r"C:\poppler\bin"), + Path(r"C:\Program Files\poppler\Library\bin"), + Path(r"C:\Program Files\poppler\bin"), + ] + for p in possible_paths: + if p.exists() and (p / "pdfinfo.exe").exists(): + p_str = str(p) + if p_str not in os.environ["PATH"]: + os.environ["PATH"] = p_str + os.pathsep + os.environ["PATH"] + print(f"[Poppler] Auto-detected Poppler at: {p_str}") + break + +_add_poppler_to_path() + + +def get_file_path(f) -> Optional[str]: + if f is None: return None + if isinstance(f, str): return f + if isinstance(f, dict):return f.get("path") or f.get("name") or f.get("tmp_path") + if hasattr(f, "path"): return f.path + if hasattr(f, "name"): return f.name + return None + + +def _chunk_text(text: str): + chunks, start = [], 0 + while start < len(text): + chunks.append(text[start: start + mr.CHUNK_SIZE]) + start += mr.CHUNK_SIZE - mr.CHUNK_OVERLAP + return chunks + + +def _safe_meta(meta: dict, chunk_index: int) -> dict: + safe = {k: v if isinstance(v, (str, int, float, bool)) else str(v) + for k, v in meta.items()} + safe["chunk_index"] = chunk_index + return safe + + +_DIMENSION_MISMATCH_HINT = ( + "The current embedding model doesn't match the one this knowledge " + "base was indexed with (vector dimension mismatch). Switch back to " + "the original embedding model in the πŸ“‚ Knowledge Base tab's " + "'🧩 Embedding Model' control, or clear the index (πŸ’₯ Clear ALL) and " + "re-index your documents with the new embedding model." +) + + +def get_collection_embedding_dim() -> Optional[int]: + """Best-effort: return the vector dimension the CURRENT ChromaDB + collection was actually built with, by peeking at one stored + embedding. Returns None if the collection is empty β€” nothing to + compare against yet, so any embedding model is safe to switch to. + + Used by the Knowledge Base tab's "🧩 Embedding Model" Load button to + warn the user BEFORE they switch, rather than only finding out the + hard way on the next query/index call. + """ + col = models.get_chroma_collection() + if col.count() == 0: + return None + try: + peek = col.peek(limit=1) + vecs = peek.get("embeddings") + if vecs is not None and len(vecs) > 0: + return len(vecs[0]) + except Exception: + pass + return None + + +def _tag_pairs(theme="", subtheme="") -> list[tuple[str, str]]: + """Expand the (possibly multi-select) theme/subtheme tags into a list + of SCALAR (theme, subtheme) pairs to index. + + ChromaDB's where-filters (`$eq` / `$in`) only match SCALAR metadata + values, so a file tagged with several themes/subthemes is indexed once + per selected combination β€” each copy carries ONE scalar pair and is + therefore retrievable under every tag the user picked. Empty selections + produce the single ('', '') pass (untagged indexing, as before). + + E.g. themes=[Law, Health], subthemes=[Criminal] β†’ + [(Law, Criminal), (Health, Criminal)]. + """ + themes = _as_scope_list(theme) or [""] + subs = _as_scope_list(subtheme) or [""] + return [(t, s) for t in themes for s in subs] + + +def index_texts(texts: list, metadatas: list) -> int: + invalidate_doc_table_cache() + col = models.get_chroma_collection() + all_chunks, all_metas, all_ids = [], [], [] + for text, meta in zip(texts, metadatas): + for j, chunk in enumerate(_chunk_text(text)): + # The id must be unique per (source, metadata) AND stable across + # re-indexing the same file with the same tags (so upsert + # replaces rather than duplicates). The metadata hash makes a + # multi-tagged file's copies β€” identical chunk text under + # different theme/subtheme tags β€” get DIFFERENT ids instead of + # colliding on a local counter (the second tag pass used to + # upsert over the first). + meta_key = hashlib.md5( + json.dumps(meta, sort_keys=True, ensure_ascii=False).encode("utf-8") + ).hexdigest()[:10] + uid = f"{meta.get('source','doc')}__{meta_key}__{len(all_chunks)}" + all_chunks.append(chunk) + all_metas.append(_safe_meta(meta, j)) + all_ids.append(uid) + if not all_chunks: + return 0 + for i in range(0, len(all_chunks), 64): + vecs = models.encode_texts(all_chunks[i:i+64]) + try: + col.upsert(embeddings=vecs, documents=all_chunks[i:i+64], + metadatas=all_metas[i:i+64], ids=all_ids[i:i+64]) + except Exception as e: + if "dimension" in str(e).lower(): + raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e + raise + return len(all_chunks) + + +# ────────────────────────────────────────────────────────────────── +# byaldi (visual PDF RAG) is a heavy native-binary dependency chain: +# byaldi -> colpali_engine -> transformers -> torchaudio. On machines +# with a broken or mismatched native wheel (e.g. a CUDA torchaudio build +# sitting on top of a CPU-only torch install β€” the same family of +# failure as llama-cpp-python), importing it at module level killed app +# startup with an OSError/RuntimeError. Per AGENTS.md ("the app MUST +# always launch"), byaldi is imported lazily and its failure is cached +# so visual RAG degrades to a clear message instead of a crash. +# ────────────────────────────────────────────────────────────────── +_BYALDI_AVAILABLE = None # None = untested, False = broken, class = OK +_BYALDI_IMPORT_ERROR = "" + + +def _get_byaldi(): + """Lazily import and return byaldi's RAGMultiModalModel class, or + None if it can't load on this machine (broken native/CUDA wheel). + Never raises β€” the app must always launch (AGENTS.md).""" + global _BYALDI_AVAILABLE, _BYALDI_IMPORT_ERROR + if _BYALDI_AVAILABLE is None: + try: + from byaldi import RAGMultiModalModel + _BYALDI_AVAILABLE = RAGMultiModalModel + except Exception as e: # ImportError, OSError, RuntimeError, ... + _BYALDI_AVAILABLE = False + _BYALDI_IMPORT_ERROR = str(e) + print("[Vision] byaldi unavailable β€” visual PDF RAG disabled. " + f"({type(e).__name__}: {str(e)[:200]})") + return _BYALDI_AVAILABLE if _BYALDI_AVAILABLE else None + + +_VISUAL_UNAVAILABLE_MSG = ( + "⚠️ Visual PDF indexing is unavailable on this PC β€” the visual-RAG " + "engine (byaldi/torchaudio) can't load its native libraries here " + "(typically a CUDA build installed on a machine without the matching " + "CUDA runtime, or an old GPU). Text indexing works fine. To enable it, " + "install the CPU build of torchaudio matching your torch version: " + 'pip install "torchaudio==+cpu" ' + "--index-url https://download.pytorch.org/whl/cpu" + "\n\nActual error: {detail}" +) + + +def _load_byaldi_model(retriever_id: str): + global _visual_retriever, _visual_retriever_id + if _visual_retriever is not None and _visual_retriever_id == retriever_id: + return _visual_retriever + + byaldi_cls = _get_byaldi() + if byaldi_cls is None: + raise RuntimeError(_VISUAL_UNAVAILABLE_MSG.format( + detail=_BYALDI_IMPORT_ERROR or "unknown")) + + target = retriever_id or mr.DEFAULT_VISUAL_RETRIEVER + index_path = Path(mr.VISUAL_INDEX_DIR) / "main" + try: + if index_path.exists(): + # Load the EXISTING index via from_index β€” it populates the + # embeddings / mappings / collection. from_pretrained alone + # leaves indexed_embeddings EMPTY, so search() fails with + # "No passages provided" and the visual retrieval can never see + # the indexed pages (the exact failure in the RAG logs: the + # retriever loads but returns nothing). The persisted index + # dictates its own model (index_config.model_name), so the + # requested retriever id is advisory once an index exists. + _visual_retriever = byaldi_cls.from_index(str(index_path)) + try: + cfg = _read_gzip_json(index_path / "index_config.json.gz") + _visual_retriever_id = cfg.get("model_name") or target + except Exception: + _visual_retriever_id = target + else: + _visual_retriever = byaldi_cls.from_pretrained( + target, index_root=mr.VISUAL_INDEX_DIR, verbose=0, + ) + _visual_retriever_id = target + except ValueError as e: + if "only supports ColPali and ColQwen2" in str(e): + fallback = "vidore/colqwen2-v1.0" + print(f"[Vision] '{target}' not supported by this version of Byaldi. Falling back to: {fallback}") + _visual_retriever = byaldi_cls.from_pretrained( + fallback, index_root=mr.VISUAL_INDEX_DIR, verbose=0, + ) + _visual_retriever_id = fallback + else: + raise + return _visual_retriever + + +def get_visual_retriever(): + try: + return _load_byaldi_model(_visual_retriever_id or mr.DEFAULT_VISUAL_RETRIEVER) + except Exception as e: + print(f"[Vision] Visual retriever unavailable: {e}") + return None + + +def visual_retriever_needs_load() -> bool: + """True when the visual index exists but the retriever model is NOT yet + loaded in memory β€” i.e. the next visual_retrieve() will pay the cold + 2-8 GB model load. chat.py's direct RAG path uses this to show a + 'πŸ–ΌοΈ Loading visual index…' status line ONLY when the load is actually + about to happen (warm calls stay snappy β€” no flicker).""" + return ((Path(mr.VISUAL_INDEX_DIR) / "main").exists() + and _visual_retriever is None) + + +def index_pdf_visual(filepath: str, retriever_id: str, lang_key: str = "kh", + source_name: str = "", theme: str = "", subtheme: str = "") -> str: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + try: + byaldi_cls = _get_byaldi() + if byaldi_cls is None: + return _VISUAL_UNAVAILABLE_MSG.format( + detail=_BYALDI_IMPORT_ERROR or "unknown") + + global _visual_retriever, _visual_retriever_id + index_path = Path(mr.VISUAL_INDEX_DIR) / "main" + index_path.parent.mkdir(parents=True, exist_ok=True) + + _load_byaldi_model(retriever_id) + + meta = {"source": source_name or Path(filepath).name, + "theme": _meta_tags(theme), "subtheme": _meta_tags(subtheme)} + + # _load_byaldi_model already loaded the index (when present) β€” reuse + # it for add_to_index instead of from_index again (a second call + # would re-create the whole 2-8 GB model). + if index_path.exists(): + try: + _visual_retriever.add_to_index(input_item=filepath, + store_collection_with_index=True, + doc_id=int(time.time()), + metadata=meta) + except Exception: + _visual_retriever.index(input_path=filepath, index_name="main", + store_collection_with_index=True, overwrite=True) + else: + _visual_retriever.index(input_path=filepath, index_name="main", + store_collection_with_index=True, overwrite=False, + metadata=[meta]) + return l["kb_msg_visual_updated"].format(name=source_name or Path(filepath).name) + except ImportError: + return l["kb_msg_byaldi_missing"] + except Exception as e: + err_str = str(e) + if "poppler" in err_str.lower() or "page count" in err_str.lower(): + return l["kb_msg_poppler_missing"] + return f"❌ {e}" + + +def index_image_visual(filepath: str, retriever_id: str, lang_key: str = "kh", + source_name: str = "", theme: str = "", subtheme: str = "") -> str: + """Add a STANDALONE image file to the byaldi visual index (image chunks + via ColPali β€” the same index the PDF visual pipeline uses). Only the + extensions byaldi's _process_and_add_to_index handles (jpg/jpeg/png/bmp) + are accepted; webp/gif/tiff get the text index only and report a clear + skip here. Unlike PDFs, an existing index is NEVER rebuilt from a single + image (that would wipe every other visual doc) β€” add_to_index only.""" + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + ext = Path(filepath).suffix.lower() + if ext not in (".jpg", ".jpeg", ".png", ".bmp"): + return l["kb_msg_image_visual_skipped"].format(ext=ext or "?") + try: + byaldi_cls = _get_byaldi() + if byaldi_cls is None: + return _VISUAL_UNAVAILABLE_MSG.format( + detail=_BYALDI_IMPORT_ERROR or "unknown") + + global _visual_retriever, _visual_retriever_id + index_path = Path(mr.VISUAL_INDEX_DIR) / "main" + index_path.parent.mkdir(parents=True, exist_ok=True) + + _load_byaldi_model(retriever_id) + + meta = {"source": source_name or Path(filepath).name, + "theme": _meta_tags(theme), "subtheme": _meta_tags(subtheme)} + + # Reuse the index loaded by _load_byaldi_model (never from_index + # again β€” that would re-create the whole 2-8 GB model). + if index_path.exists(): + _visual_retriever.add_to_index(input_item=filepath, + store_collection_with_index=True, + doc_id=int(time.time()), + metadata=meta) + else: + _visual_retriever.index(input_path=filepath, index_name="main", + store_collection_with_index=True, overwrite=False, + metadata=[meta]) + return l["kb_msg_visual_updated"].format(name=source_name or Path(filepath).name) + except ImportError: + return l["kb_msg_byaldi_missing"] + except Exception as e: + return f"❌ {e}" + + +def _visual_search_results(query: str, top_k: int = 3) -> list: + """Raw byaldi search results for `query` against the visual index, or + [] when there is no index / the retriever can't load / search fails. + Shared by visual_retrieve() (page images for the RAG grounding pass) + and VisualRetrieverTool (page images + per-page source metadata for the + agentic RAG path) so both go through ONE search implementation. The + cheap directory check runs first β€” the ~2-8 GB retriever model is only + loaded when an index actually exists.""" + # Nothing has been indexed into the visual (image-based PDF) index yet β€” + # skip entirely instead of loading the ~2-8 GB retriever model just to + # search an empty index. This is the normal state until the user + # indexes at least one PDF / image from the Knowledge Base tab. + if not (Path(mr.VISUAL_INDEX_DIR) / "main").exists(): + return [] + retriever = get_visual_retriever() + if retriever is None: + return [] + try: + return retriever.search(query, k=top_k) + except Exception as e: + print(f"[VIS] {e}") + return [] + + +def visual_retrieve(query: str, top_k: int = 3) -> list: + """Page images (PIL, RGB) from the visual index most relevant to + `query`, or [] when the index is empty / unavailable. The 2-8 GB + retriever model is only loaded when an index actually exists.""" + images = [] + for r in _visual_search_results(query, top_k): + if hasattr(r, "base64") and r.base64: + images.append(Image.open(BytesIO(base64.b64decode(r.base64))).convert("RGB")) + return images + + +# ────────────────────────────────────────────────────────────────────── +# Visual-tool hits cache β€” the page images a VisualRetrieverTool call +# retrieved during an AGENTIC RAG run. The tool returns only a TEXT report +# to the model (a text-only LLM can't see images), but the multimodal +# grounding pass in chat.py needs the ACTUAL images; the tool stashes them +# here so the grounding pass reuses them instead of loading the 2-8 GB +# retriever model a second time to re-retrieve by query. Reset before each +# run (rag_agent.reset_retriever_stats), consumed + cleared after. +# ────────────────────────────────────────────────────────────────────── +_visual_tool_hits: list = [] + + +def reset_visual_tool_hits() -> None: + """Clear the cached page images from a previous run (called right + before agent.run(), mirroring reset_retriever_stats).""" + global _visual_tool_hits + _visual_tool_hits = [] + + +def consume_visual_tool_hits() -> list: + """Return and clear the page images the agent's visual_retriever tool + retrieved this run β€” the grounding pass feeds them (with the retrieved + text context) to the same-model VLM. [] when the tool never ran or + found nothing.""" + global _visual_tool_hits + hits = _visual_tool_hits + _visual_tool_hits = [] + return hits + + +def unload_visual_retriever_fn(lang_key: str = "kh") -> str: + global _visual_retriever, _visual_retriever_id + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + if _visual_retriever is None: + return l["btn_unload_none"] + mid = _visual_retriever_id or mr.DEFAULT_VISUAL_RETRIEVER + obj = _visual_retriever + _visual_retriever = None + _visual_retriever_id = None + models._release_model(obj) + return l["msg_unloaded"].format(model=mid) + + +# ────────────────────────────────────────────────────────────────────── +# Visual index table / delete / clear β€” pure file surgery on byaldi's +# persisted files. byaldi 0.0.7 has NO per-doc delete API (remove_from_index +# is NotImplementedError), so rows are removed by rewriting the persisted +# index directly: embeddings chunks (flat list β†’ position = embed_id), +# embed_id_to_doc_id mapping, doc_ids_to_file_names, collection chunks, +# metadata and index_config. Embed ids are renumbered sequentially (search +# indexes indexed_embeddings positionally and maps back through +# embed_id_to_doc_id, so gaps would break it). The 2-8 GB retriever model +# is NEVER loaded for listing/deleting. +# ────────────────────────────────────────────────────────────────────── + + +def _meta_tags(value) -> str: + """Join multi-select theme/subtheme tags into the single metadata + string stored on visual docs (", ".join, sorted β€” the same display as + the docs table). Empty selection β†’ "".""" + vals = _as_scope_list(value) + return ", ".join(sorted(v for v in vals if v)) + + +def _visual_index_dir() -> Path: + return Path(mr.VISUAL_INDEX_DIR) / "main" + + +def _read_gzip_json(p: Path): + import gzip + with gzip.open(p, "rt", encoding="utf-8") as fh: + return json.load(fh) + + +def _write_gzip_json(p: Path, data): + import gzip + with gzip.open(p, "wt", encoding="utf-8") as fh: + json.dump(data, fh, ensure_ascii=False) + + +def _visual_display_name(doc_id, file_names, metadata) -> str: + """Display name for a visual doc: prefer the original filename stored in + byaldi metadata (added on ingest), else the basename of the stored path + (older indexes record the upload temp path).""" + meta = metadata.get(str(doc_id)) or metadata.get(doc_id) or {} + src = meta.get("source") or file_names.get(str(doc_id)) or file_names.get(doc_id) or "" + if src and src != "In-memory Image": + return Path(str(src)).name + return src or f"doc-{doc_id}" + + +def _visual_sources_set() -> set: + """The set of source filenames that have page images in the visual + index, read straight from the persisted metadata gz β€” NO retriever + model load (the same cheap file read `_visual_doc_id_for_source` + uses, but for all sources at once). Empty set when no visual index + exists. Used by the RAG summary tools to signal "this document also + has page images β€” delegate to `knowledge_searcher` for a visual + pass" (the scanned-PDF case: text chunks are OCR garbage but the + page images carry the real content).""" + index_path = _visual_index_dir() + if not index_path.exists(): + return set() + try: + metadata = _read_gzip_json(index_path / "metadata.json.gz") + except FileNotFoundError: + return set() + except Exception: + return set() + out = set() + for meta in metadata.values(): + src = str((meta or {}).get("source", "") or "") + if src and src != "In-memory Image": + out.add(src) + return out + + +def _looks_like_ocr_garbage(text: str) -> bool: + """True when extracted TEXT looks like failed OCR β€” the telltale + `(cid:N)` glyph-id fragments, `cid:N` markers, or U+FFFD replacement + chars that scanned-PDF text extraction leaves behind when the font + has no Unicode mapping. The RAG searcher / manager use this signal to + route image-heavy scanned documents to `visual_retriever` instead of + concluding the knowledge base "has nothing" or summarizing garbage. + """ + sample = str(text or "")[:20000] + if re.search(r"\(cid:\s*\d+\)", sample, re.IGNORECASE): + return True + if re.search(r"\bcid\s*\d+\b", sample, re.IGNORECASE): + return True + return "\ufffd" in sample + + +def _visual_doc_id_for_source(source: str): + """The visual-index doc id whose ingest metadata carries `source` (the + original filename), or None β€” used to link a docs-table image row to its + visual page thumbnail. Reads the persisted metadata gz, no model load.""" + index_path = _visual_index_dir() + if not index_path.exists() or not source: + return None + try: + metadata = _read_gzip_json(index_path / "metadata.json.gz") + except FileNotFoundError: + metadata = {} + except Exception: + return None + for doc_id, meta in metadata.items(): + if str(meta.get("source", "")) == source: + return str(doc_id) + return None + + +def get_visual_index_table() -> list: + """List every visual document WITHOUT loading the retriever model: + rows of [source file, doc id, pages/images, theme, subtheme] read + straight from the index's persisted gz mappings (theme/subtheme come + from the byaldi metadata stored on ingest; older rows show ""). + Empty when no visual index exists.""" + index_path = _visual_index_dir() + if not index_path.exists(): + return [] + try: + file_names = _read_gzip_json(index_path / "doc_ids_to_file_names.json.gz") + embed_map = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz") + try: + metadata = _read_gzip_json(index_path / "metadata.json.gz") + except FileNotFoundError: + metadata = {} + counts = {} + for entry in embed_map.values(): + try: + doc_id = int(entry.get("doc_id")) + except (TypeError, ValueError): + continue + counts[doc_id] = counts.get(doc_id, 0) + 1 + rows = [] + for doc_id in sorted(counts): + meta = metadata.get(str(doc_id)) or metadata.get(doc_id) or {} + rows.append([_visual_display_name(doc_id, file_names, metadata), + str(doc_id), str(counts[doc_id]), + str(meta.get("theme", "") or ""), + str(meta.get("subtheme", "") or "")]) + return rows + except Exception as e: + print(f"[Vision] visual index table read failed: {e}") + return [] + + +def get_visual_thumb_bytes(doc_id: int, page_id: int = 1): + """The stored PNG bytes for a visual document's page, read straight + from the persisted collection (base64 per embed id) β€” NO retriever + model load, so thumbnails render instantly in the KB tab. Returns None + when the visual index / collection is missing, the (doc, page) doesn't + exist, or the read fails.""" + index_path = _visual_index_dir() + coll_dir = index_path / "collection" + if not index_path.exists() or not coll_dir.exists(): + return None + try: + embed_map = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz") + target = None + for eid, entry in embed_map.items(): + try: + if (int(entry.get("doc_id", -1)) == int(doc_id) + and int(entry.get("page_id", -1)) == int(page_id)): + target = int(eid) + break + except (TypeError, ValueError): + continue + if target is None: + return None + for f in sorted(coll_dir.glob("*.json.gz"), + key=lambda x: int(x.stem.split(".")[0])): + chunk = _read_gzip_json(f) + b64 = chunk.get(str(target)) + if b64: + return base64.b64decode(b64) + return None + except Exception as e: + print(f"[Vision] visual thumb read failed: {e}") + return None + + +def _load_visual_embedding_files(index_path: Path) -> list: + """Flatten the persisted embeddings_*.pt chunks into one list whose + position is the embed id (byaldi's on-disk layout).""" + import torch + embeddings_path = index_path / "embeddings" + files = sorted(embeddings_path.glob("embeddings_*.pt"), + key=lambda x: int(x.stem.split("_")[1])) + out = [] + for f in files: + try: + out.extend(torch.load(f)) + except Exception: + out.extend(torch.load(f, weights_only=False)) + return out + + +def _drop_rows(seq, drop_positions): + return [x for i, x in enumerate(seq) if i not in drop_positions] + + +def delete_visual_docs(selected_rows: list, rows: list = None, lang_key: str = "kh") -> tuple: + """Delete selected visual documents by doc id. `selected_rows` are row + indexes into the visual table (row[1] = doc id). Rewrites the persisted + byaldi files so search keeps working without a rebuild; when the last + doc goes, the whole index dir is removed. Returns (new table, message).""" + global _visual_retriever, _visual_retriever_id + import shutil + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + index_path = _visual_index_dir() + table = get_visual_index_table() + if not index_path.exists(): + return table, l["err_nothing_deleted"] + + rows_to_use = rows if (rows and len(rows) > 0) else table + doc_ids, names = [], [] + for idx in selected_rows or []: + if 0 <= idx < len(rows_to_use): + try: + doc_ids.append(int(rows_to_use[idx][1])) + names.append(str(rows_to_use[idx][0])) + except (TypeError, ValueError): + continue + if not doc_ids: + return table, l["err_nothing_deleted"] + deleted = set(doc_ids) + + try: + embed_map_raw = _read_gzip_json(index_path / "embed_id_to_doc_id.json.gz") + file_names_raw = _read_gzip_json(index_path / "doc_ids_to_file_names.json.gz") + config = _read_gzip_json(index_path / "index_config.json.gz") + try: + metadata = _read_gzip_json(index_path / "metadata.json.gz") + except FileNotFoundError: + metadata = {} + + # embed id -> entry, keeping only non-deleted docs (order preserved) + kept = [(int(eid), entry) for eid, entry in embed_map_raw.items() + if int(entry.get("doc_id", -1)) not in deleted] + + if not kept: + # nothing left β€” wipe the whole visual index + shutil.rmtree(index_path, ignore_errors=True) + _visual_retriever = None + _visual_retriever_id = None + joined = ", ".join(names) or l["err_nothing_deleted"] + return [], l["kb_visual_deleted"].format(n=len(deleted), names=joined) + + drop_positions = {int(eid) for eid, entry in embed_map_raw.items() + if int(entry.get("doc_id", -1)) in deleted} + + # 1. embeddings β€” drop rows, keep relative order, re-chunk by 500 + embeddings = _drop_rows(_load_visual_embedding_files(index_path), drop_positions) + emb_dir = index_path / "embeddings" + for f in emb_dir.glob("embeddings_*.pt"): + f.unlink(missing_ok=True) + import torch + for i in range(0, len(embeddings), 500): + torch.save(embeddings[i:i + 500], emb_dir / f"embeddings_{i}.pt") + + # 2. embed_id_to_doc_id β€” renumber sequentially + new_embed_map = {str(i): entry for i, (_, entry) in enumerate(kept)} + _write_gzip_json(index_path / "embed_id_to_doc_id.json.gz", new_embed_map) + + # 3. doc_ids_to_file_names / metadata β€” drop deleted docs + new_file_names = {k: v for k, v in file_names_raw.items() + if int(k) not in deleted} + _write_gzip_json(index_path / "doc_ids_to_file_names.json.gz", new_file_names) + new_metadata = {k: v for k, v in metadata.items() if int(k) not in deleted} + _write_gzip_json(index_path / "metadata.json.gz", new_metadata) + + # 4. collection chunks (only when full_document_collection) β€” drop + + # renumber, re-chunk by 500 + if config.get("full_document_collection"): + coll_dir = index_path / "collection" + collection = {} + for f in sorted(coll_dir.glob("*.json.gz"), + key=lambda x: int(x.stem.split(".")[0])): + collection.update(_read_gzip_json(f)) + collection = {str(i): v for i, (old, v) in enumerate( + (k, v) for k, v in collection.items() if int(k) not in drop_positions)} + for f in coll_dir.glob("*.json.gz"): + f.unlink(missing_ok=True) + for i in range(0, len(collection), 500): + chunk = dict(list(collection.items())[i:i + 500]) + _write_gzip_json(coll_dir / f"{i}.json.gz", chunk) + + # 5. index_config β€” keep everything, refresh highest_doc_id + config["highest_doc_id"] = max( + (int(e.get("doc_id", -1)) for e in new_embed_map.values()), default=-1) + _write_gzip_json(index_path / "index_config.json.gz", config) + + # 6. any in-memory retriever is stale now β€” reload from disk next time + _visual_retriever = None + _visual_retriever_id = None + + joined = ", ".join(names) + return get_visual_index_table(), l["kb_visual_deleted"].format(n=len(deleted), names=joined) + except Exception as e: + return table, f"❌ {e}" + + +def clear_visual_index(lang_key: str = "kh") -> tuple: + """Delete the ENTIRE visual index (all visual docs). Returns the empty + table and a bilingual message β€” never raises.""" + import shutil + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + global _visual_retriever, _visual_retriever_id + _visual_retriever = None + _visual_retriever_id = None + if Path(mr.VISUAL_INDEX_DIR).exists(): + shutil.rmtree(mr.VISUAL_INDEX_DIR, ignore_errors=True) + return [], l["kb_visual_cleared"] + + +def _delete_source_chunks(source: str): + """Drop every previously-indexed chunk for a source before re-indexing + it, so re-tagging a file REPLACES its old index instead of stacking new + tag copies on top of the old ones (the pre-multi-tag behavior).""" + if not source: + return + try: + col = models.get_chroma_collection() + col.delete(where={"source": {"$eq": source}}) + except Exception: + pass + + +def index_pdf_file(filepath: str, visual_retriever_id: str = mr.DEFAULT_VISUAL_RETRIEVER, + theme: str = "", subtheme: str = "", lang_key: str = "kh", + source_name: str = "") -> str: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + display = source_name or Path(filepath).name + msgs = [] + _delete_source_chunks(display) + try: + import pdfplumber # MIT β€” replaced PyMuPDF (AGPL) for Store distribution + texts = [] + with pdfplumber.open(filepath) as pdf: + for n, page in enumerate(pdf.pages): + t = page.extract_text() or "" + if t.strip(): + texts.append((t, n + 1)) + total = 0 + for tag_theme, tag_sub in _tag_pairs(theme, subtheme): + metas = [{"source": display, "page": n, "type": "pdf", + "theme": tag_theme, "subtheme": tag_sub} + for _, n in texts] + total += index_texts([t for t, _ in texts], metas) + msgs.append(l["kb_msg_text_chunks"].format(n=total)) + except Exception as e: + msgs.append(l["kb_msg_text_failed"].format(err=e)) + msgs.append(f"πŸ–ΌοΈ {index_pdf_visual(filepath, visual_retriever_id, lang_key=lang_key, source_name=display, theme=theme, subtheme=subtheme)}") + return "\n".join(msgs) + + +def index_txt_file(filepath: str, theme: str = "", subtheme: str = "", lang_key: str = "kh", + source_name: str = "") -> str: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + display = source_name or Path(filepath).name + _delete_source_chunks(display) + try: + text = Path(filepath).read_text(encoding="utf-8", errors="replace") + k = 0 + for tag_theme, tag_sub in _tag_pairs(theme, subtheme): + k += index_texts([text], [{"source": display, "type": "txt", + "theme": tag_theme, "subtheme": tag_sub}]) + return l["kb_msg_chunks_from"].format(k=k, name=display) + except Exception as e: + return f"❌ {e}" + + +def index_docx_file(filepath: str, theme: str = "", subtheme: str = "", lang_key: str = "kh", + source_name: str = "") -> str: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + display = source_name or Path(filepath).name + _delete_source_chunks(display) + try: + import docx # python-docx + document = docx.Document(filepath) + + parts = [] + for para in document.paragraphs: + if para.text.strip(): + parts.append(para.text) + + for table in document.tables: + for row in table.rows: + cells = [c.text.strip() for c in row.cells if c.text.strip()] + if cells: + parts.append(" | ".join(cells)) + + text = "\n".join(parts) + if not text.strip(): + return l["kb_msg_no_text"].format(name=display) + + k = 0 + for tag_theme, tag_sub in _tag_pairs(theme, subtheme): + k += index_texts([text], [{"source": display, "type": "docx", + "theme": tag_theme, "subtheme": tag_sub}]) + return l["kb_msg_chunks_from"].format(k=k, name=display) + except ImportError: + return l["kb_msg_docx_missing"] + except Exception as e: + return f"❌ {e}" + + +def index_image_file(filepath: str, visual_retriever_id: str = mr.DEFAULT_VISUAL_RETRIEVER, + theme: str = "", subtheme: str = "", lang_key: str = "kh", + source_name: str = "") -> str: + """Index a STANDALONE image file. Two parts, mirroring how PDFs are + handled: + + 1. A small text chunk ("πŸ–ΌοΈ Image: (WΓ—Hpx)") into ChromaDB so the + image appears in the Knowledge Base docs table as an ingested file + (type "image"), carries its theme/subtheme tags (multi-select, one + copy per tag combination like every other file type), is deletable, + and is discoverable by filename in RAG. + 2. The image itself into the byaldi VISUAL index (ColPali image chunks) + when the visual engine is available β€” the content-level retrieval + path. jpg/jpeg/png/bmp are supported; other image formats degrade to + the text index only with a clear note.""" + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + display = source_name or Path(filepath).name + _delete_source_chunks(display) + msgs = [] + # Filename/dimension stub so the image shows in the KB docs table and + # joins the theme/subtheme filters (no OCR/VLM caption is available). + dims = "" + try: + with Image.open(filepath) as im: + dims = f" ({im.width}Γ—{im.height}px)" + except Exception: + pass + text = f"πŸ–ΌοΈ Image: {display}{dims}" + k = 0 + for tag_theme, tag_sub in _tag_pairs(theme, subtheme): + k += index_texts([text], [{"source": display, "type": "image", + "theme": tag_theme, "subtheme": tag_sub}]) + msgs.append(l["kb_msg_image_chunks"].format(k=k, name=display)) + msgs.append(f"πŸ–ΌοΈ {index_image_visual(filepath, visual_retriever_id, lang_key=lang_key, source_name=display, theme=theme, subtheme=subtheme)}") + return "\n".join(msgs) + + +def index_uploaded_files(files, visual_retriever_label: str, + theme: str = "", subtheme: str = "", lang_key: str = "kh", + source_names: dict = None) -> str: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + if not files: + return l["err_no_files"] + retriever_id = mr.VISUAL_RETRIEVER_OPTIONS.get(visual_retriever_label, mr.DEFAULT_VISUAL_RETRIEVER) + if not isinstance(files, list): + files = [files] + flat = [] + for item in files: + flat.extend(item) if isinstance(item, list) else flat.append(item) + msgs = [] + for f in flat: + path = get_file_path(f) + if not path: + msgs.append(l["err_upload"] + repr(f)) + continue + # The uploaded temp file carries a - prefix β€” index under + # the user's ORIGINAL file name (source_names maps path β†’ real name). + original = (source_names or {}).get(path) or "" + ext = Path(path).suffix.lower() + if ext == ".pdf": + msgs.append(index_pdf_file(path, retriever_id, theme, subtheme, lang_key=lang_key, + source_name=original)) + elif ext in (".txt", ".md"): + msgs.append(index_txt_file(path, theme, subtheme, lang_key=lang_key, source_name=original)) + elif ext == ".docx": + msgs.append(index_docx_file(path, theme, subtheme, lang_key=lang_key, source_name=original)) + elif ext in (".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".tiff", ".tif"): + msgs.append(index_image_file(path, retriever_id, theme, subtheme, lang_key=lang_key, + source_name=original)) + else: + msgs.append(l["err_unsupported"] + ext) + return "\n".join(msgs) or l["err_nothing_indexed"] + + +def index_hf_dataset(dataset_name: str, text_col: str, source_col: str = "", + theme: str = "", subtheme: str = ""): + try: + import datasets as ds + dataset = ds.load_dataset(dataset_name, split="train") + texts, metas = [], [] + for row in dataset: + t = row.get(text_col, "") + if not t: + continue + src = row.get(source_col, dataset_name) if source_col else dataset_name + texts.append(str(t)) + metas.append({"source": str(src), "type": "hf_dataset", + "theme": theme, "subtheme": subtheme}) + k = index_texts(texts, metas) + return f"βœ… {k} chunks from '{dataset_name}'", get_doc_table() + except Exception as e: + return f"❌ {e}", get_doc_table() + + +_DOC_TABLE_CACHE = None +_DOC_TABLE_CACHE_COUNT = -1 + + +def invalidate_doc_table_cache(): + global _DOC_TABLE_CACHE, _DOC_TABLE_CACHE_COUNT + _DOC_TABLE_CACHE = None + _DOC_TABLE_CACHE_COUNT = -1 + + +def get_doc_table(force_refresh: bool = False) -> list: + global _DOC_TABLE_CACHE, _DOC_TABLE_CACHE_COUNT + try: + col = models.get_chroma_collection() + count = col.count() + except Exception: + return [] + + if count == 0: + _DOC_TABLE_CACHE = [] + _DOC_TABLE_CACHE_COUNT = 0 + return [] + + if not force_refresh and _DOC_TABLE_CACHE is not None and _DOC_TABLE_CACHE_COUNT == count: + return _DOC_TABLE_CACHE + + result = col.get(include=["metadatas"]) + # A multi-tagged file stores one COPY of each chunk per tag combination + # (scalar metadata is required for Chroma's where-filters), so the + # per-source aggregation must dedupe those copies: chunks are counted by + # their (page, chunk_index) position β€” identical across copies β€” and the + # theme/subtheme columns join the file's unique tag values. + agg = defaultdict(lambda: {"type": "", "pages": set(), "chunks": set(), + "themes": set(), "subthemes": set()}) + for m in result["metadatas"]: + src = m.get("source", "unknown") + agg[src]["type"] = m.get("type", "unknown") + agg[src]["chunks"].add((m.get("page") or 0, m.get("chunk_index") or 0)) + agg[src]["pages"].add(m.get("page")) if m.get("page") else None + if m.get("theme"): + agg[src]["themes"].add(str(m["theme"]).strip()) + if m.get("subtheme"): + agg[src]["subthemes"].add(str(m["subtheme"]).strip()) + + def _join(vals): + return ", ".join(sorted(v for v in vals if v)) if vals else "" + + table = [] + for src, info in sorted(agg.items()): + # Image rows can carry a thumbnail from the visual index (byaldi + # metadata links the original filename to its doc id) β€” the docs + # table's 7th column; empty for text rows or images without a + # visual entry (e.g. indexed when byaldi was unavailable). + thumb = "" + if info["type"] == "image": + did = _visual_doc_id_for_source(src) + if did is not None: + thumb = did + table.append([src, info["type"], + str(len(info["pages"])) if info["pages"] else "β€”", + len(info["chunks"]), + _join(info["themes"]), + _join(info["subthemes"]), + thumb]) + + _DOC_TABLE_CACHE = table + _DOC_TABLE_CACHE_COUNT = count + return table + + +def delete_selected_sources(selected_rows: list, doc_table_data: list, + lang_key: str = "kh") -> tuple: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + invalidate_doc_table_cache() + if not selected_rows: + return get_doc_table(force_refresh=True), l["err_no_rows"] + + current_table = get_doc_table(force_refresh=True) + rows_to_use = doc_table_data if (doc_table_data and len(doc_table_data) > 0) else current_table + + col, deleted = models.get_chroma_collection(), [] + for row_idx in selected_rows: + if row_idx >= len(rows_to_use): + continue + src = rows_to_use[row_idx][0] + result = col.get(where={"source": src}, include=["metadatas"]) + if result["ids"]: + col.delete(ids=result["ids"]) + deleted.append(f"'{src}' ({len(result['ids'])} chunks)") + + invalidate_doc_table_cache() + msg = (l["err_deleted"] + ", ".join(deleted)) if deleted else l["err_nothing_deleted"] + return get_doc_table(force_refresh=True), msg + + +def clear_index(lang_key: str = "kh") -> tuple: + l = LANGUAGES.get(lang_key, LANGUAGES["kh"]) + import shutil + global _visual_retriever, _visual_retriever_id + invalidate_doc_table_cache() + + # 1. Close the ChromaDB PersistentClient FIRST so it releases its + # SQLite file locks β€” on Windows, shutil.rmtree silently fails to + # delete locked files and the old chunks reappear on the next + # get_or_create_collection() call. + models.reset_chroma_collection() + + # 2. Nuke the ENTIRE chroma_db directory β€” this is the only + # reliable way to guarantee all chunks are gone. + chroma_path = Path(mr.CHROMA_PERSIST_DIR) + if chroma_path.exists(): + try: + shutil.rmtree(str(chroma_path)) + except Exception: + pass + + # Recreate a fresh (empty) collection so the app doesn't crash + # on the next retrieval attempt. + models.get_chroma_collection() + + # 3. Delete visual index and unload the retriever model + _visual_retriever = None + _visual_retriever_id = None + if Path(mr.VISUAL_INDEX_DIR).exists(): + try: + shutil.rmtree(mr.VISUAL_INDEX_DIR) + except Exception: + pass + + return [], l["err_clear_msg"] + + +def get_index_stats(lang_key: str = "en") -> tuple[str, str]: + l = LANGUAGES[lang_key] + n = models.get_chroma_collection().count() + vis_str = l["err_visual_ready"] if (Path(mr.VISUAL_INDEX_DIR) / "main").exists() else l["err_empty_visual"] + msg = l["err_status_bar"].format(n=n, vis=vis_str, dev=DEVICE.upper()) + return msg, msg + + +def _as_scope_list(value) -> list[str]: + """Normalize a metadata scope value into a list of non-empty strings. + A single string becomes a one-element list; None / "" / [] mean "no + filter". Lists are kept as-is (stripped, empties dropped) β€” the RAG + tab's multi-select Theme/Subtheme/File filters send arrays.""" + if value is None: + return [] + if isinstance(value, str): + return [value.strip()] if value.strip() else [] + return [str(v).strip() for v in value if v is not None and str(v).strip()] + + +def retrieve_context(query: str, theme="", subtheme: str = "", sources=None) -> tuple[str, list[str]]: + """Semantic retrieval over the indexed knowledge base, optionally scoped + to a set of themes / subthemes / source filenames. + + `theme` / `subtheme` accept EITHER a single value (backward-compatible + string) OR a list of values β€” the RAG tab's multi-select filters β€” and + build Chroma `$in` filters so chunks matching ANY selected value are + returned. `sources` is a list of source filenames (the RAG tab's file + picker); empty/None means no filter on that dimension.""" + col = models.get_chroma_collection() + if col.count() == 0: + return "", [] + clauses = [] + themes = _as_scope_list(theme) + if themes: + clauses.append({"theme": {"$in": themes}}) + subthemes = _as_scope_list(subtheme) + if subthemes: + clauses.append({"subtheme": {"$in": subthemes}}) + srcs = _as_scope_list(sources) + if srcs: + clauses.append({"source": {"$in": srcs}}) + where_filter = {} + if len(clauses) == 1: + where_filter = clauses[0] + elif len(clauses) > 1: + where_filter = {"$and": clauses} + try: + results = col.query(query_embeddings=models.encode_texts([query]), + n_results=min(mr.TOP_K, col.count()), + where=where_filter or None) + except Exception as e: + if "dimension" in str(e).lower(): + raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e + raise + docs = results["documents"][0] + metas = results["metadatas"][0] + if not docs: + return "", [] + # A file indexed under several theme/subtheme tags has one copy of each + # chunk per tag combination (Chroma's filters only match scalar + # metadata); dedupe by chunk TEXT so a multi-tag retrieval (e.g. theme + # $in [A, B]) never shows the same chunk twice. + seen, uniq_docs, uniq_metas = set(), [], [] + for d, m in zip(docs, metas): + if d in seen: + continue + seen.add(d) + uniq_docs.append(d) + uniq_metas.append(m) + context = "\n\n".join(f"[{m.get('source','?')}]\n{d}" + for d, m in zip(uniq_docs, uniq_metas)) + sources = list({m.get("source", "?") for m in uniq_metas}) + return context, sources + + +_SUMMARY_STOPWORDS = { + "the", "and", "for", "with", "that", "this", "from", "are", "was", "were", + "have", "has", "had", "not", "but", "you", "your", "our", "their", "they", + "them", "his", "her", "its", "can", "may", "will", "shall", "should", + "would", "could", "about", "into", "over", "under", "than", "then", "when", + "what", "which", "who", "whom", "why", "how", "all", "any", "each", "more", + "most", "some", "such", "also", "there", "here", "been", "being", "because", + "very", "much", "many", "less", "few", "just", "only", "off", "out", "up", + "down", "in", "on", "at", "by", "to", "of", "as", "is", "it", "a", "an", +} + + +def _build_scope_filter(theme: str = "", subtheme: str = "", source: str = "") -> dict: + clauses = [] + if theme: + clauses.append({"theme": {"$eq": theme}}) + if subtheme: + clauses.append({"subtheme": {"$eq": subtheme}}) + if source: + clauses.append({"source": {"$eq": source}}) + if not clauses: + return {} + if len(clauses) == 1: + return clauses[0] + return {"$and": clauses} + + +def _safe_int(value, default: int = 0) -> int: + try: + return int(value) + except Exception: + return default + + +def _scope_value_key(value) -> str: + """Normalize a metadata value for case-insensitive comparison.""" + return re.sub(r"\s+", " ", str(value or "")).strip().casefold() + + +def _best_matching_scope_value(want, candidates) -> Optional[str]: + """Return the closest STORED metadata value to `want` (the value a small + agent paraphrased), or None when nothing is close enough. + + Ladder: case-insensitive exact -> containment (either direction) -> + token overlap / prefix (stem-ish) -> difflib ratio. Only ever returns an + exact stored value, so a retry with the result stays an exact `$eq` + filter β€” never a loose scan that could dump unrelated documents.""" + want_text = str(want or "").strip() + if not want_text: + return None + cands = sorted({str(c).strip() for c in candidates if str(c).strip()}) + if not cands: + return None + want_norm = _scope_value_key(want_text) + + for c in cands: + if _scope_value_key(c) == want_norm: + return c + + for c in cands: + cn = _scope_value_key(c) + if cn and len(want_norm) >= 4 and (want_norm in cn or cn in want_norm): + return c + + want_tokens = set(_tokenize(want_text)) + best, best_score = None, 0.0 + for c in cands: + cn = _scope_value_key(c) + c_tokens = set(_tokenize(c)) or {cn} + score = 0.0 + for wt in want_tokens: + if wt in c_tokens: + score += 2.0 + elif len(wt) > 3 and any(ct.startswith(wt) or wt.startswith(ct) for ct in c_tokens): + score += 1.0 + score = score / max(len(c_tokens), 1) + if score > best_score: + best, best_score = c, score + if best is not None and best_score >= 0.5: + return best + + best, best_ratio = None, 0.0 + for c in cands: + ratio = SequenceMatcher(None, want_norm, _scope_value_key(c)).ratio() + if ratio > best_ratio: + best, best_ratio = c, ratio + return best if best_ratio >= 0.6 else None + + +def _fetch_scope_records(col, theme: str = "", subtheme: str = "", source: str = "") -> list[dict]: + """Run the exact metadata scope filter against the collection and build + the record list. May raise the dimension-mismatch RuntimeError.""" + where_filter = _build_scope_filter(theme, subtheme, source) + try: + result = col.get(where=where_filter or None, include=["documents", "metadatas"]) + except Exception as e: + if "dimension" in str(e).lower(): + raise RuntimeError(f"{_DIMENSION_MISMATCH_HINT}\n\nOriginal error: {e}") from e + raise + + records = [] + docs = result.get("documents", []) or [] + metas = result.get("metadatas", []) or [] + seen = set() + for doc, meta in zip(docs, metas): + if not doc: + continue + # Dedupe multi-tag copies (same chunk stored once per tag pair): + # identical (source, page, chunk_index) position = the same chunk. + key = (meta.get("source", "unknown"), + _safe_int(meta.get("page", 0)), + _safe_int(meta.get("chunk_index", 0))) + if key in seen: + continue + seen.add(key) + records.append({ + "source": meta.get("source", "unknown"), + "theme": meta.get("theme", ""), + "subtheme": meta.get("subtheme", ""), + "type": meta.get("type", ""), + "page": _safe_int(meta.get("page", 0)), + "chunk_index": _safe_int(meta.get("chunk_index", 0)), + "text": str(doc).strip(), + }) + + records.sort(key=lambda r: (r["source"], r["page"], r["chunk_index"])) + return records + + +def _collect_scope_records(theme: str = "", subtheme: str = "", source: str = "", + sources_scope: Optional[list] = None) -> list[dict]: + col = models.get_chroma_collection() + if col.count() == 0: + return [] + + records = _fetch_scope_records(col, theme, subtheme, source) + if not records: + # Exact scope matched nothing. The requesting agent (often a small GGUF + # model) frequently paraphrases a stored theme/subtheme name, and the + # metadata filter is an exact `$eq` β€” so nudge the requested values + # toward the canonical stored values and retry. Each retry is STILL an + # exact filter against a resolved stored value; if nothing resolves, + # return the honest empty list rather than dumping the whole knowledge + # base. + metas = (col.get(include=["metadatas"]).get("metadatas", []) or []) if col.count() else [] + themes = {str(m.get("theme", "")).strip() for m in metas if m.get("theme")} + subthemes = {str(m.get("subtheme", "")).strip() for m in metas if m.get("subtheme")} + sources = {str(m.get("source", "")).strip() for m in metas if m.get("source")} + r_theme = (_best_matching_scope_value(theme, themes) or "") if theme else "" + r_sub = (_best_matching_scope_value(subtheme, subthemes) or "") if subtheme else "" + r_src = (_best_matching_scope_value(source, sources) or "") if source else "" + + for t, s, src in ( + (r_theme, r_sub, r_src), + (r_theme, "", r_src), + ("", r_sub, r_src), + (r_theme, "", ""), + ("", r_sub, ""), + ("", "", r_src), + ): + if not (t or s or src): + continue + recs = _fetch_scope_records(col, t, s, src) + if recs: + records = recs + break + + # The RAG tab's multi-select FILE filter (`sources_scope`): an extra hard + # restriction on top of whatever the model asked for β€” a summary must + # never cover documents outside the user's selected files. Applied as a + # post-filter so it holds for both the exact match and the fuzzy fallback + # paths (and returns the honest empty list when the model's requested + # scope lies entirely outside the selected files). + allowed = {str(s).strip().casefold() for s in (sources_scope or []) if str(s).strip()} + if allowed: + records = [r for r in records + if str(r.get("source", "")).strip().casefold() in allowed] + return records + + +def _tokenize(text: str) -> list[str]: + return [t.lower() for t in re.findall(r"[A-Za-z0-9']+", text or "") if len(t) > 2 and t.lower() not in _SUMMARY_STOPWORDS] + + +def _extract_key_terms(texts: list[str], top_n: int = 8) -> list[str]: + counter = Counter() + for text in texts: + counter.update(_tokenize(text)) + return [term for term, _ in counter.most_common(top_n)] + + +def _split_sentences(text: str) -> list[str]: + parts = re.split(r"(?<=[.!?])\s+", re.sub(r"\s+", " ", text or "").strip()) + return [p.strip() for p in parts if p.strip()] + + +def _score_sentence(sentence: str, frequency: Counter, focus_terms: list[str] | None = None) -> float: + tokens = _tokenize(sentence) + if not tokens: + return 0.0 + score = sum(frequency.get(tok, 0) for tok in tokens) + if focus_terms: + focus_set = {t.lower() for t in focus_terms if t} + score += sum(4 for tok in tokens if tok in focus_set) + length = len(tokens) + quality = 1.0 + if length < 5: + quality *= 0.35 + elif length < 9: + quality *= 0.65 + if len(sentence) < 40: + quality *= 0.85 + if not re.search(r"[.!?]['\")\]]?$", sentence.strip()): + quality *= 0.9 + if sentence[:1].islower(): + quality *= 0.92 + if " " in sentence or "..." in sentence: + quality *= 0.9 + return (score / max(length, 1)) * quality + + +def _pick_top_sentences(sentences: list[str], freq: Counter, focus_terms: list[str] | None = None, + limit: int = 5, seen_keys: set | None = None) -> list[str]: + """Pick top-scoring diverse sentences from a candidate list.""" + if seen_keys is None: + seen_keys = set() + scored = [] + for sentence in sentences: + key = sentence.lower().strip() + if key in seen_keys: + continue + score = _score_sentence(sentence, freq, focus_terms) + if score > 0: + scored.append((score, sentence, key)) + scored.sort(key=lambda item: item[0], reverse=True) + picked = [] + for _, sentence, key in scored: + if len(_tokenize(sentence)) < 4: + continue + seen_keys.add(key) + picked.append(sentence) + if len(picked) >= limit: + break + if not picked and sentences: + for sentence in sentences: + key = sentence.lower().strip() + if key not in seen_keys and len(_tokenize(sentence)) >= 4: + seen_keys.add(key) + picked.append(sentence) + if len(picked) >= limit: + break + if not picked and sentences: + for sentence in sentences[:limit]: + key = sentence.lower().strip() + seen_keys.add(key) + picked.append(sentence) + return picked + + +def _extract_stratified_points(source_records: list[dict], global_freq: Counter, + focus_terms: list[str] | None = None, + base_points: int = 4) -> list[tuple[str, list[str]]]: + """Extract representative sentences across chronological strata of a document. + Ensures broad, beginning-to-end coverage for research papers, manuals, reports, and contracts. + """ + n_chunks = len(source_records) + if not source_records: + return [] + + # Small document (< 5 chunks): single flat section with up to max(base_points, 4) points + if n_chunks < 5: + text = " ".join(r["text"] for r in source_records) + sentences = _split_sentences(text) + picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=max(base_points, 4)) + return [("", picked)] if picked else [] + + # Dynamic target point calculation: + # 5-12 chunks -> max(base_points, 6) + # 13-30 chunks -> max(base_points, 10) + # 31+ chunks -> max(base_points, 15) + if n_chunks <= 12: + total_target = max(base_points, 6) + elif n_chunks <= 30: + total_target = max(base_points, 10) + else: + total_target = max(base_points, 15) + + split1 = max(1, int(n_chunks * 0.28)) + split2 = max(split1 + 1, int(n_chunks * 0.72)) + + zone1_recs = source_records[:split1] + zone2_recs = source_records[split1:split2] + zone3_recs = source_records[split2:] + + budget1 = max(2, int(total_target * 0.30)) + budget2 = max(3, int(total_target * 0.45)) + budget3 = max(2, total_target - budget1 - budget2) + + strata = [ + ("Overview & Objectives", zone1_recs, budget1), + ("Core Substance & Details", zone2_recs, budget2), + ("Conclusions, Terms & Outcomes", zone3_recs, budget3), + ] + + results = [] + seen_keys = set() + + for label, recs, budget in strata: + if not recs: + continue + text = " ".join(r["text"] for r in recs) + sentences = _split_sentences(text) + picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=budget, seen_keys=seen_keys) + if picked: + results.append((label, picked)) + + if not results: + all_text = " ".join(r["text"] for r in source_records) + sentences = _split_sentences(all_text) + picked = _pick_top_sentences(sentences, global_freq, focus_terms, limit=total_target) + if picked: + results.append(("", picked)) + + return results + + +def _summarize_records(records: list[dict], *, title: str, focus: str = "", max_sources: int = 5, + max_points_per_source: int = 4, + visual_sources: Optional[set] = None) -> str: + if not records: + return f"{title}\n\nNo matching documents were found." + + grouped = defaultdict(list) + for record in records: + grouped[record["source"]].append(record) + # Source filenames that ALSO have page images in the visual index β€” + # the scanned / image-heavy docs whose text chunks may be OCR garbage + # but whose PAGE IMAGES carry the real content. The manager routes + # these to `knowledge_searcher` for a `visual_retriever` pass. Defaults + # to the live visual-index lookup so EVERY caller (tool or direct) + # gets the signal; an absent index yields the empty set (no signal). + visual_sources = set(_visual_sources_set() if visual_sources is None else visual_sources) + + all_texts = [r["text"] for r in records] + key_terms = _extract_key_terms(all_texts, top_n=8) + focus_terms = _tokenize(focus) if focus else [] + global_freq = Counter() + for t in all_texts: + global_freq.update(_tokenize(t)) + + lines = [title, ""] + scope_bits = [] + first = records[0] + if first.get("theme"): + scope_bits.append(f"Theme: {first['theme']}") + if first.get("subtheme"): + scope_bits.append(f"Subtheme: {first['subtheme']}") + if focus: + scope_bits.append(f"Focus: {focus}") + lines.append("Scope: " + " | ".join(scope_bits) if scope_bits else "Scope: all matching documents") + lines.append(f"Documents matched: {len(grouped)}") + lines.append(f"Chunks matched: {len(records)}") + if key_terms: + lines.append("Key terms: " + ", ".join(key_terms)) + lines.append("") + + source_items = sorted(grouped.items(), key=lambda item: (-len(item[1]), item[0]))[:max_sources] + for source, source_records in source_items: + lines.append(f"### {source}") + lines.append( + f"- Theme: {source_records[0].get('theme', '') or 'β€”'}" + f" | Subtheme: {source_records[0].get('subtheme', '') or 'β€”'}" + f" | Chunks: {len(source_records)}" + ) + # Visual-index signal: this source ALSO has page images (charts / + # scans / image-heavy PDFs). The text chunks may be unreadable OCR + # β€” the manager must delegate to `knowledge_searcher` with an + # explicit `visual_retriever` task so the actual pages are pulled. + if source in visual_sources: + lines.append("- πŸ–ΌοΈ Page images available in the visual index β€” delegate to " + "`knowledge_searcher` with a `visual_retriever` task to " + "read the ACTUAL page images.") + + stratified = _extract_stratified_points( + source_records, global_freq, focus_terms=focus_terms, + base_points=max_points_per_source + ) + for label, points in stratified: + if label: + lines.append(f"- **{label}**:") + for p in points: + lines.append(f" - {p}") + else: + for p in points: + lines.append(f"- {p}") + lines.append("") + + return "\n".join(lines).strip() + + +def _extract_key_points(records: list[dict], *, focus: str = "", max_points: int = 10, + visual_sources: Optional[set] = None) -> str: + if not records: + return "No matching documents were found." + all_texts = [r["text"] for r in records] + freq = Counter() + for t in all_texts: + freq.update(_tokenize(t)) + focus_terms = _tokenize(focus) if focus else [] + visual_sources = set(_visual_sources_set() if visual_sources is None else visual_sources) + + # If records span multiple chunks, sample across them chronologically + grouped = defaultdict(list) + for r in records: + grouped[r.get("source", "doc")].append(r) + + all_stratified = [] + points_per_doc = max(2, max_points // max(1, len(grouped))) + for src, src_records in grouped.items(): + strat = _extract_stratified_points(src_records, freq, focus_terms=focus_terms, base_points=points_per_doc) + for _, pts in strat: + all_stratified.extend(pts) + + if len(all_stratified) > max_points: + all_stratified = all_stratified[:max_points] + + if not all_stratified: + all_text = " ".join(all_texts) + sentences = _split_sentences(all_text) + all_stratified = _pick_top_sentences(sentences, freq, focus_terms=focus_terms, limit=max_points) + + lines = [] + if focus: + lines.append(f"Key points for focus: {focus}") + else: + lines.append("Key points") + lines.append("") + for idx, sentence in enumerate(all_stratified, start=1): + lines.append(f"{idx}. {sentence}") + # Visual-index signal for the manager (scanned / image-heavy sources). + visual_hits = sorted(src for src in grouped if src in visual_sources) + if visual_hits: + lines.append("") + lines.append("πŸ–ΌοΈ Page images available in the visual index for: " + + ", ".join(visual_hits) + + " β€” delegate to `knowledge_searcher` with a " + "`visual_retriever` task to read the ACTUAL page images.") + return "\n".join(lines).strip() + + +def _clean_mind_map_label(text: str, max_chars: int = 72) -> str: + label = re.sub(r"\s+", " ", str(text or "")).strip() + label = re.sub(r"^[\-*#\d.:\)\s]+", "", label).strip() + if not label: + return "Untitled" + if len(label) <= max_chars: + return label + cut = label[:max_chars].rsplit(" ", 1)[0].strip() + return (cut or label[:max_chars]).rstrip(".,;:") + "..." + + +def _mind_map_points_for_records(records: list[dict], max_points: int = 4) -> list[str]: + if not records: + return [] + text = " ".join(record["text"] for record in records) + sentences = _split_sentences(text) + freq = Counter(_tokenize(text)) + scored = [] + seen = set() + for sentence in sentences: + key = sentence.lower() + if key in seen: + continue + seen.add(key) + score = _score_sentence(sentence, freq) + if score > 0: + scored.append((score, sentence)) + scored.sort(key=lambda item: item[0], reverse=True) + picked = [] + for _, sentence in scored: + if len(_tokenize(sentence)) < 4: + continue + picked.append(_clean_mind_map_label(sentence)) + if len(picked) >= max_points: + break + if not picked: + picked = [_clean_mind_map_label(s) for s in sentences[:max_points]] + return picked + + +def _build_mind_map(records: list[dict], *, theme: str = "", subtheme: str = "", + source: str = "", output_format: str = "tree", + max_documents: int = 8, + max_points_per_document: int = 4) -> str: + if not records: + return "No matching documents were found." + + fmt = (output_format or "tree").strip().lower() + max_documents = max(1, int(max_documents or 8)) + max_points_per_document = max(1, int(max_points_per_document or 4)) + root = source or subtheme or theme or "Knowledge Base" + grouped = defaultdict(lambda: defaultdict(lambda: defaultdict(list))) + for record in records: + theme_name = record.get("theme") or "Unthemed" + subtheme_name = record.get("subtheme") or "General" + source_name = record.get("source") or "unknown" + grouped[theme_name][subtheme_name][source_name].append(record) + + docs_added = 0 + if fmt == "mermaid": + lines = ["mindmap", f" root(({_clean_mind_map_label(root)}))"] + for theme_name, subthemes in sorted(grouped.items()): + lines.append(f" {_clean_mind_map_label(theme_name)}") + for subtheme_name, sources in sorted(subthemes.items()): + lines.append(f" {_clean_mind_map_label(subtheme_name)}") + for source_name, source_records in sorted(sources.items()): + if docs_added >= max_documents: + break + docs_added += 1 + lines.append(f" {_clean_mind_map_label(source_name)}") + for point in _mind_map_points_for_records(source_records, max_points_per_document): + lines.append(f" {_clean_mind_map_label(point)}") + if docs_added >= max_documents: + break + if docs_added >= max_documents: + break + return "\n".join(lines) + + lines = [_clean_mind_map_label(root)] + for theme_name, subthemes in sorted(grouped.items()): + lines.append(f"- {_clean_mind_map_label(theme_name)}") + for subtheme_name, sources in sorted(subthemes.items()): + lines.append(f" - {_clean_mind_map_label(subtheme_name)}") + for source_name, source_records in sorted(sources.items()): + if docs_added >= max_documents: + break + docs_added += 1 + lines.append(f" - {_clean_mind_map_label(source_name)}") + for point in _mind_map_points_for_records(source_records, max_points_per_document): + lines.append(f" - {_clean_mind_map_label(point)}") + if docs_added >= max_documents: + break + if docs_added >= max_documents: + break + return "\n".join(lines) + + +class RetrieverTool(Tool): + """smolagents Tool wrapper around retrieve_context(), for agentic RAG + (see rag_agent.py). Unlike the plain RAG Chat path, which always + retrieves context before calling the LLM, this lets a CodeAgent decide + for itself whether/when to search the knowledge base, and call it more + than once (e.g. to refine a search) before giving a final answer. + """ + name = "retriever" + description = ( + "Uses semantic search over the indexed knowledge base (ChromaDB) to " + "retrieve the document chunks most relevant to a query. This is the " + "ONLY source of information you are permitted to use to answer the " + "user β€” never supplement it with your own general knowledge. Call " + "this before answering any question. It returns a clear 'no relevant " + "documents found' message if the knowledge base is empty or has " + "nothing relevant β€” treat that as a real answer (there is nothing to " + "report), not as a reason to fall back on what you already know. " + "Every returned chunk is tagged with its source filename in " + "brackets, e.g. '[report.pdf]' β€” cite that exact tag in-text " + "immediately after any claim you draw from it." + ) + inputs = { + "query": { + "type": "string", + "description": ( + "The search query. Prefer an affirmative statement close to " + "the target content (e.g. 'steps to push a model to the " + "Hub') rather than a literal question." + ), + } + } + output_type = "string" + + def __init__(self, theme: str = "", subtheme: str = "", sources=None, **kwargs): + super().__init__(**kwargs) + self._theme = theme + self._subtheme = subtheme + self._sources = sources or [] + # Self-tracked usage stats β€” used by rag_agent.py to verify (after + # agent.run() returns) that the model actually searched the + # knowledge base and actually found something, rather than trying + # to introspect smolagents' internal step/memory structure, which + # varies across versions and previously caused false negatives + # (blocking correctly-grounded answers because the introspection + # didn't match this installed version's real internals). + self.call_count = 0 + self.found_count = 0 + # Every unique source name actually returned by a successful + # retrieval this run β€” lets chat.py print a guaranteed-accurate + # References list after the agent answers, independent of whether + # the model remembered to write its own in-text citations (same + # "track it ourselves, don't just trust the model" reasoning as + # call_count/found_count above). + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, query: str) -> str: + assert isinstance(query, str), "Your search query must be a string" + self.call_count += 1 + context, sources = retrieve_context(query, self._theme, self._subtheme, sources=self._sources) + if not context: + return "No relevant documents found β€” the knowledge base may be empty." + self.found_count += 1 + self.sources_used.update(sources) + return f"Retrieved documents (sources: {', '.join(sources)}):\n\n{context}" + + +class VisualRetrieverTool(Tool): + """smolagents Tool wrapper around the VISUAL (image-based) index β€” the + `knowledge_searcher` sub-agent's second retrieval tool, alongside the + text `retriever`. ColPali page images cover what text extraction + misses: charts, tables, scans and image-heavy PDFs whose page renders + carry the information even when their extracted text doesn't. + + A text-only model can't see the images itself, so the tool returns a + TEXT report of the retrieved pages (count + source filenames) and + stashes the ACTUAL page images in the module-level visual-tool hits + cache β€” chat.py's multimodal grounding pass (same-model VLM) then + verifies/refines the agent's draft against those exact pages, so the + "multimodal" half of agentic RAG is realized without the agent needing + an image-capable model. Like RetrieverTool it self-tracks + call_count / found_count / sources_used for the post-run grounding + verification. Never raises.""" + name = "visual_retriever" + description = ( + "Searches the visual (image-based) index of the knowledge base and " + "returns the page images most relevant to a query β€” page renders of " + "PDFs / images indexed for their VISUAL content (charts, tables, " + "scans, image-heavy documents) that plain text search can miss. " + "Use this IN ADDITION to `retriever` when the question is about " + "numbers, figures, charts, screenshots, or anything that would live " + "in a page's image rather than its extracted text, or when the text " + "search came back thin. It returns the number of matching page " + "images and their source filenames; the page images themselves are " + "passed to the multimodal grounding pass so the final answer is " + "verified against the actual pages. Cite the returned source " + "filenames in your references exactly like text sources." + ) + inputs = { + "query": { + "type": "string", + "description": ( + "What to look for in the page images, e.g. 'quarterly revenue " + "chart' or 'the table of tax rates'. Prefer a concrete " + "description of the visual content over a literal question." + ), + }, + "top_k": { + "type": "integer", + "description": "Maximum number of page images to retrieve (default 3).", + "default": 3, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.call_count = 0 + self.found_count = 0 + # Total page images actually decoded and stashed across this run's + # successful calls β€” the REAL image count for the footer note (a + # call that found 3 pages is one found_count, but 3 pages). + self.pages_found = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.pages_found = 0 + self.sources_used = set() + + def forward(self, query: str, top_k: int = 3) -> str: + assert isinstance(query, str), "Your search query must be a string" + self.call_count += 1 + try: + results = _visual_search_results(query, max(1, int(top_k or 3))) + except Exception as e: + print(f"[VIS] visual_retriever tool failed: {e}") + return "The visual index search failed β€” rely on the text `retriever` results only." + if not results: + return ( + "No matching page images found in the visual index β€” either the " + "visual index is empty or nothing visually relevant matched. " + "Rely on the text `retriever` results for this question." + ) + + global _visual_tool_hits + images, sources = [], set() + for r in results: + if not (hasattr(r, "base64") and r.base64): + continue + images.append(Image.open(BytesIO(base64.b64decode(r.base64))).convert("RGB")) + meta = getattr(r, "metadata", None) or {} + src = str(meta.get("source") or "") + if src and src != "In-memory Image": + sources.add(src) + if not images: + return ( + "The visual index matched pages but their images could not be " + "decoded β€” rely on the text `retriever` results for this question." + ) + # Stash the ACTUAL page images for chat.py's multimodal grounding + # pass (the same-model VLM), which runs AFTER the agent's draft is + # done β€” reusing these avoids a second 2-8 GB retriever-model load. + _visual_tool_hits = images + self.found_count += 1 + self.pages_found += len(images) + self.sources_used.update(sources) + src_line = (", ".join(sorted(sources)) if sources else "unknown source") + plural = "image" if len(images) == 1 else "images" + return ( + f"Retrieved {len(images)} page {plural} from the visual index " + f"(sources: {src_line}). These page images will be visually " + "verified against the final answer by the multimodal grounding " + f"pass β€” cite their source filenames ({src_line}) in your " + "references section as [N] entries." + ) + + +class ThemeSummaryTool(Tool): + name = "summarize_theme" + description = ( + "Summarize the indexed knowledge base for one theme, grouping the " + "most relevant document chunks by source and extracting key points. " + "Use this when the user asks for a summary, overview, or main themes " + "within a theme." + ) + inputs = { + "theme": { + "type": "string", + "description": "Theme metadata value to summarize.", + }, + "max_sources": { + "type": "integer", + "description": "Maximum number of source documents to include.", + "default": 5, + "nullable": True, + }, + "max_points_per_source": { + "type": "integer", + "description": "Maximum summary bullets to extract per source.", + "default": 3, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, theme: str, max_sources: int = 5, max_points_per_source: int = 3) -> str: + self.call_count += 1 + records = _collect_scope_records(theme=theme, sources_scope=self._scope_sources) + if records: + self.found_count += 1 + self.sources_used.update({r["source"] for r in records}) + return _summarize_records( + records, + title=f"Theme summary: {theme}", + max_sources=max_sources, + max_points_per_source=max_points_per_source, + visual_sources=_visual_sources_set(), + ) + + +class SubthemeSummaryTool(Tool): + name = "summarize_subtheme" + description = ( + "Summarize the indexed knowledge base for a specific theme and " + "subtheme. Use this when the user wants a narrower summary of a " + "particular subtopic." + ) + inputs = { + "theme": { + "type": "string", + "description": "Theme metadata value to summarize.", + }, + "subtheme": { + "type": "string", + "description": "Subtheme metadata value to summarize.", + }, + "max_sources": { + "type": "integer", + "description": "Maximum number of source documents to include.", + "default": 5, + "nullable": True, + }, + "max_points_per_source": { + "type": "integer", + "description": "Maximum summary bullets to extract per source.", + "default": 3, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, theme: str, subtheme: str, max_sources: int = 5, max_points_per_source: int = 3) -> str: + self.call_count += 1 + records = _collect_scope_records(theme=theme, subtheme=subtheme, sources_scope=self._scope_sources) + if records: + self.found_count += 1 + self.sources_used.update({r["source"] for r in records}) + return _summarize_records( + records, + title=f"Subtheme summary: {theme} / {subtheme}", + max_sources=max_sources, + max_points_per_source=max_points_per_source, + visual_sources=_visual_sources_set(), + ) + + +class DocumentSummaryTool(Tool): + name = "summarize_document" + description = ( + "Summarize one document identified by its source filename. Optionally " + "scope it further by theme or subtheme metadata." + ) + inputs = { + "source": { + "type": "string", + "description": "Source filename to summarize.", + }, + "theme": { + "type": "string", + "description": "Optional theme metadata filter.", + "default": "", + "nullable": True, + }, + "subtheme": { + "type": "string", + "description": "Optional subtheme metadata filter.", + "default": "", + "nullable": True, + }, + "max_points": { + "type": "integer", + "description": "Maximum key points to return.", + "default": 6, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, source: str, theme: str = "", subtheme: str = "", max_points: int = 6) -> str: + self.call_count += 1 + records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources) + if records: + self.found_count += 1 + self.sources_used.update({r["source"] for r in records}) + return _summarize_records( + records, + title=f"Document summary: {source}", + max_sources=1, + max_points_per_source=max_points, + visual_sources=_visual_sources_set(), + ) + + +class KeyPointsTool(Tool): + name = "find_key_points" + description = ( + "Extract the most important points from documents within a theme, " + "subtheme, or source scope. Use this when the user asks for key " + "points, highlights, or takeaways." + ) + inputs = { + "focus": { + "type": "string", + "description": "Optional focus phrase to bias the ranking of key points.", + "default": "", + "nullable": True, + }, + "theme": { + "type": "string", + "description": "Optional theme metadata filter.", + "default": "", + "nullable": True, + }, + "subtheme": { + "type": "string", + "description": "Optional subtheme metadata filter.", + "default": "", + "nullable": True, + }, + "source": { + "type": "string", + "description": "Optional source filename filter.", + "default": "", + "nullable": True, + }, + "max_points": { + "type": "integer", + "description": "Maximum key points to return.", + "default": 8, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, focus: str = "", theme: str = "", subtheme: str = "", source: str = "", max_points: int = 8) -> str: + self.call_count += 1 + records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources) + if records: + self.found_count += 1 + self.sources_used.update({r["source"] for r in records}) + header_bits = [] + if theme: + header_bits.append(f"theme={theme}") + if subtheme: + header_bits.append(f"subtheme={subtheme}") + if source: + header_bits.append(f"source={source}") + title = "Key points" + if header_bits: + title += " (" + ", ".join(header_bits) + ")" + points = _extract_key_points(records, focus=focus, max_points=max_points, + visual_sources=_visual_sources_set()) + return f"{title}\n\n{points}" + + +class MindMapTool(Tool): + name = "create_mind_map" + description = ( + "Create a compact mind map or topic tree from indexed knowledge-base " + "content using theme, subtheme, and source metadata. Use this when " + "the user asks for a mind map, concept map, topic tree, branch " + "structure, or visual outline of indexed documents." + ) + inputs = { + "theme": { + "type": "string", + "description": "Optional theme metadata filter.", + "default": "", + "nullable": True, + }, + "subtheme": { + "type": "string", + "description": "Optional subtheme metadata filter.", + "default": "", + "nullable": True, + }, + "source": { + "type": "string", + "description": "Optional source filename filter.", + "default": "", + "nullable": True, + }, + "output_format": { + "type": "string", + "description": "Use 'tree' for Markdown outline or 'mermaid' for Mermaid mindmap.", + "default": "tree", + "nullable": True, + }, + "max_documents": { + "type": "integer", + "description": "Maximum source documents to include.", + "default": 8, + "nullable": True, + }, + "max_points_per_document": { + "type": "integer", + "description": "Maximum key-point nodes under each document.", + "default": 4, + "nullable": True, + }, + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, theme: str = "", subtheme: str = "", source: str = "", + output_format: str = "tree", max_documents: int = 8, + max_points_per_document: int = 4) -> str: + self.call_count += 1 + records = _collect_scope_records(theme=theme, subtheme=subtheme, source=source, sources_scope=self._scope_sources) + if records: + self.found_count += 1 + self.sources_used.update({r["source"] for r in records}) + return _build_mind_map( + records, + theme=theme, + subtheme=subtheme, + source=source, + output_format=output_format, + max_documents=max_documents, + max_points_per_document=max_points_per_document, + ) + + +class ListTopicsTool(Tool): + name = "list_knowledge_base_topics" + description = ( + "List all available themes, subthemes, and document source filenames " + "indexed in the knowledge base. Use this when the user asks what topics, " + "themes, subthemes, or files are available, or before summarizing when " + "you need to identify valid theme/subtheme/source names from metadata." + ) + inputs = { + "theme": { + "type": "string", + "description": "Optional theme filter to list only subthemes and sources under this theme.", + "default": "", + "nullable": True, + } + } + output_type = "string" + + def __init__(self, sources=None, **kwargs): + super().__init__(**kwargs) + # The RAG tab's multi-select FILE filter β€” the UI's selected source + # filenames. Applied on top of whatever scope the model passes, so a + # summary/topic listing never covers documents outside the user's + # selected files (mirrors how RetrieverTool threads the selection). + self._scope_sources = [str(s).strip() for s in (sources or []) if str(s).strip()] + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def reset_stats(self): + self.call_count = 0 + self.found_count = 0 + self.sources_used = set() + + def forward(self, theme: str = "") -> str: + self.call_count += 1 + themes, subthemes = get_existing_themes_and_subthemes(theme=theme) + table = get_doc_table() + # Scope the file listing to the requested theme β€” a doc-table row is + # [source, type, pages, chunks, themes, subthemes] with the theme + # column comma-joined for multi-tagged files (the same matching rule + # the RAG tab's own rowMatchesFilters uses). Without this the tool + # dumped EVERY indexed file regardless of the theme filter, so an + # agent scoped to one theme saw unrelated documents (CVs, other + # contracts) listed as if they were in scope. + want = str(theme or "").strip().casefold() + allowed = ({str(s).strip().casefold() for s in self._scope_sources} + if self._scope_sources else None) + sources = [] + for row in table: + if not row or not row[0]: + continue + if want: + row_themes = {t.strip().casefold() + for t in str(row[4] or "").split(",") if t.strip()} + if want not in row_themes: + continue + # The RAG tab's selected files are a hard restriction on the + # listing too β€” a file outside the selection is never advertised. + if allowed is not None and str(row[0]).strip().casefold() not in allowed: + continue + sources.append(row[0]) + if themes or subthemes or sources: + self.found_count += 1 + self.sources_used.update(sources) + lines = [] + if theme: + lines.append(f"Knowledge Base Topics (Theme: '{theme}'):") + else: + lines.append("Knowledge Base Topics:") + if themes: + lines.append(f"- Available Themes: {', '.join(themes)}") + else: + lines.append("- Available Themes: (None)") + if subthemes: + lines.append(f"- Available Subthemes: {', '.join(subthemes)}") + if sources: + lines.append(f"- Available Document Files: {', '.join(sources)}") + if not themes and not subthemes and not sources: + lines.append("- (Knowledge base is currently empty)") + return "\n".join(lines) + + +def get_existing_themes_and_subthemes(theme: str = "") -> tuple[list[str], list[str]]: + """Query ChromaDB for all unique non-empty theme and subtheme values in stored metadatas. + If theme is specified and non-empty, subthemes will be filtered to those under that theme. + """ + try: + col = models.get_chroma_collection() + if col.count() == 0: + return [], [] + result = col.get(include=["metadatas"]) + themes = set() + subthemes = set() + theme_stripped = str(theme or "").strip() + for m in result.get("metadatas", []): + t = str(m.get("theme", "")).strip() + st = str(m.get("subtheme", "")).strip() + if t: + themes.add(t) + if st: + if not theme_stripped or t == theme_stripped: + subthemes.add(st) + return sorted(list(themes)), sorted(list(subthemes)) + except Exception: + return [], []