Spaces:
Running on Zero
Running on Zero
Download scripts/build_index.py from MustafaHussein/te-assistant: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/scripts/build_index.py
- Command line
-
hf download hf://spaces/MustafaHussein/te-assistant/scripts/build_index.py
-
curl -L -o build_index.py https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/scripts/build_index.py
2.06 kB
| #!/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() | |