File size: 1,851 Bytes
2d7afea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compute per-verse embeddings for the WEB corpus.

Input:  data/web_bible.json   (from fetch_web_bible.py)
Output: data/verse_embeddings.npy  (float32, L2-normalized, shape [N, 384])
        data/verse_index.json      (list of {book, chapter, verse, text})
"""
import json
import sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
IN_PATH = DATA_DIR / "web_bible.json"
EMBED_PATH = DATA_DIR / "verse_embeddings.npy"
INDEX_PATH = DATA_DIR / "verse_index.json"

MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
BATCH_SIZE = 64


def main() -> int:
    if not IN_PATH.exists():
        print(f"ERROR: {IN_PATH} not found. Run scripts/fetch_web_bible.py first.", file=sys.stderr)
        return 1

    verses = json.loads(IN_PATH.read_text(encoding="utf-8"))
    print(f"Loaded {len(verses)} verses from {IN_PATH}")

    # Per-verse chunks. Including the reference in the embedded text helps
    # queries that mention a book name or citation to retrieve usefully.
    texts = [f"{v['book']} {v['chapter']}:{v['verse']} — {v['text']}" for v in verses]

    from sentence_transformers import SentenceTransformer
    model = SentenceTransformer(MODEL_NAME)
    print(f"Loaded model {MODEL_NAME} (dim={model.get_sentence_embedding_dimension()})")

    print("Embedding ... this will take a few minutes on CPU.")
    embs = model.encode(
        texts,
        batch_size=BATCH_SIZE,
        show_progress_bar=True,
        normalize_embeddings=True,
        convert_to_numpy=True,
    ).astype(np.float32)

    np.save(EMBED_PATH, embs)
    INDEX_PATH.write_text(json.dumps(verses, ensure_ascii=False), encoding="utf-8")
    print(f"Wrote {EMBED_PATH} (shape {embs.shape})")
    print(f"Wrote {INDEX_PATH}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())