| """Faiss vector store utilities.""" |
|
|
| from __future__ import annotations |
|
|
| import json |
| from pathlib import Path |
| from typing import Dict, Iterable, List, Tuple |
|
|
| import numpy as np |
|
|
| try: |
| import faiss |
| except Exception: |
| faiss = None |
|
|
|
|
| def _require_faiss(): |
| if faiss is None: |
| raise ImportError( |
| "faiss is required for vector index operations. Install `faiss-cpu` in the active environment." |
| ) |
|
|
|
|
| def _normalize(vectors: np.ndarray) -> np.ndarray: |
| if vectors.size == 0: |
| return vectors |
| if faiss is not None: |
| faiss.normalize_L2(vectors) |
| return vectors |
| norms = np.linalg.norm(vectors, axis=1, keepdims=True) |
| norms = np.where(norms <= 0.0, 1.0, norms) |
| vectors /= norms |
| return vectors |
|
|
|
|
| def build_faiss_index(embeddings: np.ndarray, normalize: bool = True): |
| _require_faiss() |
| if embeddings.size == 0: |
| raise ValueError("embeddings are empty") |
| vecs = embeddings.copy() |
| if normalize: |
| vecs = _normalize(vecs) |
| index = faiss.IndexFlatIP(vecs.shape[1]) |
| else: |
| index = faiss.IndexFlatL2(vecs.shape[1]) |
| index.add(vecs) |
| return index |
|
|
|
|
| def save_index(index, path: str) -> None: |
| _require_faiss() |
| Path(path).parent.mkdir(parents=True, exist_ok=True) |
| faiss.write_index(index, path) |
|
|
|
|
| def load_index(path: str): |
| _require_faiss() |
| return faiss.read_index(path) |
|
|
|
|
| def save_metadata(rows: Iterable[Dict], path: str) -> None: |
| Path(path).parent.mkdir(parents=True, exist_ok=True) |
| with open(path, "w", encoding="utf-8") as f: |
| for r in rows: |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") |
|
|
|
|
| def load_metadata(path: str) -> List[Dict]: |
| rows = [] |
| with open(path, "r", encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| rows.append(json.loads(line)) |
| return rows |
|
|
|
|
| def search_index( |
| index, |
| metadata: List[Dict], |
| query_vec: np.ndarray, |
| top_k: int = 5, |
| normalize: bool = True, |
| ) -> List[Tuple[Dict, float]]: |
| if query_vec.ndim == 1: |
| query_vec = query_vec.reshape(1, -1) |
| q = query_vec.astype(np.float32) |
| if normalize: |
| _normalize(q) |
| scores, idxs = index.search(q, top_k) |
| results: List[Tuple[Dict, float]] = [] |
| for i, score in zip(idxs[0], scores[0]): |
| if i < 0 or i >= len(metadata): |
| continue |
| results.append((metadata[i], float(score))) |
| return results |
|
|