Spaces:
Sleeping
Sleeping
Update memory_store.py
Browse files- memory_store.py +79 -78
memory_store.py
CHANGED
|
@@ -1,106 +1,107 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import faiss
|
| 3 |
-
import pickle
|
| 4 |
import hashlib
|
| 5 |
-
import
|
| 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 |
-
#
|
| 12 |
-
FAISS_PATH = "memory/faiss_index.bin"
|
| 13 |
-
HASH_PATH = "memory/faiss_hashes.pkl"
|
| 14 |
DATASET_REPO = "abhidgp1978/agentchat_logs"
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
#
|
| 17 |
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 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 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
print("π Creating new empty FAISS index.")
|
| 42 |
-
else:
|
| 43 |
print("π Creating new empty FAISS index.")
|
|
|
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
-
# === Embedding and Search ===
|
| 53 |
def build_or_update_index(profession, query, answer):
|
| 54 |
-
full_text = f"
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
if
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
return []
|
| 69 |
-
D, I = faiss_index.search(np.array([embedding]).astype(np.float32), k)
|
| 70 |
-
return I[0]
|
| 71 |
|
| 72 |
-
#
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
row = {"query": query, "answer": answer, "timestamp": timestamp}
|
| 76 |
-
print(f"π Logging: {query} β {answer}")
|
| 77 |
|
| 78 |
-
|
| 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 |
-
#
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return
|
| 100 |
|
| 101 |
try:
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
print("β
Chat log pushed to Hugging Face Dataset")
|
| 105 |
except Exception as e:
|
| 106 |
print(f"β Failed to log chat: {e}")
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import faiss
|
|
|
|
| 4 |
import hashlib
|
| 5 |
+
import pandas as pd
|
| 6 |
from datetime import datetime
|
|
|
|
|
|
|
| 7 |
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from huggingface_hub import HfApi, upload_file
|
| 9 |
+
from datasets import Dataset
|
| 10 |
+
import numpy as np
|
| 11 |
|
| 12 |
+
# Constants
|
|
|
|
|
|
|
| 13 |
DATASET_REPO = "abhidgp1978/agentchat_logs"
|
| 14 |
+
FAISS_PATH = "memory/faiss_index.bin"
|
| 15 |
+
HASHES_FILE = "memory/faiss_hashes.json"
|
| 16 |
|
| 17 |
+
# Load model
|
| 18 |
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 19 |
|
| 20 |
+
# Initialize FAISS index
|
| 21 |
+
embedding_dim = 384
|
| 22 |
+
try:
|
| 23 |
+
if os.path.exists(FAISS_PATH):
|
| 24 |
+
print("β
Loading FAISS index from file.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
faiss_index = faiss.read_index(FAISS_PATH)
|
| 26 |
+
else:
|
| 27 |
+
raise FileNotFoundError("No existing FAISS index.")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"β οΈ Failed to load FAISS index: {e}")
|
|
|
|
|
|
|
| 30 |
print("π Creating new empty FAISS index.")
|
| 31 |
+
faiss_index = faiss.IndexFlatL2(embedding_dim)
|
| 32 |
|
| 33 |
+
# Load previously logged hashes to avoid duplicate FAISS entries
|
| 34 |
+
if os.path.exists(HASHES_FILE):
|
| 35 |
+
with open(HASHES_FILE, "r") as f:
|
| 36 |
+
hash_cache = set(json.load(f))
|
| 37 |
+
else:
|
| 38 |
+
hash_cache = set()
|
| 39 |
|
|
|
|
| 40 |
def build_or_update_index(profession, query, answer):
|
| 41 |
+
full_text = f"{profession.strip()} | {query.strip()} | {answer.strip()}"
|
| 42 |
+
emb = model.encode([full_text])
|
| 43 |
+
entry_hash = hashlib.md5(full_text.encode()).hexdigest()
|
| 44 |
|
| 45 |
+
if entry_hash in hash_cache:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
print("π‘ Duplicate entry detected β skipping FAISS update.")
|
| 47 |
+
return
|
| 48 |
|
| 49 |
+
faiss_index.add(np.array(emb).astype("float32"))
|
| 50 |
+
faiss.write_index(faiss_index, FAISS_PATH)
|
| 51 |
+
hash_cache.add(entry_hash)
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Save updated hash set
|
| 54 |
+
with open(HASHES_FILE, "w") as f:
|
| 55 |
+
json.dump(list(hash_cache), f)
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
print("β
Updated FAISS and saved to memory/faiss_index.bin")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
# Attempt to upload FAISS file
|
| 60 |
+
token = os.getenv("agentchat_token")
|
| 61 |
+
if token:
|
| 62 |
+
try:
|
| 63 |
+
upload_file(
|
| 64 |
+
path_or_fileobj=FAISS_PATH,
|
| 65 |
+
path_in_repo="memory/faiss_index.bin",
|
| 66 |
+
repo_id="abhidgp1978/agentchat",
|
| 67 |
+
repo_type="space",
|
| 68 |
+
token=token
|
| 69 |
+
)
|
| 70 |
+
print("β
FAISS pushed to Hugging Face space repo.")
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"β Failed to push FAISS to Hugging Face: {e}")
|
| 73 |
+
else:
|
| 74 |
+
print("β HF_TOKEN not set β skipping FAISS upload.")
|
| 75 |
|
| 76 |
+
def search_similar(text, k=5):
|
| 77 |
+
emb = model.encode([text])
|
| 78 |
+
D, I = faiss_index.search(np.array(emb).astype("float32"), k)
|
| 79 |
+
return D[0], I[0]
|
| 80 |
+
|
| 81 |
+
def log_chat(query, answer):
|
| 82 |
+
token = os.getenv("agentchat_token")
|
| 83 |
+
if not token:
|
| 84 |
+
print("β HF_TOKEN not set β cannot log to dataset.")
|
| 85 |
return
|
| 86 |
|
| 87 |
try:
|
| 88 |
+
from datasets import load_dataset
|
| 89 |
+
ds = load_dataset(DATASET_REPO, split="train")
|
| 90 |
+
df = ds.to_pandas()
|
| 91 |
+
except Exception:
|
| 92 |
+
df = pd.DataFrame(columns=["query", "answer", "timestamp"])
|
| 93 |
+
|
| 94 |
+
# Append new row
|
| 95 |
+
new_row = pd.DataFrame([{
|
| 96 |
+
"query": query,
|
| 97 |
+
"answer": answer,
|
| 98 |
+
"timestamp": datetime.utcnow().isoformat()
|
| 99 |
+
}])
|
| 100 |
+
|
| 101 |
+
df = pd.concat([df, new_row], ignore_index=True)
|
| 102 |
+
try:
|
| 103 |
+
updated_dataset = Dataset.from_pandas(df)
|
| 104 |
+
updated_dataset.push_to_hub(DATASET_REPO, token=token)
|
| 105 |
print("β
Chat log pushed to Hugging Face Dataset")
|
| 106 |
except Exception as e:
|
| 107 |
print(f"β Failed to log chat: {e}")
|