| |
| """ |
| Build FAISS indices from library vectors. Plan §1.3: index_smi, index_chem. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import sys |
| from pathlib import Path |
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| if str(ROOT) not in sys.path: |
| sys.path.insert(0, str(ROOT)) |
|
|
| from spec_rag.faiss_index import build_hnsw_index, save_index |
| from spec_rag.io import ensure_dir |
|
|
|
|
| def parse_args(): |
| p = argparse.ArgumentParser(description="Build index_smi.faiss, index_chem.faiss, and index_flare.faiss") |
| p.add_argument("--library-dir", required=True, help="Directory with vectors_smi.npy, vectors_chem.npy, and/or vectors_flare.npy") |
| p.add_argument("--out-dir", default=None, help="Defaults to library-dir") |
| p.add_argument("--metric", choices=["cosine", "l2"], default="cosine") |
| p.add_argument("--m", type=int, default=32) |
| p.add_argument("--ef-construction", type=int, default=200) |
| p.add_argument("--ef-search", type=int, default=256, help="HNSW ef_search; higher improves recall") |
| p.add_argument("--smi-only", action="store_true", help="Only build index_smi") |
| p.add_argument("--chem-only", action="store_true", help="Only build index_chem") |
| p.add_argument("--flare-only", action="store_true", help="Only build index_flare") |
| return p.parse_args() |
|
|
|
|
| def main(): |
| args = parse_args() |
| lib = Path(args.library_dir) |
| out = ensure_dir(args.out_dir or lib) |
|
|
| import numpy as np |
|
|
| if args.flare_only: |
| targets = [("flare", "vectors_flare.npy", "index_flare.faiss")] |
| else: |
| targets = [] |
| if not args.chem_only: |
| targets.append(("smi", "vectors_smi.npy", "index_smi.faiss")) |
| targets.append(("flare", "vectors_flare.npy", "index_flare.faiss")) |
| if not args.smi_only: |
| targets.append(("chem", "vectors_chem.npy", "index_chem.faiss")) |
|
|
| for label, vec_name, index_name in targets: |
| vec_path = lib / vec_name |
| if not vec_path.exists(): |
| print(f"Skip index_{label}: {vec_path} not found") |
| continue |
| v = np.load(vec_path).astype(np.float32) |
| idx = build_hnsw_index( |
| v, m=args.m, ef_construction=args.ef_construction, |
| ef_search=args.ef_search, metric=args.metric, |
| ) |
| save_index(idx, out / index_name) |
| print(f"Saved {index_name} ({v.shape[0]} vectors)") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|