Skip to content

Search

Derived search index: SQLite FTS5 (BM25) + embeddings, fused with reciprocal rank fusion, then reranked.

The index lives in <vault>/.murmurvault/index.db and can always be rebuilt from the vault. Vectors are brute-forced with numpy, which is fast enough for tens of thousands of chunks.

Embedder

Text embeddings from a local sentence-transformers model or an OpenAI-compatible API.

Source code in src/murmurvault/search.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
class Embedder:
    """Text embeddings from a local sentence-transformers model or an OpenAI-compatible API."""

    def __init__(self, cfg: dict):
        """Configure from the ``[embedding]`` section.

        Args:
            cfg: The ``[embedding]`` config section.
        """
        self.cfg = cfg
        self.backend = cfg.get("backend", "local")
        self.model_id = f"{self.backend}:{cfg.get('model')}"

    @property
    def enabled(self) -> bool:
        """Whether embeddings are configured at all."""
        return self.backend != "none"

    def embed(self, texts: list[str], query: bool = False) -> np.ndarray:
        """Embed texts as unit vectors.

        Args:
            texts: Texts to embed.
            query: Prefix with the configured query instruction.

        Returns:
            A ``(len(texts), dim)`` float32 array of unit vectors.

        Raises:
            RuntimeError: If the local backend's extra is missing.
            ValueError: If the backend is unknown.
        """
        if query and self.cfg.get("query_prefix"):
            texts = [self.cfg["query_prefix"] + t for t in texts]
        if self.backend == "local":
            key = ("embed", self.cfg["model"])
            if key not in _MODELS:
                try:
                    from sentence_transformers import SentenceTransformer
                except ImportError as exc:
                    raise RuntimeError("local embeddings need `pip install 'murmurvault[search]'`") from exc
                _MODELS[key] = SentenceTransformer(self.cfg["model"])
            vecs = _MODELS[key].encode(texts, normalize_embeddings=True, convert_to_numpy=True)
            return np.asarray(vecs, dtype=np.float32)
        if self.backend == "openai":
            import httpx

            resp = httpx.post(
                f"{self.cfg['base_url'].rstrip('/')}/embeddings",
                headers=_auth(self.cfg),
                json={"model": self.cfg["model"], "input": texts},
                timeout=120,
            )
            resp.raise_for_status()
            data = sorted(resp.json()["data"], key=lambda d: d["index"])
            vecs = np.asarray([d["embedding"] for d in data], dtype=np.float32)
            return vecs / np.maximum(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12)
        raise ValueError(f"unknown embedding backend {self.backend!r}")

enabled property

Whether embeddings are configured at all.

__init__(cfg)

Configure from the [embedding] section.

Parameters:

Name Type Description Default
cfg dict

The [embedding] config section.

required
Source code in src/murmurvault/search.py
165
166
167
168
169
170
171
172
173
def __init__(self, cfg: dict):
    """Configure from the ``[embedding]`` section.

    Args:
        cfg: The ``[embedding]`` config section.
    """
    self.cfg = cfg
    self.backend = cfg.get("backend", "local")
    self.model_id = f"{self.backend}:{cfg.get('model')}"

embed(texts, query=False)

Embed texts as unit vectors.

Parameters:

Name Type Description Default
texts list[str]

Texts to embed.

required
query bool

Prefix with the configured query instruction.

False

Returns:

Type Description
ndarray

A (len(texts), dim) float32 array of unit vectors.

Raises:

Type Description
RuntimeError

If the local backend's extra is missing.

ValueError

If the backend is unknown.

