File size: 2,063 Bytes
7c19e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f522e
7c19e41
 
 
 
 
 
 
c9f522e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c19e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""data/te_corpus.jsonl -> data/index/{te.faiss, te_meta.json}

    python scripts/build_index.py

Commit the data/index folder to the Space so it starts without re-embedding.
"""
import json
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import config  # noqa: E402
from core.corpus import doc_text, filter_docs  # noqa: E402
from core.ingest import chunk_text, clean_text  # noqa: E402
from core.rag import Embedder, TEIndex  # noqa: E402


def corpus_to_chunks(path: Path) -> list:
    metas = []
    with open(path, encoding="utf-8") as f:
        docs = [json.loads(line) for line in f if line.strip()]
    docs, dropped = filter_docs(docs)
    if dropped:
        chars = sum(len(doc_text(d)) for d in dropped)
        print(f"dropped {len(dropped)} non-customer/duplicate pages ({chars:,} chars):")
        for d in dropped:
            print("   -", d["url"][:110])
    for d in docs:
        title, url, lang = d.get("title", ""), d["url"], d.get("lang", "")
        if "pages" in d:
            units = [(i, p) for i, p in enumerate(d["pages"], start=1)]
        else:
            units = [(None, d.get("text", ""))]
        for page, text in units:
            for c in chunk_text(clean_text(text)):
                metas.append({"text": c, "title": title, "source": url, "page": page, "lang": lang})
    return metas


def main():
    if not config.CORPUS_PATH.exists():
        sys.exit(f"{config.CORPUS_PATH} not found. Run scripts/scrape_te.py first.")
    metas = corpus_to_chunks(config.CORPUS_PATH)
    print(f"{len(metas)} chunks from {config.CORPUS_PATH}")
    emb = Embedder()
    t = time.time()
    texts = [(m["title"] + "\n" + m["text"]) if m["title"] else m["text"] for m in metas]
    vecs = emb.passages(texts)
    print(f"embedded in {time.time() - t:.1f}s, dim={vecs.shape[1]}")
    TEIndex.build(metas, vecs, config.INDEX_DIR, model_name=config.EMBED_MODEL)
    print(f"saved index -> {config.INDEX_DIR}")


if __name__ == "__main__":
    main()