Spaces:
Sleeping
Sleeping
Create vector_store.py
Browse files- app/vector_store.py +55 -0
app/vector_store.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
import faiss
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import logging
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout)
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
class BaseVectorStore(ABC):
|
| 12 |
+
@abstractmethod
|
| 13 |
+
def add_documents(self, documents, embeddings):
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
@abstractmethod
|
| 17 |
+
def search(self, query_vector, num_results=5):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
class FaissVectorStore(BaseVectorStore):
|
| 21 |
+
def __init__(self, dimension):
|
| 22 |
+
self.dimension = dimension
|
| 23 |
+
self.index = faiss.IndexFlatL2(dimension)
|
| 24 |
+
self.documents = []
|
| 25 |
+
self.index_path = "data/faiss_index"
|
| 26 |
+
os.makedirs("data", exist_ok=True)
|
| 27 |
+
self.load_index()
|
| 28 |
+
|
| 29 |
+
def load_index(self):
|
| 30 |
+
if os.path.exists(self.index_path):
|
| 31 |
+
try:
|
| 32 |
+
self.index = faiss.read_index(self.index_path)
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"Error loading FAISS index: {e}")
|
| 35 |
+
|
| 36 |
+
def save_index(self):
|
| 37 |
+
try:
|
| 38 |
+
faiss.write_index(self.index, self.index_path)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Error saving FAISS index: {e}")
|
| 41 |
+
|
| 42 |
+
def add_documents(self, documents, embeddings):
|
| 43 |
+
self.index.add(np.array(embeddings))
|
| 44 |
+
self.documents.extend(documents)
|
| 45 |
+
self.save_index()
|
| 46 |
+
|
| 47 |
+
def search(self, query_vector, num_results=5):
|
| 48 |
+
if len(self.documents) == 0:
|
| 49 |
+
return []
|
| 50 |
+
D, I = self.index.search(np.array([query_vector]), num_results)
|
| 51 |
+
return [self.documents[i] for i in I[0]]
|
| 52 |
+
|
| 53 |
+
def get_vector_store(config):
|
| 54 |
+
"""Factory function to get the appropriate vector store"""
|
| 55 |
+
return FaissVectorStore # Always return FAISS vector store
|