Source code in src/murmurvault/search.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def embed(self, texts: list[str], query: bool = False) -> np.ndarray:
    """Embed texts as unit vectors.

    Args:
        texts: Texts to embed.
        query: Prefix with the configured query instruction.

    Returns:
        A ``(len(texts), dim)`` float32 array of unit vectors.

    Raises:
        RuntimeError: If the local backend's extra is missing.
        ValueError: If the backend is unknown.
    """
    if query and self.cfg.get("query_prefix"):
        texts = [self.cfg["query_prefix"] + t for t in texts]
    if self.backend == "local":
        key = ("embed", self.cfg["model"])
        if key not in _MODELS:
            try:
                from sentence_transformers import SentenceTransformer
            except ImportError as exc:
                raise RuntimeError("local embeddings need `pip install 'murmurvault[search]'`") from exc
            _MODELS[key] = SentenceTransformer(self.cfg["model"])
        vecs = _MODELS[key].encode(texts, normalize_embeddings=True, convert_to_numpy=True)
        return np.asarray(vecs, dtype=np.float32)
    if self.backend == "openai":
        import httpx

        resp = httpx.post(
            f"{self.cfg['base_url'].rstrip('/')}/embeddings",
            headers=_auth(self.cfg),
            json={"model": self.cfg["model"], "input": texts},
            timeout=120,
        )
        resp.raise_for_status()
        data = sorted(resp.json()["data"], key=lambda d: d["index"])
        vecs = np.asarray([d["embedding"] for d in data], dtype=np.float32)
        return vecs / np.maximum(np.linalg.norm(vecs, axis=1, keepdims=True), 1e-12)
    raise ValueError(f"unknown embedding backend {self.backend!r}")

Hit dataclass

A search result: one chunk of a transcript.

Attributes:

Name Type Description
rec_id str

Recording id.

title str

Recording title.

folder str

Recording folder.

start float

Chunk start time in seconds.

end float

Chunk end time in seconds.

speaker str | None

Comma-separated speakers in the chunk.

text str

Chunk text.

score float

Reranker score, or the fused rank score when reranking is off.

Source code in src/murmurvault/search.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@dataclass
class Hit:
    """A search result: one chunk of a transcript.

    Attributes:
        rec_id: Recording id.
        title: Recording title.
        folder: Recording folder.
        start: Chunk start time in seconds.
        end: Chunk end time in seconds.
        speaker: Comma-separated speakers in the chunk.
        text: Chunk text.
        score: Reranker score, or the fused rank score when reranking is off.
    """

    rec_id: str
    title: str
    folder: str
    start: float
    end: float
    speaker: str | None
    text: str
    score: float

    def to_dict(self) -> dict[str, Any]:
        """Serialise to a JSON-compatible dict.

        Returns:
            The hit as plain data.
        """
        return asdict(self)

to_dict()

Serialise to a JSON-compatible dict.

Returns:

Type Description
dict[str, Any]

The hit as plain data.

Source code in src/murmurvault/search.py
76
77
78
79
80
81
82
def to_dict(self) -> dict[str, Any]:
    """Serialise to a JSON-compatible dict.

    Returns:
        The hit as plain data.
    """
    return asdict(self)

Index

The search index of one vault.

