""" Shared builder for Klara's offline knowledge packs: one SQLite file per pack, the same layout for all. meta(key, value) id, name, domain, source, publisher, license, built, mode, passages, docs docs(id, title, url, publisher) passages(id, doc_id, heading, text, original) heading: what the passage is ("Atik 5", "Kolera: sentòm"); original: the source's own words when `text` is a Kreyòl summary of a text in another language (else empty) passages_fts FTS5 over (heading, text, original), unicode61 without diacritics titles(norm, passage_id, proper, prio) exact names a question can mention ("atik 5", "toussaint louverture") mode says how the app should search a pack: "title" (only exact names, as for Wikipedia, where loose word matches over 34k articles are mostly noise), "search" (full-text passages, for guides), or "both". """ import datetime import re import sqlite3 import unicodedata from dataclasses import dataclass, field def norm(text: str) -> str: """Lowercase, no accents, words of letters and digits separated by single spaces (as the app does).""" plain = unicodedata.normalize("NFD", text.lower()) plain = "".join(c for c in plain if unicodedata.category(c) != "Mn") return " ".join(re.sub(r"[^a-z0-9]+", " ", plain).split()) def chunks(text: str, limit: int = 900, floor: int = 300) -> list[str]: """Split text into passages of at most `limit` characters at paragraph, then sentence, ends.""" paras = [re.sub(r"\s+", " ", p).strip() for p in re.split(r"\n\s*\n|\n", text)] paras = [p for p in paras if p] out, cur = [], "" for p in paras: if len(p) > limit: sentences = re.split(r"(?<=[.!?;:])\s+", p) else: sentences = [p] for s in sentences: while len(s) > limit: # one very long sentence: cut at a space cut = s[:limit].rsplit(" ", 1)[0] if cur: out.append(cur) cur = "" out.append(cut) s = s[len(cut):].strip() if cur and len(cur) + 1 + len(s) > limit: out.append(cur) cur = s else: cur = f"{cur} {s}".strip() if cur else s if len(cur) >= floor: out.append(cur) cur = "" if cur: if out and len(cur) < floor and len(out[-1]) + 1 + len(cur) <= limit * 1.3: out[-1] = f"{out[-1]} {cur}" else: out.append(cur) return out @dataclass class Pack: id: str name: str domain: str source: str publisher: str license: str mode: str = "search" docs: list[tuple[str, str, str]] = field(default_factory=list) # (title, url, publisher) passages: list[tuple[int, str, str, str]] = field(default_factory=list) # (doc index, heading, text, original) titles: dict[str, tuple[int, int, int]] = field(default_factory=dict) # norm -> (passage index, proper, prio) def doc(self, title: str, url: str, publisher: str | None = None) -> int: self.docs.append((title, url, publisher or self.publisher)) return len(self.docs) - 1 def passage(self, doc: int, heading: str, text: str, original: str = "") -> int: self.passages.append((doc, heading.strip(), re.sub(r"[ \t]+", " ", text).strip(), original.strip())) return len(self.passages) - 1 def title(self, name: str, passage: int, proper: bool = True, prio: int = 0) -> None: k = norm(name) if len(k) < 2: return if k not in self.titles or prio > self.titles[k][2]: self.titles[k] = (passage, int(proper), prio) def write(self, path: str, extra_meta: dict | None = None) -> None: con = sqlite3.connect(path) con.executescript(""" DROP TABLE IF EXISTS meta; DROP TABLE IF EXISTS docs; DROP TABLE IF EXISTS passages; DROP TABLE IF EXISTS passages_fts; DROP TABLE IF EXISTS titles; CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT); CREATE TABLE docs (id INTEGER PRIMARY KEY, title TEXT NOT NULL, url TEXT NOT NULL, publisher TEXT NOT NULL); CREATE TABLE passages (id INTEGER PRIMARY KEY, doc_id INTEGER NOT NULL, heading TEXT NOT NULL, text TEXT NOT NULL, original TEXT NOT NULL DEFAULT ''); CREATE VIRTUAL TABLE passages_fts USING fts5(heading, text, original, content='passages', content_rowid='id', tokenize="unicode61 remove_diacritics 2"); CREATE TABLE titles (norm TEXT PRIMARY KEY, passage_id INTEGER NOT NULL, proper INTEGER NOT NULL, prio INTEGER NOT NULL) WITHOUT ROWID; """) con.executemany("INSERT INTO docs VALUES (?, ?, ?, ?)", [(i + 1, *d) for i, d in enumerate(self.docs)]) con.executemany("INSERT INTO passages VALUES (?, ?, ?, ?, ?)", [(i + 1, d + 1, h, t, o) for i, (d, h, t, o) in enumerate(self.passages)]) if self.mode != "title": # name-only packs never search text: no index to carry con.execute("INSERT INTO passages_fts(passages_fts) VALUES ('rebuild')") con.executemany("INSERT INTO titles VALUES (?, ?, ?, ?)", [(k, p + 1, proper, prio) for k, (p, proper, prio) in self.titles.items()]) meta = { "id": self.id, "name": self.name, "domain": self.domain, "source": self.source, "publisher": self.publisher, "license": self.license, "mode": self.mode, "built": datetime.date.today().isoformat(), "format": "3", "docs": str(len(self.docs)), "passages": str(len(self.passages)), "titles": str(len(self.titles)), **(extra_meta or {}), } con.executemany("INSERT INTO meta VALUES (?, ?)", meta.items()) con.commit() con.execute("VACUUM") con.close() print(f"{path}: {len(self.docs)} docs, {len(self.passages)} passages, {len(self.titles)} titles")