abhidgp1978 commited on
Commit
bce4ee6
Β·
verified Β·
1 Parent(s): 43dbe1c

Update memory_store.py

Browse files
Files changed (1) hide show
  1. memory_store.py +40 -47
memory_store.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import json
3
  import hashlib
@@ -36,65 +37,57 @@ except Exception as e:
36
  faiss_index = faiss.IndexFlatL2(dimension)
37
  print("πŸ†• Creating new empty FAISS index.")
38
 
39
- # 🧠 Hash tracking for deduplication
40
- if os.path.exists(HASH_TRACK_PATH):
41
  with open(HASH_TRACK_PATH, "r") as f:
42
  existing_hashes = set(f.read().splitlines())
43
- else:
44
  existing_hashes = set()
45
 
46
- def compute_hash(profession, query, answer):
47
- content = f"{profession}|{query}|{answer}"
48
- return hashlib.sha256(content.encode()).hexdigest()
49
 
50
- def build_or_update_index(profession, query, answer):
51
- hash_value = compute_hash(profession, query, answer)
52
- if hash_value in existing_hashes:
 
 
 
 
53
  print("🟑 Duplicate entry detected β€” skipping FAISS update.")
54
  return
55
 
56
- vector = model.encode([f"{profession} {query} {answer}"])
57
- faiss_index.add(np.array(vector).astype("float32"))
58
-
59
- # Save index
60
- faiss.write_index(faiss_index, FAISS_PATH)
61
- print("βœ… Updated FAISS and saved to memory/faiss_index.bin")
62
-
63
- # Track hash
64
  with open(HASH_TRACK_PATH, "a") as f:
65
- f.write(hash_value + "\n")
66
- existing_hashes.add(hash_value)
67
-
68
- # Upload FAISS to HF Hub
69
  try:
70
- upload_file(
71
- path_or_fileobj=FAISS_PATH,
72
- path_in_repo="memory/faiss_index.bin",
73
- repo_id="abhidgp1978/agentchat",
74
- repo_type="space",
75
- token=HF_TOKEN
76
- )
77
- print("βœ… FAISS pushed to Hugging Face space repo.")
78
  except Exception as e:
79
- print(f"⚠️ Failed to push FAISS: {e}")
80
-
81
- def log_chat(query, answer):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  try:
83
- row = {"query": query, "answer": answer, "timestamp": datetime.utcnow().isoformat()}
84
- df = pd.DataFrame([row])
85
-
86
- # Load previous logs from dataset
87
- dataset = Dataset.from_pandas(df)
88
- dataset.push_to_hub(DATASET_REPO)
89
  print("βœ… Chat log pushed to Hugging Face Dataset")
90
  except Exception as e:
91
  print(f"❌ Failed to log chat: {e}")
92
-
93
- def search_similar(text, top_k=3):
94
- try:
95
- query_vector = model.encode([text])
96
- scores, indices = faiss_index.search(np.array(query_vector).astype("float32"), top_k)
97
- return indices[0], scores[0]
98
- except Exception as e:
99
- print(f"❌ FAISS search failed: {e}")
100
- return [], []
 
1
+
2
  import os
3
  import json
4
  import hashlib
 
37
  faiss_index = faiss.IndexFlatL2(dimension)
38
  print("πŸ†• Creating new empty FAISS index.")
39
 
40
+ # 🧠 Hash tracker
41
+ try:
42
  with open(HASH_TRACK_PATH, "r") as f:
43
  existing_hashes = set(f.read().splitlines())
44
+ except FileNotFoundError:
45
  existing_hashes = set()
46
 
47
+ def embed(text: str):
48
+ return model.encode([text])[0]
 
49
 
50
+ def hash_text(text: str):
51
+ return hashlib.sha256(text.encode()).hexdigest()
52
+
53
+ def build_or_update_index(query: str, role: str, answer: str):
54
+ combined = f"{role} | {query}"
55
+ query_hash = hash_text(combined)
56
+ if query_hash in existing_hashes:
57
  print("🟑 Duplicate entry detected β€” skipping FAISS update.")
58
  return
59
 
60
+ embedding = embed(combined).astype("float32")
61
+ faiss_index.add(np.array([embedding]))
 
 
 
 
 
 
62
  with open(HASH_TRACK_PATH, "a") as f:
63
+ f.write(query_hash + "\n")
 
 
 
64
  try:
65
+ faiss.write_index(faiss_index, FAISS_PATH)
66
+ print("βœ… Updated FAISS and saved to memory/faiss_index.bin")
67
+ if HF_TOKEN:
68
+ upload_file(path_or_fileobj=FAISS_PATH, path_in_repo=FAISS_PATH, repo_id=DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
69
+ upload_file(path_or_fileobj=HASH_TRACK_PATH, path_in_repo=HASH_TRACK_PATH, repo_id=DATASET_REPO, repo_type="dataset", token=HF_TOKEN)
 
 
 
70
  except Exception as e:
71
+ print(f"❌ Failed to push FAISS: {e}")
72
+
73
+ def search_similar(query: str, role: str, k=3):
74
+ combined = f"{role} | {query}"
75
+ embedding = embed(combined).astype("float32")
76
+ if faiss_index.ntotal == 0:
77
+ return []
78
+ _, indices = faiss_index.search(np.array([embedding]), k)
79
+ return indices[0].tolist()
80
+
81
+ def log_chat(role: str, query: str, answer: str):
82
+ entry = {
83
+ "timestamp": datetime.utcnow().isoformat(),
84
+ "role": role,
85
+ "query": query,
86
+ "answer": answer,
87
+ }
88
  try:
89
+ dataset = Dataset.from_list([entry])
90
+ dataset.push_to_hub(DATASET_REPO, token=HF_TOKEN)
 
 
 
 
91
  print("βœ… Chat log pushed to Hugging Face Dataset")
92
  except Exception as e:
93
  print(f"❌ Failed to log chat: {e}")