Source code in src/murmurvault/search.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
class Index:
    """The search index of one vault."""

    def __init__(self, vault: Vault, cfg: dict):
        """Open (and create if needed) the index database.

        Args:
            vault: The vault to index.
            cfg: The configuration.
        """
        self.vault = vault
        self.db = sqlite3.connect(vault.internal / "index.db")
        self.db.executescript(SCHEMA)
        self.embedder = Embedder(cfg["embedding"])
        self.reranker = Reranker(cfg["rerank"])

    def close(self) -> None:
        """Close the database."""
        self.db.close()

    def _meta(self, key: str) -> str | None:
        row = self.db.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
        return row[0] if row else None

    def _set_meta(self, key: str, value: str) -> None:
        self.db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)", (key, value))

    def remove(self, rec_id: str) -> None:
        """Drop a recording from the index.

        Args:
            rec_id: Recording id.
        """
        self.db.execute("DELETE FROM chunks WHERE rec_id = ?", (rec_id,))
        self.db.commit()

    def update(self, rec: Recording, transcript: Transcript | None = None) -> int:
        """(Re-)index a recording's transcript.

        If embedding fails, the chunks are still indexed for keyword search.

        Args:
            rec: The recording.
            transcript: Transcript to index; defaults to the active one.

        Returns:
            Number of chunks indexed.
        """
        transcript = transcript or self.vault.load_transcript(rec)
        self.db.execute("DELETE FROM chunks WHERE rec_id = ?", (rec.id,))
        if transcript is None:
            self.db.commit()
            return 0
        chunks = chunk_segments(transcript.segments)
        vecs: np.ndarray | None = None
        stored = self._meta("embedding_model")
        if chunks and self.embedder.enabled and stored not in {None, self.embedder.model_id}:
            # Never mix vectors from two models in one index; keyword search still covers these chunks.
            logger.warning(
                "index was embedded with %s, config says %s; run `murmurvault reindex` to embed new recordings",
                stored,
                self.embedder.model_id,
            )
        elif chunks and self.embedder.enabled:
            try:
                vecs = self.embedder.embed([c["text"] for c in chunks])
                self._set_meta("embedding_model", self.embedder.model_id)
            except Exception as exc:  # noqa: BLE001 -- missing model or API outage must not block indexing
                logger.warning("embeddings skipped (%s); keyword search still works", exc)
        for i, c in enumerate(chunks):
            emb = vecs[i].tobytes() if vecs is not None else None
            self.db.execute(
                "INSERT INTO chunks(rec_id, start, end, speaker, text, emb) VALUES (?, ?, ?, ?, ?, ?)",
                (rec.id, c["start"], c["end"], c["speaker"], c["text"], emb),
            )
        self.db.commit()
        return len(chunks)

    def rebuild(self) -> tuple[int, int]:
        """Rebuild the whole index from the vault.

        Returns:
            Number of recordings and number of chunks indexed.
        """
        self.db.execute("DELETE FROM chunks")
        self.db.execute("DELETE FROM meta")
        self.db.commit()
        recs = self.vault.recordings()
        n = sum(self.update(r) for r in recs)
        return len(recs), n

    def _keyword(self, query: str, allowed: set[str], limit: int) -> list[int]:
        q = fts_query(query)
        if not q:
            return []
        # Filter inside the query so the LIMIT applies to allowed recordings only. The ids travel as one
        # JSON parameter, which avoids SQLite's limit on the number of bound parameters.
        rows = self.db.execute(
            "SELECT c.id FROM chunks_fts f JOIN chunks c ON c.id = f.rowid "
            "WHERE chunks_fts MATCH ? AND c.rec_id IN (SELECT value FROM json_each(?)) "
            "ORDER BY bm25(chunks_fts) LIMIT ?",
            (q, json.dumps(sorted(allowed)), limit),
        ).fetchall()
        return [cid for (cid,) in rows]

    def _semantic(self, query: str, allowed: set[str], limit: int) -> list[int]:
        if not self.embedder.enabled:
            return []
        stored = self._meta("embedding_model")
        if not stored:
            return []
        if stored != self.embedder.model_id:
            logger.warning(
                "index was embedded with %s, config says %s; run `murmurvault reindex`. Using keyword search only.",
                stored,
                self.embedder.model_id,
            )
            return []
        rows = [
            r
            for r in self.db.execute("SELECT id, rec_id, emb FROM chunks WHERE emb IS NOT NULL").fetchall()
            if r[1] in allowed
        ]
        if not rows:
            return []
        try:
            qv = self.embedder.embed([query], query=True)[0]
        except Exception as exc:  # noqa: BLE001 -- fall back to keyword search
            logger.warning("semantic search skipped (%s)", exc)
            return []
        mat = np.stack([np.frombuffer(r[2], dtype=np.float32) for r in rows])
        order = np.argsort(-(mat @ qv))[:limit]
        return [rows[i][0] for i in order]

    def search(  # noqa: PLR0913
        self,
        query: str,
        *,
        k: int = 10,
        folder: str | None = None,
        tags: list[str] | None = None,
        rerank: bool = True,
        candidates: int = 50,
    ) -> list[Hit]:
        """Hybrid search: BM25 and vector candidates fused by RRF, then reranked.

        Args:
            query: Free-text query.
            k: Number of hits to return.
            folder: Only recordings in this folder or below.
            tags: Only recordings carrying all these tags.
            rerank: Rerank the fused candidates.
            candidates: Candidates taken from each retriever.

        Returns:
            The best hits, best first.
        """
        recs = {r.id: r for r in self.vault.recordings(folder=folder, tags=tags)}
        if not recs:
            return []
        allowed = set(recs)
        fused = rrf([self._keyword(query, allowed, candidates), self._semantic(query, allowed, candidates)])
        ranked = sorted(fused, key=fused.__getitem__, reverse=True)[: max(k * 3, 20)]
        if not ranked:
            return []
        placeholders = ",".join("?" * len(ranked))
        rows = self.db.execute(
            # Only "?" placeholders are interpolated; the values are bound parameters.
            f"SELECT id, rec_id, start, end, speaker, text FROM chunks WHERE id IN ({placeholders})",  # noqa: S608
            ranked,
        ).fetchall()
        by_id = {r[0]: r for r in rows}
        ranked = [cid for cid in ranked if cid in by_id]
        scores = {cid: fused[cid] for cid in ranked}

        if rerank and self.reranker.enabled and len(ranked) > 1:
            try:
                rs = self.reranker.scores(query, [by_id[c][5] for c in ranked])
                scores = dict(zip(ranked, rs, strict=True))
                ranked = sorted(ranked, key=scores.__getitem__, reverse=True)
            except Exception as exc:  # noqa: BLE001 -- keep the fused order
                logger.warning("reranking skipped (%s)", exc)

        hits = []
        for cid in ranked[:k]:
            _, rid, start, end, speaker, text = by_id[cid]
            rec = recs[rid]
            hits.append(Hit(rid, rec.title, rec.folder, start, end, speaker, text, round(scores[cid], 4)))
        return hits

