File size: 4,559 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
83
84
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
"""Step 3d: build every search index with one command.



    uv run python -m coveragecheck.index.build



Builds System B's BM25 index (chunks.embed_text), B's dense index (same texts) and

System A's dense index (naive_chunks.text), each saved next to the Step 2 tables and

checked by its own load() later. Embeddings go through the vector cache (Step 3b),

so only new or changed texts are embedded: the first run takes ~5 minutes on this

laptop, a rerun with nothing changed takes seconds.

"""

import sys
import time
from collections.abc import Callable
from pathlib import Path

from coveragecheck import config
from coveragecheck.index import dense, lexical
from coveragecheck.index.store import load_table

MAX_MODEL_TOKENS = 512  # bge-small truncates longer texts silently


def count_truncated(texts: list[str], model_dir: Path = config.MODEL_CACHE_DIR) -> int | None:
    """How many texts exceed the model's 512 tokens (their tails are not embedded).

    Uses the model's own tokenizer file; None if the model isn't downloaded yet."""
    files = sorted(model_dir.glob("models--*bge-small-en-v1.5*/snapshots/*/tokenizer.json"))
    if not files:
        return None
    from tokenizers import Tokenizer  # installed with fastembed

    tokenizer = Tokenizer.from_file(str(files[0]))
    tokenizer.no_truncation()  # count the full length, even if the file sets a cap
    tokenizer.no_padding()
    return sum(len(e.ids) > MAX_MODEL_TOKENS for e in tokenizer.encode_batch(texts))


class ModelUnavailable(RuntimeError):
    """The embedding model could not be loaded or run (first build: no download)."""


def guarded(embedder: dense.Embedder) -> dense.Embedder:
    """The embedder, with any failure inside it re-raised as ModelUnavailable, so the

    "check the network" hint is shown only when the model is the problem."""

    def embed(texts: list[str]):
        try:
            return embedder(texts)
        except Exception as error:
            raise ModelUnavailable(f"the embedding model failed: {error}") from error

    return embed


def build_dense(

    name: str,

    ids: list[str],

    texts: list[str],

    directory: Path,

    embedder: dense.Embedder,

    cache: dense.VectorCache,

    log: Callable[[str], None],

) -> None:
    """One dense index: embed through the cache (only new texts), save, report the time

    and how many texts are longer than the model reads."""
    start = time.perf_counter()

    def progress(done: int, total: int) -> None:
        log(f"  {name}: embedded {done}/{total} new texts")

    dense.save(dense.build(ids, texts, embedder, cache, progress=progress), directory)
    log(f"{name}: {len(ids)} texts -> {directory} ({time.perf_counter() - start:.1f} s)")
    too_long = count_truncated(texts)
    if too_long:
        log(f"  note: {too_long} texts exceed {MAX_MODEL_TOKENS} tokens (tails not embedded)")


def build_all(

    embedder: dense.Embedder,

    cache: dense.VectorCache,

    index_dir: Path = config.INDEX_DIR,

    bm25_dir: Path = config.BM25_DIR,

    dense_b_dir: Path = config.DENSE_B_DIR,

    dense_a_dir: Path = config.DENSE_A_DIR,

    log: Callable[[str], None] = print,

) -> None:
    """B lexical, B dense, A dense, in that order (the cheap one first, so a model

    problem still leaves BM25 built). Each index is saved atomically by its module."""
    chunks = load_table(index_dir / "chunks.parquet")
    naive = load_table(index_dir / "naive_chunks.parquet")
    b_ids, b_texts = list(chunks.chunk_id), list(chunks.embed_text)
    a_ids, a_texts = list(naive.chunk_id), list(naive.text)

    start = time.perf_counter()
    lexical.save(lexical.build(b_ids, b_texts), bm25_dir)
    log(f"B lexical: {len(b_ids)} chunks -> {bm25_dir} ({time.perf_counter() - start:.1f} s)")

    build_dense("B dense", b_ids, b_texts, dense_b_dir, embedder, cache, log)
    build_dense("A dense", a_ids, a_texts, dense_a_dir, embedder, cache, log)


def main() -> None:
    try:
        build_all(guarded(dense.fastembed_embedder()), dense.VectorCache.open())
    except ModelUnavailable as error:
        sys.exit(
            f"index build failed: {error}\n(a first build downloads the embedding model "
            f"into {config.MODEL_CACHE_DIR}: check the network or that folder)"
        )
    except (OSError, ValueError) as error:  # a missing table, an unreadable cache ...
        sys.exit(f"index build failed: {error}")


if __name__ == "__main__":
    main()