suraj-ml-projects commited on
Commit
fb3231c
Β·
verified Β·
1 Parent(s): 186e3ff

Upload memory_py.py

Browse files
Files changed (1) hide show
  1. memory_py.py +324 -0
memory_py.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ core/memory.py
3
+ ==============
4
+ Intelligent session-scoped vector memory using FAISS + sentence-transformers.
5
+
6
+ Architecture:
7
+ - Each session gets an isolated MemoryStore instance.
8
+ - Memories are embedded with all-MiniLM-L6-v2 (22 MB, very fast).
9
+ - FAISS IndexFlatIP used for cosine similarity (inner product on L2-normalised vecs).
10
+ - Timeline index keeps ordered scene summaries for "last N minutes" queries.
11
+ - Everything lives in RAM β€” no disk DB β€” auto-wiped on session end.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ import uuid
18
+ import threading
19
+ from dataclasses import dataclass, field
20
+ from typing import List, Optional, Dict
21
+
22
+ import numpy as np
23
+ import faiss
24
+ from sentence_transformers import SentenceTransformer
25
+ from loguru import logger
26
+
27
+
28
+ # ── Lazy singleton embedder (shared across all sessions to save RAM) ─────────
29
+ _embedder: Optional[SentenceTransformer] = None
30
+ _embedder_lock = threading.Lock()
31
+
32
+ def get_embedder() -> SentenceTransformer:
33
+ global _embedder
34
+ if _embedder is None:
35
+ with _embedder_lock:
36
+ if _embedder is None:
37
+ logger.info("Loading sentence embedder (all-MiniLM-L6-v2)…")
38
+ _embedder = SentenceTransformer(
39
+ "sentence-transformers/all-MiniLM-L6-v2",
40
+ device="cpu", # keep GPU free for LLM/Whisper
41
+ )
42
+ return _embedder
43
+
44
+
45
+ # ── Memory unit ───────────────────────────────────────────────────────────────
46
+ @dataclass
47
+ class MemoryChunk:
48
+ chunk_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
49
+ timestamp_sec: float = 0.0 # video timestamp (seconds)
50
+ memory_type: str = "scene" # scene | dialogue | qa | emotion | character
51
+ content: str = "" # raw text stored
52
+ metadata: Dict = field(default_factory=dict)
53
+ created_at: float = field(default_factory=time.time)
54
+
55
+
56
+ # ── Per-session memory store ──────────────────────────────────────────────────
57
+ class MemoryStore:
58
+ """
59
+ Isolated vector store for one user session.
60
+ Thread-safe for concurrent Gradio callbacks.
61
+ """
62
+
63
+ EMBEDDING_DIM = 384 # all-MiniLM-L6-v2 output dimension
64
+
65
+ def __init__(self, session_id: str):
66
+ self.session_id = session_id
67
+ self._lock = threading.Lock()
68
+
69
+ # FAISS index β€” inner product (cosine on normalised vectors)
70
+ self._index = faiss.IndexFlatIP(self.EMBEDDING_DIM)
71
+ self._chunks: List[MemoryChunk] = [] # parallel list to index
72
+ self._timeline: List[MemoryChunk] = [] # ordered by timestamp
73
+
74
+ # Fast character / keyword lookup
75
+ self._character_map: Dict[str, List[MemoryChunk]] = {}
76
+ self._conversation_history: List[Dict] = [] # {role, content}
77
+
78
+ # Stats
79
+ self.total_chunks = 0
80
+ logger.info(f"MemoryStore created for session {session_id}")
81
+
82
+ # ── Embedding helper ──────────────────────────────────────────────────────
83
+ def _embed(self, texts: List[str]) -> np.ndarray:
84
+ emb = get_embedder().encode(
85
+ texts,
86
+ batch_size=32,
87
+ normalize_embeddings=True, # required for IP = cosine
88
+ show_progress_bar=False,
89
+ )
90
+ return emb.astype(np.float32)
91
+
92
+ # ── Add memory ────────────────────────────────────────────────────────────
93
+ def add(
94
+ self,
95
+ content: str,
96
+ timestamp_sec: float = 0.0,
97
+ memory_type: str = "scene",
98
+ metadata: Optional[Dict] = None,
99
+ ) -> MemoryChunk:
100
+ if not content.strip():
101
+ return None
102
+
103
+ chunk = MemoryChunk(
104
+ timestamp_sec=timestamp_sec,
105
+ memory_type=memory_type,
106
+ content=content,
107
+ metadata=metadata or {},
108
+ )
109
+
110
+ vec = self._embed([content]) # shape (1, 384)
111
+
112
+ with self._lock:
113
+ self._index.add(vec)
114
+ self._chunks.append(chunk)
115
+ self._timeline.append(chunk)
116
+ self._timeline.sort(key=lambda c: c.timestamp_sec)
117
+ self.total_chunks += 1
118
+
119
+ # Character index
120
+ char = (metadata or {}).get("character")
121
+ if char:
122
+ self._character_map.setdefault(char.lower(), []).append(chunk)
123
+
124
+ return chunk
125
+
126
+ def add_batch(self, items: List[Dict]) -> None:
127
+ """Batch insert for efficiency during video processing."""
128
+ if not items:
129
+ return
130
+ texts = [i["content"] for i in items]
131
+ vecs = self._embed(texts)
132
+
133
+ chunks = [
134
+ MemoryChunk(
135
+ timestamp_sec=i.get("timestamp_sec", 0.0),
136
+ memory_type=i.get("memory_type", "scene"),
137
+ content=i["content"],
138
+ metadata=i.get("metadata", {}),
139
+ )
140
+ for i in items
141
+ ]
142
+
143
+ with self._lock:
144
+ self._index.add(vecs)
145
+ self._chunks.extend(chunks)
146
+ self._timeline.extend(chunks)
147
+ self._timeline.sort(key=lambda c: c.timestamp_sec)
148
+ self.total_chunks += len(chunks)
149
+
150
+ for chunk in chunks:
151
+ char = chunk.metadata.get("character")
152
+ if char:
153
+ self._character_map.setdefault(char.lower(), []).append(chunk)
154
+
155
+ # ── Semantic search ───────────────────────────────────────────────────────
156
+ def search(
157
+ self,
158
+ query: str,
159
+ top_k: int = 5,
160
+ memory_type: Optional[str] = None,
161
+ min_score: float = 0.25,
162
+ ) -> List[MemoryChunk]:
163
+ if self._index.ntotal == 0:
164
+ return []
165
+
166
+ q_vec = self._embed([query])
167
+ k = min(top_k * 2, self._index.ntotal)
168
+ scores, indices = self._index.search(q_vec, k)
169
+
170
+ results = []
171
+ with self._lock:
172
+ for score, idx in zip(scores[0], indices[0]):
173
+ if idx < 0 or score < min_score:
174
+ continue
175
+ chunk = self._chunks[idx]
176
+ if memory_type and chunk.memory_type != memory_type:
177
+ continue
178
+ results.append(chunk)
179
+ if len(results) >= top_k:
180
+ break
181
+
182
+ return results
183
+
184
+ # ── Timeline retrieval ────────────────────────────────────────────────────
185
+ def get_timeline_range(
186
+ self, start_sec: float, end_sec: float
187
+ ) -> List[MemoryChunk]:
188
+ with self._lock:
189
+ return [
190
+ c for c in self._timeline
191
+ if start_sec <= c.timestamp_sec <= end_sec
192
+ ]
193
+
194
+ def get_last_n_minutes(self, minutes: int, video_duration_sec: float) -> List[MemoryChunk]:
195
+ end = video_duration_sec
196
+ start = max(0.0, end - minutes * 60)
197
+ return self.get_timeline_range(start, end)
198
+
199
+ def get_recent_scenes(self, n: int = 5) -> List[MemoryChunk]:
200
+ with self._lock:
201
+ return list(reversed(self._timeline[-n:]))
202
+
203
+ # ── Character search ──────────────────────────────────────────────────────
204
+ def get_character_memories(self, character_name: str) -> List[MemoryChunk]:
205
+ with self._lock:
206
+ return self._character_map.get(character_name.lower(), [])
207
+
208
+ # ── Conversation history ──────────────────────────────────────────────────
209
+ def add_conversation(self, role: str, content: str) -> None:
210
+ with self._lock:
211
+ self._conversation_history.append({
212
+ "role": role,
213
+ "content": content,
214
+ "ts": time.time(),
215
+ })
216
+ # Keep last 20 turns to avoid context bloat
217
+ if len(self._conversation_history) > 20:
218
+ self._conversation_history = self._conversation_history[-20:]
219
+
220
+ def get_conversation_history(self, last_n: int = 6) -> List[Dict]:
221
+ with self._lock:
222
+ return self._conversation_history[-last_n:]
223
+
224
+ # ── Context builder for LLM ───────────────────────────────────────────────
225
+ def build_context_for_query(self, query: str, video_duration_sec: float = 0.0) -> str:
226
+ """
227
+ Smart context assembly:
228
+ 1. Semantic top-5 results for the query
229
+ 2. Last 3 recent scenes (recency bias)
230
+ 3. De-duplicate
231
+ Returns a formatted string ready to inject into the LLM prompt.
232
+ """
233
+ semantic = self.search(query, top_k=5)
234
+ recent = self.get_recent_scenes(3)
235
+
236
+ seen = set()
237
+ combined = []
238
+ for chunk in semantic + recent:
239
+ if chunk.chunk_id not in seen:
240
+ seen.add(chunk.chunk_id)
241
+ combined.append(chunk)
242
+
243
+ if not combined:
244
+ return "No prior video context available."
245
+
246
+ lines = []
247
+ for c in combined:
248
+ ts = _fmt_time(c.timestamp_sec)
249
+ lines.append(f"[{ts}] ({c.memory_type}) {c.content}")
250
+
251
+ return "\n".join(lines)
252
+
253
+ # ── Stats ─────────────────────────────────────────────────────────────────
254
+ def stats(self) -> Dict:
255
+ with self._lock:
256
+ return {
257
+ "session_id": self.session_id,
258
+ "total_chunks": self.total_chunks,
259
+ "characters_tracked": len(self._character_map),
260
+ "conversation_turns": len(self._conversation_history),
261
+ "index_size": self._index.ntotal,
262
+ }
263
+
264
+ # ── Cleanup ───────────────────────────────────────────────────────────────
265
+ def clear(self) -> None:
266
+ with self._lock:
267
+ self._index.reset()
268
+ self._chunks.clear()
269
+ self._timeline.clear()
270
+ self._character_map.clear()
271
+ self._conversation_history.clear()
272
+ self.total_chunks = 0
273
+ logger.info(f"MemoryStore cleared for session {self.session_id}")
274
+
275
+
276
+ # ── Session registry ──────────────────────────────────────────────────────────
277
+ class SessionRegistry:
278
+ """Global registry β€” maps session_id β†’ MemoryStore. Auto-expires after timeout."""
279
+
280
+ def __init__(self, timeout_minutes: int = 60):
281
+ self._stores: Dict[str, MemoryStore] = {}
282
+ self._lock = threading.Lock()
283
+ self._timeout = timeout_minutes * 60
284
+
285
+ def get_or_create(self, session_id: str) -> MemoryStore:
286
+ with self._lock:
287
+ if session_id not in self._stores:
288
+ self._stores[session_id] = MemoryStore(session_id)
289
+ return self._stores[session_id]
290
+
291
+ def destroy(self, session_id: str) -> None:
292
+ with self._lock:
293
+ if session_id in self._stores:
294
+ self._stores[session_id].clear()
295
+ del self._stores[session_id]
296
+ logger.info(f"Session {session_id} destroyed")
297
+
298
+ def gc(self) -> None:
299
+ """Garbage-collect expired sessions."""
300
+ now = time.time()
301
+ with self._lock:
302
+ expired = [
303
+ sid for sid, store in self._stores.items()
304
+ if store._conversation_history and
305
+ now - store._conversation_history[-1]["ts"] > self._timeout
306
+ ]
307
+ for sid in expired:
308
+ self._stores[sid].clear()
309
+ del self._stores[sid]
310
+ logger.info(f"GC: expired session {sid}")
311
+
312
+
313
+ # ── Helpers ───────────────────────────────────────────────────────────────────
314
+ def _fmt_time(sec: float) -> str:
315
+ sec = int(sec)
316
+ h, rem = divmod(sec, 3600)
317
+ m, s = divmod(rem, 60)
318
+ if h:
319
+ return f"{h:02d}:{m:02d}:{s:02d}"
320
+ return f"{m:02d}:{s:02d}"
321
+
322
+
323
+ # ── Module-level registry ─────────────────────────────────────────────────────
324
+ registry = SessionRegistry(timeout_minutes=60)