__init__(vault, cfg)

Open (and create if needed) the index database.

Parameters:

Name Type Description Default
vault Vault

The vault to index.

required
cfg dict

The configuration.

required
Source code in src/murmurvault/search.py
285
286
287
288
289
290
291
292
293
294
295
296
def __init__(self, vault: Vault, cfg: dict):
    """Open (and create if needed) the index database.

    Args:
        vault: The vault to index.
        cfg: The configuration.
    """
    self.vault = vault
    self.db = sqlite3.connect(vault.internal / "index.db")
    self.db.executescript(SCHEMA)
    self.embedder = Embedder(cfg["embedding"])
    self.reranker = Reranker(cfg["rerank"])

close()

Close the database.

Source code in src/murmurvault/search.py
298
299
300
def close(self) -> None:
    """Close the database."""
    self.db.close()

rebuild()

Rebuild the whole index from the vault.

Returns:

Type Description
tuple[int, int]

Number of recordings and number of chunks indexed.

Source code in src/murmurvault/search.py
360
361
362
363
364
365
366
367
368
369
370
371
def rebuild(self) -> tuple[int, int]:
    """Rebuild the whole index from the vault.

    Returns:
        Number of recordings and number of chunks indexed.
    """
    self.db.execute("DELETE FROM chunks")
    self.db.execute("DELETE FROM meta")
    self.db.commit()
    recs = self.vault.recordings()
    n = sum(self.update(r) for r in recs)
    return len(recs), n

remove(rec_id)

Drop a recording from the index.

Parameters:

Name Type Description Default
rec_id str

Recording id.

required
Source code in src/murmurvault/search.py
309
310
311
312
313
314
315
316
def remove(self, rec_id: str) -> None:
    """Drop a recording from the index.

    Args:
        rec_id: Recording id.
    """
    self.db.execute("DELETE FROM chunks WHERE rec_id = ?", (rec_id,))
    self.db.commit()

search(query, *, k=10, folder=None, tags=None, rerank=True, candidates=50)

Hybrid search: BM25 and vector candidates fused by RRF, then reranked.

Parameters:

Name Type Description Default
query str

