bat-6 commited on
Commit
4c2a767
·
1 Parent(s): 88a5be7

feat: add server-side script to rebuild FAISS index for deployment environments

Browse files
Files changed (1) hide show
  1. rebuild_index_server.py +59 -0
rebuild_index_server.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SERVER-SIDE rebuild script (Linux / Azure App Service).
3
+ Run this once on the deployed server to rebuild the FAISS index with all-mpnet-base-v2.
4
+
5
+ Usage:
6
+ cd /home/user/app
7
+ python rebuild_index_server.py
8
+ """
9
+ import os
10
+ os.environ["OMP_NUM_THREADS"] = "1"
11
+ os.environ["MKL_NUM_THREADS"] = "1"
12
+ os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
13
+
14
+ import sys
15
+ sys.path.insert(0, "/home/user/app")
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ import faiss
20
+ from pathlib import Path
21
+ from sentence_transformers import SentenceTransformer
22
+
23
+ MODEL_NAME = "all-mpnet-base-v2"
24
+ MODELS_DIR = Path("/home/user/app/models")
25
+ PARQUET_PATH = MODELS_DIR / "metadata.parquet"
26
+ INDEX_PATH = MODELS_DIR / "faiss_index.bin"
27
+ EMBED_PATH = MODELS_DIR / "project_embeddings.npy"
28
+
29
+ print(f"[SERVER REBUILD] Model: {MODEL_NAME}")
30
+ model = SentenceTransformer(MODEL_NAME)
31
+ dim = model.get_sentence_embedding_dimension()
32
+ print(f"[SERVER REBUILD] Embedding dim: {dim}")
33
+
34
+ df = pd.read_parquet(PARQUET_PATH)
35
+ print(f"[SERVER REBUILD] Loaded {len(df)} projects")
36
+
37
+ def build_text(row):
38
+ return f"{row.get('project_title','') or ''}. {row.get('abstract','') or ''}. {row.get('description','') or ''}".strip()
39
+
40
+ texts = df.apply(build_text, axis=1).tolist()
41
+
42
+ print("[SERVER REBUILD] Generating embeddings...")
43
+ embeddings = model.encode(
44
+ texts,
45
+ convert_to_numpy=True,
46
+ normalize_embeddings=True,
47
+ show_progress_bar=True,
48
+ batch_size=8
49
+ ).astype("float32")
50
+
51
+ print(f"[SERVER REBUILD] Embeddings shape: {embeddings.shape}")
52
+ np.save(str(EMBED_PATH), embeddings)
53
+
54
+ index = faiss.IndexFlatIP(dim)
55
+ index.add(embeddings)
56
+ faiss.write_index(index, str(INDEX_PATH))
57
+
58
+ print(f"[SERVER REBUILD] Done! Index: {index.ntotal} vectors @ {dim}-dim")
59
+ print("[SERVER REBUILD] Restart the app process to reload the index.")