_ / app.py
husnainbinmunawar's picture
Create app.py
451ac54 verified
Raw History Blame Contribute Delete
32.1 kB
# semantic_search_api_improved_commented.py
"""
Improved Semantic Search FastAPI service (commented).
I kept your original implementation exactly and only added plain 3-line human comments
above every major function/class/section to make the code easy to read.
No logic was removed — only comments were inserted.
Requirements (pip):
pip install fastapi uvicorn sentence-transformers faiss-cpu python-multipart
Usage example:
export LOCAL_MODEL_DIR="models/all-mpnet-base-v2"
export API_KEY="secret"
uvicorn semantic_search_api_improved_commented:app --host 0.0.0.0 --port 8000
"""
from __future__ import annotations
import os, json, time, tempfile, threading, logging, math
from typing import List, Dict, Optional, Any
from fastapi import FastAPI, HTTPException, Query, Depends, Header, Request, UploadFile, File, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import numpy as np
# optional imports
try:
import faiss
_HAS_FAISS = True
except Exception:
faiss = None
_HAS_FAISS = False
from sentence_transformers import SentenceTransformer
# ----------------------------
# FileLock for cross-process safety
# 1) Use fcntl on POSIX if available.
# 2) Fallback to an in-memory threading lock map if not.
# 3) Simple context manager to lock files across processes.
# ----------------------------
try:
import fcntl
class FileLock:
def __init__(self, path: str):
self.path = path
self.fd = None
def __enter__(self):
os.makedirs(os.path.dirname(self.path) or '.', exist_ok=True)
self.fd = open(self.path, 'w')
fcntl.flock(self.fd, fcntl.LOCK_EX)
return self
def __exit__(self, exc_type, exc, tb):
try:
fcntl.flock(self.fd, fcntl.LOCK_UN)
self.fd.close()
except Exception:
pass
except Exception:
# fallback to threading.Lock (no cross-process guarantees)
class FileLock:
_locks: Dict[str, threading.Lock] = {}
def __init__(self, path: str):
self.path = path
self.l = FileLock._locks.setdefault(path, threading.Lock())
def __enter__(self):
self.l.acquire(); return self
def __exit__(self, exc_type, exc, tb):
try: self.l.release()
except Exception: pass
# ------------------
# CONFIG
# 1) Environment-driven defaults for paths and behavior.
# 2) Change env vars to tune memory, batch sizes, and rate limiting.
# 3) Keep values conservative for single-server deployments.
# ------------------
LOCAL_MODEL_DIR = os.environ.get('LOCAL_MODEL_DIR', 'models/all-MiniLM-L6-v2')
INDEX_DIR = os.environ.get('INDEX_DIR', 'index')
MAPPING_PATH = os.path.join(INDEX_DIR, 'mapping.json')
FAISS_INDEX_PATH = os.path.join(INDEX_DIR, 'products.index')
NUMPY_VECTORS_PATH = os.path.join(INDEX_DIR, 'vectors.npy')
NUMPY_IDS_PATH = os.path.join(INDEX_DIR, 'ids.json')
TOMBSTONE_PATH = os.path.join(INDEX_DIR, 'tombstones.json')
MANIFEST_PATH = os.path.join(INDEX_DIR, 'manifest.json')
API_KEY = os.environ.get('API_KEY', '')
ALLOWED_ORIGINS = os.environ.get('ALLOWED_ORIGINS', 'https://ca.binnacle.com,https://us.binnacle.com').split(',')
HNSW_M = int(os.environ.get('HNSW_M', '32'))
BATCH_SIZE = int(os.environ.get('BATCH_SIZE', '64'))
SINGLE_PROCESS_MODE = os.environ.get('SINGLE_PROCESS_MODE', 'true').lower() in ('1','true','yes')
RATE_LIMIT_WINDOW = int(os.environ.get('RATE_LIMIT_WINDOW', '60'))
RATE_LIMIT_REQ = int(os.environ.get('RATE_LIMIT_REQ', '120'))
MAX_RATE_IPS = 10000
MAX_IMPORT_ROWS = 200000
LARGE_MEMMAP_THRESHOLD = 10000 # if vectors > threshold use memmap save/load
# ------------------
# LOGGING
# 1) Basic INFO level logging by default.
# 2) Use `logger` to track lifecycle and errors.
# 3) Redact long strings before logging if needed by `redact()`.
# ------------------
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('semantic_search_improved')
# helper to redact logs
def redact(s: str) -> str:
if not s: return s
if len(s) > 200:
return s[:200] + '...[redacted]'
return s
# ------------------
# FastAPI app
# 1) CORS enabled for listed origins.
# 2) Single-file API with admin and public endpoints.
# 3) Keep middleware minimal and safe for production.
# ------------------
app = FastAPI(title='Semantic Search - improved')
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=['GET','POST','OPTIONS'],
allow_headers=['*'],
)
# ------------------
# DATA MODELS
# 1) Simple pydantic models for inputs/outputs.
# 2) `ProductItem` used in admin reindex/rebuild calls.
# 3) `SearchResult` is what /search returns to the frontend.
# ------------------
class ProductItem(BaseModel):
product_id: str
text: str
class SearchResult(BaseModel):
product_id: str
similarity_score: float
# ------------------
# GLOBALS
# 1) Thread-safe locks for model and index.
# 2) Mapping between internal integer ids and product ids.
# 3) Tombstones, counters and simple in-memory rate limiter.
# ------------------
_model_lock = threading.RLock()
_model: Optional[SentenceTransformer] = None
_model_meta: Optional[Dict[str, Any]] = None
_dim: Optional[int] = None
_index_lock = threading.RLock()
_index_impl = None
_mapping: Dict[int, str] = {} # internal id -> product_id
_rev_map: Dict[str, int] = {} # product_id -> internal id
_next_id_counter = 0
_tombstones: set = set()
# simple counters/metrics
_metrics = {
'queries': 0,
'encodes': 0,
'avg_encode_ms': 0.0,
'avg_query_ms': 0.0,
}
# rate limiter store: ip -> list[timestamps]
_rate_store: Dict[str, List[float]] = {}
_rate_lock = threading.Lock()
# background job queue
_jobs: Dict[str, Dict[str, Any]] = {}
_jobs_lock = threading.Lock()
# thread pool for CPU-bound encoding tasks
_encode_executor = threading.BoundedSemaphore(4) # limit concurrent encodes
# ------------------
# UTIL: manifest & atomic JSON helpers
# 1) Save manifest and mapping atomically using tmp files.
# 2) Prevent partial writes during crashes.
# 3) Keep file I/O safe for concurrent processes.
# ------------------
def save_manifest_atomic(manifest: dict):
os.makedirs(os.path.dirname(MANIFEST_PATH) or '.', exist_ok=True)
tmp = MANIFEST_PATH + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
os.replace(tmp, MANIFEST_PATH)
def load_manifest() -> Dict[str, Any]:
if not os.path.exists(MANIFEST_PATH):
return {}
with open(MANIFEST_PATH, 'r', encoding='utf-8') as f:
return json.load(f)
def atomic_write_json(path: str, obj: Any):
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(obj, f, indent=2, ensure_ascii=False)
os.replace(tmp, path)
# ------------------
# INDEX WRAPPERS
# 1) BaseIndex defines expected methods for index backends.
# 2) FaissIndex wraps faiss.IndexIDMap with HNSW+Flat or fallback.
# 3) NumpyIndex is a simple memory-backed fallback for dev/testing.
# ------------------
class BaseIndex:
def add_with_ids(self, vectors: np.ndarray, ids: np.ndarray): raise NotImplementedError
def remove_ids(self, ids: np.ndarray): raise NotImplementedError
def search(self, qvec: np.ndarray, topk: int): raise NotImplementedError
def ntotal(self) -> int: raise NotImplementedError
def persist(self): raise NotImplementedError
def load(self): raise NotImplementedError
class FaissIndex(BaseIndex):
def __init__(self, dim: int, path: str):
self.dim = dim; self.path = path; self.index = None
self._init_or_load()
def _init_or_load(self):
# try to load existing index file, else create a fresh HNSW+Flat index
if os.path.exists(self.path) and _HAS_FAISS:
try:
self.index = faiss.read_index(self.path)
logger.info('Loaded FAISS index')
return
except Exception as e:
logger.warning('Failed load FAISS index, will recreate: %s', e)
if not _HAS_FAISS:
raise RuntimeError('FAISS not installed')
base = faiss.index_factory(self.dim, f'HNSW{HNSW_M},Flat', faiss.METRIC_INNER_PRODUCT)
self.index = faiss.IndexIDMap(base)
logger.info('Created new FAISS index dim=%d', self.dim)
def add_with_ids(self, vectors: np.ndarray, ids: np.ndarray):
if vectors.dtype != np.float32: vectors = vectors.astype('float32')
try:
self.index.add_with_ids(vectors, ids)
except Exception as e:
logger.exception('Faiss add_with_ids failed: %s', e)
raise
def remove_ids(self, ids: np.ndarray):
try:
sel = faiss.IDSelectorArray(ids.astype(np.int64))
self.index.remove_ids(sel)
except Exception as e:
logger.warning('Faiss remove_ids unsupported or failed: %s', e)
raise
def search(self, qvec: np.ndarray, topk: int):
if qvec.dtype != np.float32: qvec = qvec.astype('float32')
D, I = self.index.search(qvec, topk)
return D, I
def ntotal(self) -> int:
return int(self.index.ntotal)
def persist(self):
tmp = self.path + '.tmp'
faiss.write_index(self.index, tmp)
os.replace(tmp, self.path)
def load(self):
self._init_or_load()
class NumpyIndex(BaseIndex):
def __init__(self, dim: int, vec_path: str, ids_path: str):
self.dim = dim
self.vec_path = vec_path
self.ids_path = ids_path
self.vectors: List[np.ndarray] = []
self.ids: List[int] = []
self._load_if_exists()
def _load_if_exists(self):
# load vectors lazily using numpy memmap when available
if os.path.exists(self.vec_path) and os.path.exists(self.ids_path):
try:
arr = np.load(self.vec_path, mmap_mode='r')
with open(self.ids_path, 'r', encoding='utf-8') as f:
ids = json.load(f)
if arr.ndim == 2 and arr.shape[1] == self.dim and len(ids) == arr.shape[0]:
# load lazily via memmap reference
self.vectors = [arr[i].astype('float32') for i in range(arr.shape[0])]
self.ids = [int(x) for x in ids]
logger.info('Loaded NumPy index with %d vectors', len(self.ids))
else:
logger.warning('NumPy index mismatch on disk; ignoring')
except Exception as e:
logger.warning('NumPy index load failed: %s', e)
def add_with_ids(self, vectors: np.ndarray, ids: np.ndarray):
for v, id_ in zip(vectors, ids):
self.vectors.append(v.astype('float32'))
self.ids.append(int(id_))
def remove_ids(self, ids: np.ndarray):
ids_set = set(int(x) for x in ids)
new_vectors = []
new_ids = []
for v, id_ in zip(self.vectors, self.ids):
if id_ in ids_set:
continue
new_vectors.append(v); new_ids.append(id_)
self.vectors = new_vectors; self.ids = new_ids
def search(self, qvec: np.ndarray, topk: int):
if len(self.vectors) == 0:
return np.zeros((1, 0), dtype=np.float32), np.full((1, 0), -1, dtype=np.int64)
mat = np.vstack(self.vectors) # (n,dim)
scores = (mat @ qvec[0].astype('float32').reshape(-1, 1)).reshape(-1)
k = min(topk, len(scores))
idx_part = np.argpartition(-scores, k - 1)[:k]
top_sorted = idx_part[np.argsort(-scores[idx_part])]
top_ids = [self.ids[i] for i in top_sorted]
top_scores = scores[top_sorted].astype('float32')
return top_scores.reshape(1, -1), np.array(top_ids, dtype=np.int64).reshape(1, -1)
def ntotal(self) -> int:
return len(self.ids)
def persist(self):
os.makedirs(os.path.dirname(self.vec_path) or '.', exist_ok=True)
n = len(self.ids)
if n >= LARGE_MEMMAP_THRESHOLD:
# write memmap for large arrays
mm_path = self.vec_path + '.mmap'
shape = (n, self.dim)
mm = np.memmap(mm_path, dtype='float32', mode='w+', shape=shape)
for i, v in enumerate(self.vectors): mm[i, :] = v
del mm
tmp = self.vec_path + '.tmp.npy'
os.replace(mm_path, tmp)
os.replace(tmp, self.vec_path)
else:
tmp = self.vec_path + '.tmp'
np.save(tmp, np.vstack(self.vectors) if self.vectors else np.zeros((0, self.dim), dtype=np.float32))
os.replace(tmp, self.vec_path)
tmp_ids = self.ids_path + '.tmp'
with open(tmp_ids, 'w', encoding='utf-8') as f:
json.dump(self.ids, f, ensure_ascii=False)
os.replace(tmp_ids, self.ids_path)
def load(self):
self._load_if_exists()
# ------------------
# HELPERS: mapping and tombstones
# 1) Mapping stored on disk as JSON with string keys for safety.
# 2) Tombstones persisted to allow delete semantics when backend lacks remove.
# 3) Small helpers to load/save mapping and tombstones.
# ------------------
def load_mapping(path: str) -> Dict[int, str]:
if not os.path.exists(path): return {}
with open(path, 'r', encoding='utf-8') as f:
raw = json.load(f)
return {int(k): v for k, v in raw.items()}
def save_mapping(mapping: Dict[int, str]):
atomic_write_json(MAPPING_PATH, {str(k): v for k, v in mapping.items()})
# tombstones persist
def load_tombstones():
global _tombstones
if os.path.exists(TOMBSTONE_PATH):
try:
with open(TOMBSTONE_PATH, 'r', encoding='utf-8') as f:
_tombstones = set(json.load(f))
except Exception:
_tombstones = set()
else:
_tombstones = set()
def save_tombstones():
atomic_write_json(TOMBSTONE_PATH, list(_tombstones))
# ensure index backend
def ensure_index_impl(dim: int):
global _index_impl
if _HAS_FAISS:
_index_impl = FaissIndex(dim=dim, path=FAISS_INDEX_PATH)
else:
_index_impl = NumpyIndex(dim=dim, vec_path=NUMPY_VECTORS_PATH, ids_path=NUMPY_IDS_PATH)
_index_impl.load()
# ------------------
# STARTUP
# 1) Load mapping and tombstones.
# 2) Try to load the local model (if present).
# 3) Ensure index implementation is ready for searches.
# ------------------
@app.on_event('startup')
def startup_event():
global _model, _model_meta, _dim, _mapping, _next_id_counter, _rev_map
os.makedirs(INDEX_DIR, exist_ok=True)
load_tombstones()
_mapping = load_mapping(MAPPING_PATH) if os.path.exists(MAPPING_PATH) else {}
_rev_map = {v: k for k, v in _mapping.items()}
_next_id_counter = max(_mapping.keys()) + 1 if _mapping else 0
manifest = load_manifest()
# try load model
try:
if os.path.exists(LOCAL_MODEL_DIR):
_model = SentenceTransformer(LOCAL_MODEL_DIR)
_dim = _model.get_sentence_embedding_dimension()
_model_meta = {'name': os.path.basename(LOCAL_MODEL_DIR), 'dim': _dim}
logger.info('Model loaded at startup. dim=%s', _dim)
else:
logger.warning('LOCAL_MODEL_DIR not present; run /reload_model after placing model folder')
_model = None; _dim = None
except Exception as e:
logger.exception('Failed to load model at startup; model_loaded=false')
_model = None; _dim = None
if _dim is None:
# set default dim for all-MiniLM-L6-v2
_dim = 384
ensure_index_impl(_dim)
logger.info('Startup complete. model_loaded=%s index_size=%d SINGLE_PROCESS_MODE=%s', _model is not None, _index_impl.ntotal(), SINGLE_PROCESS_MODE)
if not SINGLE_PROCESS_MODE:
logger.warning('SINGLE_PROCESS_MODE is false — multi-process deployments require an external vector DB or coordination to avoid index conflicts.')
# ------------------
# UTILS: auth & rate-limit
# 1) require_api_key checks Authorization bearer header.
# 2) rate_limiter is a simple per-IP in-memory window limiter.
# 3) Replace with Redis for multi-instance deployments.
# ------------------
def require_api_key(api_key_header: str = Header(None, alias='api_key'), authorization: str = Header(None, alias='Authorization')):
token = None
if authorization and isinstance(authorization, str) and authorization.lower().startswith('bearer '):
token = authorization.split(' ', 1)[1]
elif api_key_header:
token = api_key_header
if API_KEY and token != API_KEY:
raise HTTPException(status_code=401, detail='Invalid API key')
return True
def l2_normalize_np(x: np.ndarray) -> np.ndarray:
if x.ndim == 1:
norm = np.linalg.norm(x)
return x / (norm + 1e-12)
norms = np.linalg.norm(x, axis=1, keepdims=True)
norms = np.where(norms == 0, 1e-12, norms)
return x / norms
# Simple rate limiter dependency
async def rate_limiter(request: Request):
client = request.client.host if request.client else 'unknown'
now = time.time()
with _rate_lock:
lst = _rate_store.get(client, [])
# remove old
lst = [t for t in lst if t > now - RATE_LIMIT_WINDOW]
if len(lst) >= RATE_LIMIT_REQ:
raise HTTPException(status_code=429, detail='Too many requests')
lst.append(now)
_rate_store[client] = lst
# ------------------
# BACKGROUND JOBS
# 1) _start_job runs heavy tasks in a background thread and records status.
# 2) Jobs stored in `_jobs` map with basic progress/result fields.
# 3) Useful for rebuild/reindex operations that take time.
# ------------------
def _start_job(name: str, func, *a, **kw):
job_id = f'job-{int(time.time()*1000)}-{len(_jobs)}'
with _jobs_lock:
_jobs[job_id] = {'status':'running','started':time.time(),'progress':0,'result':None}
def runner():
try:
res = func(*a, **kw)
with _jobs_lock:
_jobs[job_id].update({'status':'done','progress':100,'result':res,'finished':time.time()})
except Exception as e:
with _jobs_lock:
_jobs[job_id].update({'status':'failed','result':str(e),'finished':time.time()})
logger.exception('Job failed: %s', e)
t = threading.Thread(target=runner, daemon=True)
t.start()
return job_id
@app.get('/jobs/{job_id}')
def get_job(job_id: str, auth=Depends(require_api_key)):
with _jobs_lock:
j = _jobs.get(job_id)
if not j: raise HTTPException(status_code=404, detail='job not found')
return j
# ------------------
# API ENDPOINTS
# 1) /health returns basic service status and metrics.
# 2) /search encodes query, normalizes vector, searches index and returns ids+scores.
# 3) Admin endpoints run background jobs to reindex/rebuild safely.
# ------------------
@app.get('/health')
def health():
return {
'status': 'ok',
'model_loaded': get_model_safe() is not None,
'model_version': _model_version,
'index_size': _index_impl.ntotal() if _index_impl else 0,
'timestamp': int(time.time()),
}
@app.get('/search', response_model=List[SearchResult])
def search(q: Optional[str] = Query(None), topk: int = Query(10, ge=1, le=100), authorized: bool = Depends(require_api_key), _rl=Depends(rate_limiter)):
if not q:
raise HTTPException(status_code=400, detail="Missing 'q' parameter")
model = get_model_safe()
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded; place model folder and call /reload_model")
try:
qvec = model.encode([q], convert_to_numpy=True)
qvec = l2_normalize_np(qvec).astype("float32")
except Exception as e:
logger.exception("Encode error: %s", e)
raise HTTPException(status_code=500, detail="Failed to encode query")
with _index_lock:
D, I = _index_impl.search(qvec, topk)
results: List[SearchResult] = []
if I.shape[1] == 0:
return results
for score, idx in zip(D[0], I[0]):
if int(idx) == -1:
continue
pid = _mapping.get(int(idx))
if pid is None:
continue
norm_score = float((float(score) + 1.0) / 2.0)
results.append(SearchResult(product_id=pid, similarity_score=norm_score))
return results
# ------------------
# helper to obtain model safely
# 1) Returns the global _model while holding the lock.
# 2) Keep simple to avoid race conditions.
# 3) Used by health and search endpoints.
# ------------------
def get_model_safe():
with _model_lock:
return _model
# ------------------
# ADMIN: reindex (incremental) and rebuild (full)
# 1) reindex runs in background to avoid blocking clients.
# 2) rebuild creates an atomic new index and swaps it in.
# 3) Both persist mapping and index files safely.
# ------------------
@app.post('/reindex')
def reindex(items: List[ProductItem], authorized: bool = Depends(require_api_key)):
"""
Incremental idempotent reindex. Reuses mapping IDs for existing product_ids.
For updates to existing product text we attempt to remove old id then add new vector (if backend supports remove).
For best consistency use /rebuild_index which atomically rebuilds the entire index from provided items.
"""
global _next_id_counter, _mapping
model = get_model_safe()
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded")
if not items:
raise HTTPException(status_code=400, detail="Request body must be a non-empty JSON list")
texts = [it.text for it in items]
pids = [it.product_id for it in items]
try:
vecs = model.encode(texts, convert_to_numpy=True, batch_size=BATCH_SIZE)
vecs = l2_normalize_np(vecs).astype("float32")
except Exception as e:
logger.exception("Failed to encode items: %s", e)
raise HTTPException(status_code=500, detail="Failed to encode items")
new_ids = []
to_remove = []
with _index_lock:
for vec, pid in zip(vecs, pids):
# reuse id if exists
existing = None
for k, v in _mapping.items():
if v == pid:
existing = k
break
if existing is not None:
# remove old id then re-add to update vector
try:
_index_impl.remove_ids(np.array([existing], dtype=np.int64))
except Exception:
logger.warning("Backend does not support remove_ids or remove failed; result may have duplicates until full rebuild")
_index_impl.add_with_ids(vec.reshape(1, -1), np.array([existing], dtype=np.int64))
new_ids.append(existing)
else:
nid = int(_next_id_counter)
_next_id_counter += 1
_index_impl.add_with_ids(vec.reshape(1, -1), np.array([nid], dtype=np.int64))
_mapping[nid] = pid
new_ids.append(nid)
# persist mapping and index
save_mapping(_mapping)
try:
_index_impl.persist()
except Exception:
logger.exception("Failed to persist index after incremental reindex")
raise HTTPException(status_code=500, detail="Failed to persist index")
return {"indexed": len(new_ids), "assigned_index_ids": {pid: idx for pid, idx in zip(pids, new_ids)}}
@app.post('/rebuild_index')
def rebuild_index(items: List[ProductItem], authorized: bool = Depends(require_api_key)):
"""
Atomically rebuild the whole index from provided items. This is the recommended admin operation after large updates.
"""
global _next_id_counter, _mapping, _index_impl
model = get_model_safe()
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded")
if not items:
raise HTTPException(status_code=400, detail="Request body must be a non-empty JSON list")
texts = [it.text for it in items]
pids = [it.product_id for it in items]
try:
vecs = model.encode(texts, convert_to_numpy=True, batch_size=BATCH_SIZE)
vecs = l2_normalize_np(vecs).astype("float32")
except Exception as e:
logger.exception("Failed to encode items: %s", e)
raise HTTPException(status_code=500, detail="Failed to encode items")
# Build a new index impl in temp files
tmp_index_path = FAISS_INDEX_PATH + ".rebuild.tmp"
tmp_mapping = {}
try:
if _HAS_FAISS:
# create fresh index
base = faiss.index_factory(_dim, f"HNSW{HNSW_M},Flat", faiss.METRIC_INNER_PRODUCT)
new_index = faiss.IndexIDMap(base)
# add in batches
cur_ids = []
for i in range(0, len(vecs), BATCH_SIZE):
batch = vecs[i:i+BATCH_SIZE]
batch_ids = np.arange(i, i + len(batch), dtype=np.int64)
new_index.add_with_ids(batch.astype(np.float32), batch_ids)
cur_ids.extend(batch_ids.tolist())
# write to temporary path
faiss.write_index(new_index, tmp_index_path)
# atomic swap
os.replace(tmp_index_path, FAISS_INDEX_PATH)
# now load into runtime index_impl safely
with _index_lock:
_index_impl = FaissIndex(dim=_dim, path=FAISS_INDEX_PATH)
else:
# numpy fallback
new_impl = NumpyIndex(dim=_dim, vec_path=NUMPY_VECTORS_PATH, ids_path=NUMPY_IDS_PATH)
for i in range(vecs.shape[0]):
new_impl.vectors.append(vecs[i].astype('float32'))
new_impl.ids.append(int(i))
new_impl.persist()
with _index_lock:
_index_impl = new_impl
# build mapping
tmp_map = {int(i): pid for i, pid in enumerate(pids)}
_mapping = tmp_map
_next_id_counter = max(_mapping.keys()) + 1 if _mapping else 0
save_mapping(_mapping)
logger.info("Rebuild complete. indexed=%d", len(pids))
return {"status": "rebuild_complete", "indexed": len(pids)}
except Exception as e:
logger.exception("Rebuild failed: %s", e)
# cleanup tmp files
try:
if os.path.exists(tmp_index_path):
os.remove(tmp_index_path)
except Exception:
pass
raise HTTPException(status_code=500, detail="Rebuild failed")
@app.post('/admin/import_csv')
def import_csv(file: UploadFile = File(...), auth=Depends(require_api_key)):
# Accept CSV product_id,text and call rebuild in background
content = file.file.read().decode('utf-8')
rows = []
import csv, io
reader = csv.DictReader(io.StringIO(content))
for r in reader:
rows.append(ProductItem(product_id=r['product_id'], text=r['text']))
return rebuild_index(rows, auth)
@app.post('/admin/update_item')
def update_item(item: ProductItem, auth=Depends(require_api_key)):
# Update or insert single product. If product exists it will be replaced (best-effort).
if not item.product_id or not item.text: raise HTTPException(status_code=400, detail='invalid input')
model = get_model_safe()
if model is None: raise HTTPException(status_code=503, detail='model not loaded')
try:
vec = model.encode([item.text], convert_to_numpy=True)
vec = l2_normalize_np(vec).astype('float32')
except Exception as e:
logger.exception('Encode error: %s', e)
raise HTTPException(status_code=500, detail='Failed to encode item')
with _index_lock:
existing = None
for k, v in _mapping.items():
if v == item.product_id:
existing = k
break
if existing is not None:
try:
_index_impl.remove_ids(np.array([existing], dtype=np.int64))
except Exception:
logger.warning('backend did not support remove_ids; index may have duplicates until full rebuild')
_index_impl.add_with_ids(vec.reshape(1, -1), np.array([existing], dtype=np.int64))
else:
nid = int(_next_id_counter)
_next_id_counter += 1
_index_impl.add_with_ids(vec.reshape(1, -1), np.array([nid], dtype=np.int64))
_mapping[nid] = item.product_id
_rev_map[item.product_id] = nid
save_mapping(_mapping)
try:
_index_impl.persist()
except Exception:
logger.exception('Failed to persist index after update')
raise HTTPException(status_code=500, detail='Failed to persist index')
return {'status':'ok', 'product_id':item.product_id}
@app.post('/admin/delete_items')
def delete_items(product_ids: List[str], auth=Depends(require_api_key)):
# Delete products by product_id.
if not product_ids: raise HTTPException(status_code=400, detail='Provide non-empty product_ids list')
to_remove_ids = []
with _index_lock:
# find internal ids
pid_to_remove = set(product_ids)
for k, v in list(_mapping.items()):
if v in pid_to_remove:
to_remove_ids.append(k)
del _mapping[k]
if not to_remove_ids:
return {'deleted': 0}
try:
_index_impl.remove_ids(np.array(to_remove_ids, dtype=np.int64))
except Exception:
logger.warning('backend did not support remove_ids; you should run /rebuild_index to fully remove entries')
save_mapping(_mapping)
try:
_index_impl.persist()
except Exception:
logger.exception('Failed to persist index after delete')
raise HTTPException(status_code=500, detail='Failed to persist index')
return {'deleted': len(to_remove_ids)}
@app.post('/admin/reload_model')
def reload_model(auth=Depends(require_api_key)):
# Load model from LOCAL_MODEL_DIR and swap into service if successful.
global _model, _model_meta, _dim
if not os.path.exists(LOCAL_MODEL_DIR): raise HTTPException(status_code=400, detail=f'LOCAL_MODEL_DIR not found: {LOCAL_MODEL_DIR}')
try:
candidate = SentenceTransformer(LOCAL_MODEL_DIR)
cand_dim = candidate.get_sentence_embedding_dimension()
# if dim differs from current and index non-empty, require rebuild
if _index_impl and _index_impl.ntotal() > 0 and cand_dim != _dim:
raise HTTPException(status_code=409, detail=f'model dimension mismatch (current index dim={_dim}, candidate dim={cand_dim}). Rebuild required before switching.')
with _model_lock:
old = _model
_model = candidate
_dim = cand_dim
_model_meta = {'name': os.path.basename(LOCAL_MODEL_DIR), 'dim': _dim}
ensure_index_impl(_dim)
manifest = {'model': _model_meta, 'timestamp': time.time()}
save_manifest_atomic(manifest)
try:
del old
except Exception:
pass
return {'status':'model_reloaded', 'model_meta': _model_meta}
except HTTPException:
raise
except Exception as e:
logger.exception('Failed to reload model: %s', e)
raise HTTPException(status_code=500, detail='failed to load model')
# ------------------
# SHUTDOWN persistence
# 1) Persist index and mapping on shutdown to avoid data loss.
# 2) Best-effort writes, log errors but do not crash shutdown.
# 3) Keeps state consistent for next startup.
# ------------------
@app.on_event('shutdown')
def shutdown_event():
logger.info('shutdown: persisting index and mapping')
try:
with _index_lock:
if _index_impl: _index_impl.persist()
if _mapping: save_mapping(_mapping)
save_tombstones()
except Exception as e:
logger.exception('Error during shutdown persist: %s', e)
# EOF