Free-text query.

required
k int

Number of hits to return.

10
folder str | None

Only recordings in this folder or below.

None
tags list[str] | None

Only recordings carrying all these tags.

None
rerank bool

Rerank the fused candidates.

True
candidates int

Candidates taken from each retriever.

50

Returns:

Type Description
list[Hit]

The best hits, best first.

Source code in src/murmurvault/search.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def search(  # noqa: PLR0913
    self,
    query: str,
    *,
    k: int = 10,
    folder: str | None = None,
    tags: list[str] | None = None,
    rerank: bool = True,
    candidates: int = 50,
) -> list[Hit]:
    """Hybrid search: BM25 and vector candidates fused by RRF, then reranked.

    Args:
        query: Free-text query.
        k: Number of hits to return.
        folder: Only recordings in this folder or below.
        tags: Only recordings carrying all these tags.
        rerank: Rerank the fused candidates.
        candidates: Candidates taken from each retriever.

    Returns:
        The best hits, best first.
    """
    recs = {r.id: r for r in self.vault.recordings(folder=folder, tags=tags)}
    if not recs:
        return []
    allowed = set(recs)
    fused = rrf([self._keyword(query, allowed, candidates), self._semantic(query, allowed, candidates)])
    ranked = sorted(fused, key=fused.__getitem__, reverse=True)[: max(k * 3, 20)]
    if not ranked:
        return []
    placeholders = ",".join("?" * len(ranked))
    rows = self.db.execute(
        # Only "?" placeholders are interpolated; the values are bound parameters.
        f"SELECT id, rec_id, start, end, speaker, text FROM chunks WHERE id IN ({placeholders})",  # noqa: S608
        ranked,
    ).fetchall()
    by_id = {r[0]: r for r in rows}
    ranked = [cid for cid in ranked if cid in by_id]
    scores = {cid: fused[cid] for cid in ranked}

    if rerank and self.reranker.enabled and len(ranked) > 1:
        try:
            rs = self.reranker.scores(query, [by_id[c][5] for c in ranked])
            scores = dict(zip(ranked, rs, strict=True))
            ranked = sorted(ranked, key=scores.__getitem__, reverse=True)
        except Exception as exc:  # noqa: BLE001 -- keep the fused order
            logger.warning("reranking skipped (%s)", exc)

    hits = []
    for cid in ranked[:k]:
        _, rid, start, end, speaker, text = by_id[cid]
        rec = recs[rid]
        hits.append(Hit(rid, rec.title, rec.folder, start, end, speaker, text, round(scores[cid], 4)))
    return hits

update(rec, transcript=None)

(Re-)index a recording's transcript.

If embedding fails, the chunks are still indexed for keyword search.

Parameters:

Name Type Description Default
rec Recording

The recording.

required
transcript Transcript | None

Transcript to index; defaults to the active one.

None

Returns:

Type Description
int

Number of chunks indexed.

Source code in src/murmurvault/search.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def update(self, rec: Recording, transcript: Transcript | None = None) -> int:
    """(Re-)index a recording's transcript.

    If embedding fails, the chunks are still indexed for keyword search.

    Args:
        rec: The recording.
        transcript: Transcript to index; defaults to the active one.

    Returns:
        Number of chunks indexed.
    """
    transcript = transcript or self.vault.load_transcript(rec)
    self.db.execute("DELETE FROM chunks WHERE rec_id = ?", (rec.id,))
    if transcript is None:
        self.db.commit()
        return 0
    chunks = chunk_segments(transcript.segments)
    vecs: np.ndarray | None = None
    stored = self._meta("embedding_model")
    if chunks and self.embedder.enabled and stored not in {None, self.embedder.model_id}:
        # Never mix vectors from two models in one index; keyword search still covers these chunks.
        logger.warning(
            "index was embedded with %s, config says %s; run `murmurvault reindex` to embed new recordings",
            stored,
            self.embedder.model_id,
        )
    elif chunks and self.embedder.enabled:
        try:
            vecs = self.embedder.embed([c["text"] for c in chunks])
            self._set_meta("embedding_model", self.embedder.model_id)
        except Exception as exc:  # noqa: BLE001 -- missing model or API outage must not block indexing
            logger.warning("embeddings skipped (%s); keyword search still works", exc)
    for i, c in enumerate(chunks):
        emb = vecs[i].tobytes() if vecs is not None else None
        self.db.execute(
            "INSERT INTO chunks(rec_id, start, end, speaker, text, emb) VALUES (?, ?, ?, ?, ?, ?)",
            (rec.id, c["start"], c["end"], c["speaker"], c["text"], emb),
        )
    self.db.commit()
    return len(chunks)

