"""
Saving text for search: cut it into passages, make a meaning fingerprint for each passage, and store
both in Postgres through LlamaIndex's vector store. The same rows also get a keyword index, so search
can match exact words ("RREF", "Dijkstra") as well as meaning.
Two passage tables (LlamaIndex adds the data_ prefix):
- data_notes every student's own notes; every read and search is limited to one user_id
- data_library the shared course library (library.py): one copy, searched by every student
Safety: LlamaIndex writes metadata filter values straight into its SQL, so filters only ever use
values the server made itself: user ids (checked) and hashed keys of paths, courses and subjects
(path_key, course_key, subject_key). SQL written here always uses bound parameters.
"""
import hashlib
import logging
import re
import threading
import uuid
from llama_index.core import Document
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import TextNode
from llama_index.core.vector_stores.types import FilterOperator, MetadataFilter, MetadataFilters
from backend import db, settings
from backend.pages import PageStarts, page_at
from backend.pipeline import models
from backend.store import clean_text
logger = logging.getLogger(__name__)
NOTES_TABLE = "notes" # → data_notes
LIBRARY_TABLE = "library" # → data_library
EMBED_BATCH = 64
_SAFE_ID = re.compile(r"^[A-Za-z0-9_-]{1,80}$")
_stores: dict[str, object] = {}
_stores_lock = threading.Lock()
# ---------- Keys used in filters ----------
def key(kind: str, value: str) -> str:
"""Filter-safe key for a path, course or subject: a letter and 40 hex digits."""
return kind[0] + hashlib.sha256((value or "").encode("utf-8")).hexdigest()[:40]
def path_key(path: str) -> str:
return key("p", path)
def course_key(course: str) -> str:
return key("c", course)
def subject_key(subject: str) -> str:
return key("s", subject)
def safe_user_id(user_id: str) -> str:
if not _SAFE_ID.match(user_id or ""):
raise ValueError("Invalid user id")
return user_id
def where(**equals: str) -> MetadataFilters:
"""LlamaIndex filters: every key equals its value (values must be safe keys or user ids)."""
return MetadataFilters(filters=[MetadataFilter(key=k, value=v) for k, v in equals.items()])
def where_not(filters: MetadataFilters, **not_equal: str) -> MetadataFilters:
extra = [MetadataFilter(key=k, value=v, operator=FilterOperator.NE) for k, v in not_equal.items()]
return MetadataFilters(filters=[*filters.filters, *extra])
# ---------- The vector stores ----------
def _store(table: str, indexed: set[tuple[str, str]]):
store = _stores.get(table)
if store is not None:
return store
with _stores_lock:
if table not in _stores:
from llama_index.vector_stores.postgres import PGVectorStore
db.init()
store = PGVectorStore(
engine=db.engine(),
async_engine=db.async_engine(),
table_name=table,
embed_dim=settings.EMBED_DIM,
hybrid_search=True, # keyword search (Postgres full text) next to meaning search
text_search_config="english", # English words are stemmed; other scripts are kept as they are
use_jsonb=True,
indexed_metadata_keys=indexed,
# No approximate (HNSW) index: each search covers one student's or one course's passages,
# which Postgres scans exactly in milliseconds, and an exact scan never misses a passage.
)
store.get_nodes(node_ids=["-"]) # creates the table and its indexes once, before any search
_stores[table] = store
return _stores[table]
def notes_store():
return _store(NOTES_TABLE, {("user_id", "text"), ("path_key", "text"), ("course_key", "text")})
def library_store():
return _store(LIBRARY_TABLE, {("path_key", "text"), ("subject_key", "text")})
def forget_stores() -> None:
with _stores_lock:
_stores.clear()
# ---------- Cutting text into passages ----------
_splitter = SentenceSplitter(
chunk_size=settings.CHUNK_CHARS,
chunk_overlap=settings.CHUNK_OVERLAP_CHARS,
tokenizer=list, # sizes in characters (the same in every language), not model tokens
paragraph_separator="\n\n",
secondary_chunking_regex="[^,.;।。?!?!]+[,.;।。?!?!]?", # also ends sentences at the Hindi danda (।)
include_metadata=False,
include_prev_next_rel=False,
)
def split_text(text: str) -> list[tuple[str, int]]:
"""Passages of about CHUNK_CHARS characters, each with where it starts in `text`."""
text = clean_text(text)
if not text.strip():
return []
out: list[tuple[str, int]] = []
prev_start, prev_end = -1, 0
for node in _splitter.get_nodes_from_documents([Document(text=text)]):
chunk = node.get_content()
if not chunk.strip():
continue
# LlamaIndex finds a passage's first occurrence, which is wrong for repeated text: search
# forward instead. A passage starts after the previous one, at most CHUNK_OVERLAP_CHARS back.
frm = max(prev_start + 1, prev_end - settings.CHUNK_OVERLAP_CHARS)
start = text.find(chunk, frm)
if start < 0:
start = text.find(chunk[:80], frm)
if start < 0:
start = max(frm, 0)
out.append((chunk, start))
prev_start, prev_end = start, start + len(chunk)
return out
def _with_embeddings(nodes: list[TextNode]) -> list[TextNode]:
for i in range(0, len(nodes), EMBED_BATCH):
batch = nodes[i : i + EMBED_BATCH]
for node, emb in zip(batch, models.embed_passages([n.text for n in batch])):
node.embedding = emb
return nodes
def join_chunks(chunks: list[str], max_overlap: int = 300) -> str:
"""Join ordered passages, dropping the text repeated between neighbours (passages overlap on purpose)."""
out = ""
for ch in chunks:
if not out:
out = ch
continue
overlap = 0
for k in range(min(max_overlap, len(ch), len(out)), 0, -1):
if out.endswith(ch[:k]):
overlap = k
break
out += ch[overlap:] if overlap else "\n\n" + ch
return out
# ---------- A student's notes ----------
def _note_metadata(user_id: str, path: str, source_file: str) -> dict:
from backend.file_meta import course_id_from_path, get_entry
fm = get_entry(user_id, path)
course = course_id_from_path(path)
return {
"user_id": safe_user_id(str(user_id)),
"path": str(path or ""),
"path_key": path_key(path),
"source_file": str(source_file or ""),
"course_id": course,
"course_key": course_key(course),
"is_primary_authority": int(bool(fm.get("is_primary_authority"))),
"doc_type": str(fm.get("doc_type") or "other"),
}
def _replace_note_passages(user_id: str, path: str, nodes: list[TextNode], version: str) -> None:
"""Add the new passages first, then drop older versions: a failure never leaves the file empty."""
if nodes:
notes_store().add(nodes)
db.execute(
"DELETE FROM data_notes WHERE metadata_->>'user_id' = :u AND metadata_->>'path_key' = :pk "
"AND coalesce(metadata_->>'ver', '') <> :ver",
u=user_id,
pk=path_key(path),
ver=version,
)
# Page breaks and markup a passage may start with (Sarvam writes "---" between pages).
_LEADING_BREAKS = re.compile(r"^(?:\s|-{3,}|\*{3,}|_{3,}|
|