-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
282 lines (241 loc) · 7.43 KB
/
Copy pathmemory.py
File metadata and controls
282 lines (241 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
memory.py
SQLite-backed long-term memory for Otaku Concierge Pro.
Stores:
- user preferences
- watch history
- recommendation logs
"""
import os
import sqlite3
from datetime import datetime
from typing import Optional, Dict, Any, List
DB_PATH = os.environ.get("OTAKU_DB_PATH", "otaku_memory.db")
def get_conn() -> sqlite3.Connection:
"""Create and return a SQLite connection with row factory."""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db() -> Dict[str, Any]:
"""Initialise the SQLite database with all required tables."""
conn = get_conn()
cur = conn.cursor()
# User preferences
cur.execute(
"""
CREATE TABLE IF NOT EXISTS user_preferences (
user_id TEXT PRIMARY KEY,
fav_genres TEXT,
disliked_genres TEXT,
preferred_runtime TEXT,
last_updated TEXT
)
"""
)
# Watch history
cur.execute(
"""
CREATE TABLE IF NOT EXISTS watch_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
title TEXT,
kind TEXT,
genres TEXT,
imdb_rating REAL,
user_rating REAL,
watched_at TEXT
)
"""
)
# Recommendation log
cur.execute(
"""
CREATE TABLE IF NOT EXISTS recommendation_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT,
title TEXT,
kind TEXT,
imdb_rating REAL,
reason TEXT,
recommended_at TEXT
)
"""
)
conn.commit()
conn.close()
return {"status": "ok", "message": "Database initialised.", "db_path": DB_PATH}
def save_user_preferences(
user_id: str,
fav_genres: Optional[str] = None,
disliked_genres: Optional[str] = None,
preferred_runtime: Optional[str] = None,
) -> Dict[str, Any]:
"""
Insert/update user's taste preferences.
Genres and runtime are stored as simple strings (e.g. comma-separated).
"""
conn = get_conn()
cur = conn.cursor()
now = datetime.utcnow().isoformat()
cur.execute(
"""
INSERT INTO user_preferences (user_id, fav_genres, disliked_genres, preferred_runtime, last_updated)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
fav_genres = COALESCE(EXCLUDED.fav_genres, user_preferences.fav_genres),
disliked_genres = COALESCE(EXCLUDED.disliked_genres, user_preferences.disliked_genres),
preferred_runtime = COALESCE(EXCLUDED.preferred_runtime, user_preferences.preferred_runtime),
last_updated = EXCLUDED.last_updated
""",
(user_id, fav_genres, disliked_genres, preferred_runtime, now),
)
conn.commit()
conn.close()
return {
"status": "ok",
"user_id": user_id,
"fav_genres": fav_genres,
"disliked_genres": disliked_genres,
"preferred_runtime": preferred_runtime,
}
def load_user_preferences(user_id: str) -> Dict[str, Any]:
"""Return user preferences row if present."""
conn = get_conn()
cur = conn.cursor()
cur.execute(
"""
SELECT user_id, fav_genres, disliked_genres, preferred_runtime, last_updated
FROM user_preferences
WHERE user_id = ?
""",
(user_id,),
)
row = cur.fetchone()
conn.close()
if not row:
return {
"found": False,
"user_id": user_id,
"fav_genres": "",
"disliked_genres": "",
"preferred_runtime": "",
}
return {
"found": True,
"user_id": row["user_id"],
"fav_genres": row["fav_genres"] or "",
"disliked_genres": row["disliked_genres"] or "",
"preferred_runtime": row["preferred_runtime"] or "",
"last_updated": row["last_updated"],
}
def log_watch_event(
user_id: str,
title: str,
kind: str,
genres: Optional[str] = None,
imdb_rating: Optional[float] = None,
user_rating: Optional[float] = None,
) -> Dict[str, Any]:
"""Insert a watch event into history."""
conn = get_conn()
cur = conn.cursor()
cur.execute(
"""
INSERT INTO watch_history (user_id, title, kind, genres, imdb_rating, user_rating, watched_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
user_id,
title,
kind,
genres,
imdb_rating,
user_rating,
datetime.utcnow().isoformat(),
),
)
conn.commit()
conn.close()
return {"status": "ok", "user_id": user_id, "title": title}
def log_recommendation(
user_id: str,
title: str,
kind: str,
imdb_rating: Optional[float],
reason: str,
) -> Dict[str, Any]:
"""Store a recommended title & reason."""
conn = get_conn()
cur = conn.cursor()
cur.execute(
"""
INSERT INTO recommendation_log (user_id, title, kind, imdb_rating, reason, recommended_at)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
user_id,
title,
kind,
imdb_rating,
reason,
datetime.utcnow().isoformat(),
),
)
conn.commit()
conn.close()
return {
"status": "ok",
"user_id": user_id,
"title": title,
"imdb_rating": imdb_rating,
}
def get_recent_watch_history(user_id: str, limit: int = 10) -> List[Dict[str, Any]]:
"""Return up to `limit` recent watch events."""
conn = get_conn()
cur = conn.cursor()
cur.execute(
"""
SELECT title, kind, genres, imdb_rating, user_rating, watched_at
FROM watch_history
WHERE user_id = ?
ORDER BY watched_at DESC
LIMIT ?
""",
(user_id, limit),
)
rows = cur.fetchall()
conn.close()
result: List[Dict[str, Any]] = []
for r in rows:
result.append(
{
"title": r["title"],
"kind": r["kind"],
"genres": r["genres"],
"imdb_rating": r["imdb_rating"],
"user_rating": r["user_rating"],
"watched_at": r["watched_at"],
}
)
return result
def get_taste_summary(user_id: str) -> Dict[str, Any]:
"""Produce a compact natural language summary of taste."""
prefs = load_user_preferences(user_id)
history = get_recent_watch_history(user_id, limit=8)
lines = []
lines.append(f"User ID: {user_id}")
lines.append(f"Favourite genres: {prefs.get('fav_genres') or 'not specified'}")
lines.append(f"Disliked genres: {prefs.get('disliked_genres') or 'not specified'}")
lines.append(
f"Preferred runtime: {prefs.get('preferred_runtime') or 'not specified'}"
)
lines.append("")
lines.append("Recent watch history:")
if not history:
lines.append("- None yet")
else:
for h in history:
lines.append(
f"- {h['title']} ({h['kind']}) | genres={h['genres']} | imdb={h['imdb_rating']} | user_rating={h['user_rating']}"
)
return {"status": "ok", "summary": "\n".join(lines)}