Reranker

Query-document relevance from a local cross-encoder or a /v1/rerank API.

Source code in src/murmurvault/search.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
class Reranker:
    """Query-document relevance from a local cross-encoder or a ``/v1/rerank`` API."""

    def __init__(self, cfg: dict):
        """Configure from the ``[rerank]`` section.

        Args:
            cfg: The ``[rerank]`` config section.
        """
        self.cfg = cfg
        self.backend = cfg.get("backend", "local")

    @property
    def enabled(self) -> bool:
        """Whether reranking is configured at all."""
        return self.backend != "none"

    def scores(self, query: str, docs: list[str]) -> list[float]:
        """Score each document's relevance to the query.

        Args:
            query: The query.
            docs: Candidate documents.

        Returns:
            One score per document; higher is more relevant.

        Raises:
            RuntimeError: If the local backend's extra is missing.
            ValueError: If the backend is unknown.
        """
        if self.backend == "local":
            key = ("rerank", self.cfg["model"])
            if key not in _MODELS:
                try:
                    from sentence_transformers import CrossEncoder
                except ImportError as exc:
                    raise RuntimeError("local reranking needs `pip install 'murmurvault[search]'`") from exc
                _MODELS[key] = CrossEncoder(self.cfg["model"])
            return [float(s) for s in _MODELS[key].predict([(query, d) for d in docs])]
        if self.backend == "api":
            import httpx

            resp = httpx.post(
                f"{self.cfg['base_url'].rstrip('/')}/rerank",
                headers=_auth(self.cfg),
                json={"model": self.cfg["model"], "query": query, "documents": docs, "top_n": len(docs)},
                timeout=120,
            )
            resp.raise_for_status()
            out = [0.0] * len(docs)
            for r in resp.json()["results"]:
                out[r["index"]] = float(r.get("relevance_score", r.get("score", 0.0)))
            return out
        raise ValueError(f"unknown rerank backend {self.backend!r}")

enabled property

Whether reranking is configured at all.

__init__(cfg)

Configure from the [rerank] section.

Parameters:

Name Type Description Default
cfg dict

The [rerank] config section.

required
Source code in src/murmurvault/search.py
225
226
227
228
229
230
231
232
def __init__(self, cfg: dict):
    """Configure from the ``[rerank]`` section.

    Args:
        cfg: The ``[rerank]`` config section.
    """
    self.cfg = cfg
    self.backend = cfg.get("backend", "local")

scores(query, docs)

Score each document's relevance to the query.

Parameters:

Name Type Description Default
query str

The query.

required
docs list[str]

Candidate documents.

required

Returns:

Type Description
list[float]

One score per document; higher is more relevant.

Raises:

Type Description
RuntimeError

If the local backend's extra is missing.

ValueError

If the backend is unknown.

