Spaces:
Sleeping
Sleeping
Update memory_store.py
Browse files- memory_store.py +78 -60
memory_store.py
CHANGED
|
@@ -1,88 +1,106 @@
|
|
| 1 |
import os
|
| 2 |
-
import hashlib
|
| 3 |
import faiss
|
| 4 |
import pickle
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
-
import pandas as pd
|
| 7 |
from datetime import datetime
|
| 8 |
-
from datasets import Dataset
|
| 9 |
from huggingface_hub import HfApi
|
|
|
|
| 10 |
from sentence_transformers import SentenceTransformer
|
| 11 |
|
| 12 |
-
# === Paths
|
| 13 |
-
EMBED_DIM = 384
|
| 14 |
FAISS_PATH = "memory/faiss_index.bin"
|
| 15 |
-
|
| 16 |
DATASET_REPO = "abhidgp1978/agentchat_logs"
|
| 17 |
|
| 18 |
-
# ===
|
| 19 |
-
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 20 |
|
| 21 |
# === FAISS Setup ===
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
with open(HASH_STORE_PATH, "rb") as f:
|
| 25 |
-
hash_store = pickle.load(f)
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
faiss_index = faiss.read_index(FAISS_PATH)
|
| 30 |
print("β
FAISS index loaded from file.")
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
print("π Creating new empty FAISS index.")
|
| 37 |
-
faiss.write_index(faiss_index, FAISS_PATH)
|
| 38 |
|
| 39 |
-
# ===
|
| 40 |
-
def
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
combined = dataset
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
print("π‘ Duplicate entry detected β skipping FAISS update.")
|
| 65 |
-
return
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
except Exception as e:
|
| 77 |
-
print(f"β Failed to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
# === FAISS Search ===
|
| 80 |
-
def search_similar(profession, query, top_k=3):
|
| 81 |
try:
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
return I, D
|
| 86 |
except Exception as e:
|
| 87 |
-
print(f"β
|
| 88 |
-
return [], []
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import faiss
|
| 3 |
import pickle
|
| 4 |
+
import hashlib
|
| 5 |
import numpy as np
|
|
|
|
| 6 |
from datetime import datetime
|
|
|
|
| 7 |
from huggingface_hub import HfApi
|
| 8 |
+
from datasets import Dataset, DatasetDict, load_dataset
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
+
# === Paths ===
|
|
|
|
| 12 |
FAISS_PATH = "memory/faiss_index.bin"
|
| 13 |
+
HASH_PATH = "memory/faiss_hashes.pkl"
|
| 14 |
DATASET_REPO = "abhidgp1978/agentchat_logs"
|
| 15 |
|
| 16 |
+
# === Model ===
|
| 17 |
+
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 18 |
|
| 19 |
# === FAISS Setup ===
|
| 20 |
+
embedding_size = model.get_sentence_embedding_dimension()
|
| 21 |
+
faiss_index = faiss.IndexFlatL2(embedding_size)
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# === Hashing for deduplication ===
|
| 24 |
+
seen_hashes = set()
|
| 25 |
+
if os.path.exists(HASH_PATH):
|
| 26 |
+
try:
|
| 27 |
+
with open(HASH_PATH, "rb") as f:
|
| 28 |
+
seen_hashes = pickle.load(f)
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"β οΈ Failed to load hash cache: {e}")
|
| 31 |
+
seen_hashes = set()
|
| 32 |
+
|
| 33 |
+
# === Load FAISS index if exists ===
|
| 34 |
+
if os.path.exists(FAISS_PATH):
|
| 35 |
+
try:
|
| 36 |
faiss_index = faiss.read_index(FAISS_PATH)
|
| 37 |
print("β
FAISS index loaded from file.")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"β οΈ Failed to load FAISS index: {e}")
|
| 40 |
+
faiss_index = faiss.IndexFlatL2(embedding_size)
|
| 41 |
+
print("π Creating new empty FAISS index.")
|
| 42 |
+
else:
|
| 43 |
print("π Creating new empty FAISS index.")
|
|
|
|
| 44 |
|
| 45 |
+
# === Save FAISS index and hashes ===
|
| 46 |
+
def save_faiss_index():
|
| 47 |
+
faiss.write_index(faiss_index, FAISS_PATH)
|
| 48 |
+
with open(HASH_PATH, "wb") as f:
|
| 49 |
+
pickle.dump(seen_hashes, f)
|
| 50 |
+
print("β
Updated FAISS and saved to memory/faiss_index.bin")
|
| 51 |
|
| 52 |
+
# === Embedding and Search ===
|
| 53 |
+
def build_or_update_index(profession, query, answer):
|
| 54 |
+
full_text = f"[{profession}] {query} => {answer}"
|
| 55 |
+
embedding = model.encode(full_text)
|
| 56 |
+
h = hashlib.sha256(full_text.encode()).hexdigest()
|
|
|
|
| 57 |
|
| 58 |
+
if h not in seen_hashes:
|
| 59 |
+
seen_hashes.add(h)
|
| 60 |
+
faiss_index.add(np.array([embedding]).astype(np.float32))
|
| 61 |
+
save_faiss_index()
|
| 62 |
+
else:
|
| 63 |
+
print("π‘ Duplicate entry detected β skipping FAISS update.")
|
| 64 |
|
| 65 |
+
def search_similar(text, k=3):
|
| 66 |
+
embedding = model.encode(text)
|
| 67 |
+
if faiss_index.ntotal == 0:
|
| 68 |
+
return []
|
| 69 |
+
D, I = faiss_index.search(np.array([embedding]).astype(np.float32), k)
|
| 70 |
+
return I[0]
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
# === Logging to HF Dataset ===
|
| 73 |
+
def log_chat(query, answer):
|
| 74 |
+
timestamp = datetime.utcnow().isoformat()
|
| 75 |
+
row = {"query": query, "answer": answer, "timestamp": timestamp}
|
| 76 |
+
print(f"π Logging: {query} β {answer}")
|
| 77 |
|
| 78 |
+
# Try to load the dataset
|
| 79 |
+
try:
|
| 80 |
+
dataset = load_dataset(DATASET_REPO, split="train")
|
| 81 |
+
df = dataset.to_pandas()
|
| 82 |
+
df.loc[len(df)] = row
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"β οΈ Could not load existing dataset: {e}")
|
| 85 |
+
import pandas as pd
|
| 86 |
+
df = pd.DataFrame([row])
|
| 87 |
|
| 88 |
+
# Convert to Dataset
|
| 89 |
+
try:
|
| 90 |
+
updated_dataset = Dataset.from_pandas(df.reset_index(drop=True))
|
| 91 |
except Exception as e:
|
| 92 |
+
print(f"β Failed to convert DataFrame to Dataset: {e}")
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
# Push to Hugging Face Dataset repo
|
| 96 |
+
hf_token = os.getenv("agentchat_token")
|
| 97 |
+
if not hf_token:
|
| 98 |
+
print("β HF_TOKEN not found in environment. Skipping dataset push.")
|
| 99 |
+
return
|
| 100 |
|
|
|
|
|
|
|
| 101 |
try:
|
| 102 |
+
api = HfApi(token=hf_token)
|
| 103 |
+
DatasetDict({"train": updated_dataset}).push_to_hub(DATASET_REPO, token=hf_token)
|
| 104 |
+
print("β
Chat log pushed to Hugging Face Dataset")
|
|
|
|
| 105 |
except Exception as e:
|
| 106 |
+
print(f"β Failed to log chat: {e}")
|
|
|