Source code in src/murmurvault/search.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def scores(self, query: str, docs: list[str]) -> list[float]:
    """Score each document's relevance to the query.

    Args:
        query: The query.
        docs: Candidate documents.

    Returns:
        One score per document; higher is more relevant.

    Raises:
        RuntimeError: If the local backend's extra is missing.
        ValueError: If the backend is unknown.
    """
    if self.backend == "local":
        key = ("rerank", self.cfg["model"])
        if key not in _MODELS:
            try:
                from sentence_transformers import CrossEncoder
            except ImportError as exc:
                raise RuntimeError("local reranking needs `pip install 'murmurvault[search]'`") from exc
            _MODELS[key] = CrossEncoder(self.cfg["model"])
        return [float(s) for s in _MODELS[key].predict([(query, d) for d in docs])]
    if self.backend == "api":
        import httpx

        resp = httpx.post(
            f"{self.cfg['base_url'].rstrip('/')}/rerank",
            headers=_auth(self.cfg),
            json={"model": self.cfg["model"], "query": query, "documents": docs, "top_n": len(docs)},
            timeout=120,
        )
        resp.raise_for_status()
        out = [0.0] * len(docs)
        for r in resp.json()["results"]:
            out[r["index"]] = float(r.get("relevance_score", r.get("score", 0.0)))
        return out
    raise ValueError(f"unknown rerank backend {self.backend!r}")

chunk_segments(segments, max_chars=CHUNK_CHARS)

Group consecutive segments into windows of about max_chars, overlapping by one segment.

Parameters:

Name Type Description Default
segments list[Segment]

Transcript segments in time order.

required
max_chars int

Target window size in characters.

CHUNK_CHARS

Returns:

Type Description
list[dict[str, Any]]

Chunks with start, end, speaker and text.

Source code in src/murmurvault/search.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def chunk_segments(segments: list[Segment], max_chars: int = CHUNK_CHARS) -> list[dict[str, Any]]:
    """Group consecutive segments into windows of about ``max_chars``, overlapping by one segment.

    Args:
        segments: Transcript segments in time order.
        max_chars: Target window size in characters.

    Returns:
        Chunks with ``start``, ``end``, ``speaker`` and ``text``.
    """
    chunks: list[dict[str, Any]] = []
    window: list[Segment] = []

    def flush():
        speakers = list(dict.fromkeys(s.speaker for s in window if s.speaker))
        text = " ".join(f"{s.speaker}: {s.text}" if s.speaker else s.text for s in window)
        chunks.append(
            {"start": window[0].start, "end": window[-1].end, "speaker": ", ".join(speakers) or None, "text": text}
        )

    size = 0
    for seg in segments:
        if not seg.text.strip():
            continue
        window.append(seg)
        size += len(seg.text) + 1
        if size >= max_chars:
            flush()
            window = window[-1:]
            size = len(window[0].text) + 1
    # After a flush the window holds only the overlap segment, which is already indexed. Segment ends are
    # not monotonic once tracks are merged, so compare lengths rather than times.
    if window and (not chunks or len(window) > 1):
        flush()
    return chunks

fts_query(text)

Turn free text into an FTS5 query that matches any of its words.

Parameters:

Name Type Description Default
text str

The user's query.

required

Returns:

Type Description
str

Quoted terms joined by OR; empty if the text has no words.

Source code in src/murmurvault/search.py
122
123
124
125
126
127
128
129
130
131
132
def fts_query(text: str) -> str:
    """Turn free text into an FTS5 query that matches any of its words.

    Args:
        text: The user's query.

    Returns:
        Quoted terms joined by ``OR``; empty if the text has no words.
    """
    terms = re.findall(r"\w+", text.lower())
    return " OR ".join(f'"{t}"' for t in terms)

rrf(rankings, k=RRF_K)

Reciprocal rank fusion.

Parameters:

Name Type Description Default
rankings list[list[int]]

Ranked lists of item ids, best first.

required
k int

Damping constant.

RRF_K

Returns:

Type Description
dict[int, float]

Item id to fused score.

Source code in src/murmurvault/search.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def rrf(rankings: list[list[int]], k: int = RRF_K) -> dict[int, float]:
    """Reciprocal rank fusion.

    Args:
        rankings: Ranked lists of item ids, best first.
        k: Damping constant.

    Returns:
        Item id to fused score.
    """
    scores: dict[int, float] = {}
    for ranking in rankings:
        for rank, item in enumerate(ranking):
            scores[item] = scores.get(item, 0.0) + 1.0 / (k + rank + 1)
    return scores