Hfzune commited on
Commit
1c47d23
·
verified ·
1 Parent(s): 649a2e8

Update db/models.py

Browse files
Files changed (1) hide show
  1. db/models.py +372 -83
db/models.py CHANGED
@@ -1,17 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ============================================================
2
- # ARCHIVE — one .md file per session, at /data/chat_logs/{user_id}/{timestamp}.md
3
- # A session starts on the first message after boot OR after /reset.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  # ============================================================
5
  import os
6
- import threading
7
- from pathlib import Path
8
- from datetime import datetime, timezone
9
 
10
  ARCHIVE_DIR = os.environ.get("ARCHIVE_DIR", "/data/chat_logs")
11
 
12
- # In-memory map: user_id -> Path of current session file
13
- _session_files: dict = {}
14
- _session_lock = threading.Lock()
15
 
16
 
17
  def _user_dir(user_id: int) -> Path:
@@ -21,106 +308,106 @@ def _user_dir(user_id: int) -> Path:
21
 
22
 
23
  def _new_session_path(user_id: int) -> Path:
24
- """Create a fresh timestamped markdown file for a new session."""
25
  d = _user_dir(user_id)
26
- ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
27
- # Collision guard (two messages in same second)
28
- p = d / f"{ts}.md"
29
- counter = 1
 
30
  while p.exists():
31
- p = d / f"{ts}_{counter}.md"
32
- counter += 1
33
- p.write_text(
34
- f"# Transcript — user {user_id}\n\n"
35
- f"_Session started: {datetime.now(timezone.utc).isoformat()}_\n\n---\n\n",
36
- encoding="utf-8",
37
- )
38
  return p
39
 
40
 
41
- def _current_session_file(user_id: int) -> Path:
42
- """Return the current session file for this user, creating one if needed."""
43
- with _session_lock:
44
- p = _session_files.get(user_id)
45
- if p is None or not p.exists():
46
- p = _new_session_path(user_id)
47
- _session_files[user_id] = p
48
- return p
49
-
50
-
51
- def archive_start_new_session(user_id: int) -> Path:
52
- """Force a new session file. Called on /reset."""
53
- with _session_lock:
54
  p = _new_session_path(user_id)
55
- _session_files[user_id] = p
56
- return p
57
-
 
 
 
 
58
 
59
- def archive_append(user_id: int, role: str, content: str,
60
- timestamp: str = None, latency_ms: int = None):
61
- """Append a message to the user's *current* session file."""
62
- p = _current_session_file(user_id)
63
- ts = timestamp or now_iso()
64
  header = "🧑 **User**" if role == "user" else "🤖 **Assistant**"
65
-
66
  with p.open("a", encoding="utf-8") as f:
67
- f.write(f"### {header} — `{ts}`\n\n")
68
  if role == "assistant" and latency_ms is not None:
69
  f.write(f"_(latency: {latency_ms} ms)_\n\n")
70
  f.write(content.strip() + "\n\n")
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
73
  def archive_list(user_id: int = None):
74
  """
75
- List session files.
76
- If user_id is given: only that user's sessions.
77
- If None: all users' sessions.
78
- Returns list of dicts: {user_id, session, path, size, modified, started}
79
  """
80
- base = Path(ARCHIVE_DIR)
81
- if not base.exists():
82
  return []
83
 
84
  out = []
85
- user_dirs = [base / str(user_id)] if user_id else [d for d in base.iterdir() if d.is_dir()]
86
- for ud in user_dirs:
87
- if not ud.exists():
88
  continue
89
  try:
90
- uid = int(ud.name)
91
  except ValueError:
92
  continue
93
- for f in sorted(ud.glob("*.md"), reverse=True):
94
  stat = f.stat()
95
  out.append({
96
  "user_id": uid,
97
- "session": f.stem,
98
  "path": str(f),
99
  "size": stat.st_size,
100
- "modified": datetime.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(),
101
- "started": f.stem.split("_")[0:2] and f.stem, # just the stem
102
  })
103
  return out
104
 
105
 
106
- def archive_read(user_id: int, session: str) -> str:
107
- """Read one specific session file."""
108
- p = Path(ARCHIVE_DIR) / str(user_id) / f"{session}.md"
109
  if not p.exists():
110
  return ""
111
  return p.read_text(encoding="utf-8")
112
 
113
 
114
- def archive_delete_session(user_id: int, session: str) -> bool:
115
- p = Path(ARCHIVE_DIR) / str(user_id) / f"{session}.md"
116
  if p.exists():
117
  p.unlink()
 
 
 
118
  return True
119
  return False
120
 
121
 
122
  def archive_delete_user(user_id: int) -> int:
123
- """Delete all session files for one user. Returns count deleted."""
124
  d = Path(ARCHIVE_DIR) / str(user_id)
125
  if not d.exists():
126
  return 0
@@ -128,31 +415,33 @@ def archive_delete_user(user_id: int) -> int:
128
  for f in d.glob("*.md"):
129
  f.unlink()
130
  n += 1
131
- try:
132
- d.rmdir()
133
- except OSError:
134
- pass
135
- with _session_lock:
136
- _session_files.pop(user_id, None)
137
  return n
138
 
139
 
140
- def archive_delete_all() -> int:
141
- """Delete all session files for all users."""
142
- base = Path(ARCHIVE_DIR)
143
- if not base.exists():
144
  return 0
145
  n = 0
146
- for ud in base.iterdir():
147
- if not ud.is_dir():
148
  continue
149
- for f in ud.glob("*.md"):
150
  f.unlink()
151
  n += 1
152
- try:
153
- ud.rmdir()
154
- except OSError:
155
- pass
156
- with _session_lock:
157
- _session_files.clear()
158
- return n
 
 
 
 
 
 
 
 
1
+ import json
2
+ import secrets
3
+ import sqlite3
4
+ import logging
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+
8
+ from db.init import get_conn
9
+
10
+ log = logging.getLogger("db.models")
11
+
12
+
13
+ def now_iso():
14
+ return datetime.now(timezone.utc).isoformat()
15
+
16
+
17
  # ============================================================
18
+ # USERS
19
+ # ============================================================
20
+ def get_user(user_id: int):
21
+ with get_conn() as conn:
22
+ row = conn.execute(
23
+ "SELECT * FROM users WHERE user_id = ?", (user_id,)
24
+ ).fetchone()
25
+ return dict(row) if row else None
26
+
27
+
28
+ def upsert_user(user_id: int, username: str = None, first_name: str = None):
29
+ with get_conn() as conn:
30
+ existing = conn.execute(
31
+ "SELECT user_id FROM users WHERE user_id = ?", (user_id,)
32
+ ).fetchone()
33
+ if existing:
34
+ conn.execute(
35
+ "UPDATE users SET username=?, first_name=?, last_seen=? WHERE user_id=?",
36
+ (username, first_name, now_iso(), user_id),
37
+ )
38
+ else:
39
+ conn.execute(
40
+ """INSERT INTO users(user_id, username, first_name, created_at, last_seen)
41
+ VALUES (?, ?, ?, ?, ?)""",
42
+ (user_id, username, first_name, now_iso(), now_iso()),
43
+ )
44
+
45
+
46
+ def bind_token(user_id: int, token: str) -> bool:
47
+ with get_conn() as conn:
48
+ row = conn.execute(
49
+ "SELECT * FROM tokens WHERE token = ?", (token,)
50
+ ).fetchone()
51
+ if not row:
52
+ return False
53
+ if not row["is_active"]:
54
+ return False
55
+ if row["assigned_to"] not in (None, user_id):
56
+ return False
57
+
58
+ conn.execute(
59
+ "UPDATE tokens SET assigned_to=? WHERE token=?", (user_id, token)
60
+ )
61
+ conn.execute(
62
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
63
+ (token, user_id),
64
+ )
65
+ return True
66
+
67
+
68
+ def user_has_valid_token(user_id: int) -> bool:
69
+ with get_conn() as conn:
70
+ row = conn.execute(
71
+ """SELECT u.is_active AS u_active, t.is_active AS t_active
72
+ FROM users u LEFT JOIN tokens t ON u.token = t.token
73
+ WHERE u.user_id = ?""",
74
+ (user_id,),
75
+ ).fetchone()
76
+ if not row:
77
+ return False
78
+ return bool(row["u_active"]) and bool(row["t_active"])
79
+
80
+
81
+ def revoke_user(user_id: int):
82
+ with get_conn() as conn:
83
+ conn.execute("UPDATE users SET is_active=0 WHERE user_id=?", (user_id,))
84
+ conn.execute(
85
+ "UPDATE tokens SET is_active=0 WHERE assigned_to=?", (user_id,)
86
+ )
87
+
88
+
89
+ def delete_user(user_id: int):
90
+ with get_conn() as conn:
91
+ conn.execute("DELETE FROM conversations WHERE user_id=?", (user_id,))
92
+ conn.execute("DELETE FROM users WHERE user_id=?", (user_id,))
93
+ conn.execute(
94
+ "UPDATE tokens SET assigned_to=NULL, is_active=0 WHERE assigned_to=?",
95
+ (user_id,),
96
+ )
97
+
98
+
99
+ def increment_user_turns(user_id: int):
100
+ with get_conn() as conn:
101
+ conn.execute(
102
+ "UPDATE users SET total_turns = total_turns + 1 WHERE user_id=?",
103
+ (user_id,),
104
+ )
105
+
106
+
107
+ # ============================================================
108
+ # TOKENS
109
+ # ============================================================
110
+ def generate_token(assigned_to: int = None) -> str:
111
+ tok = secrets.token_urlsafe(24)
112
+ with get_conn() as conn:
113
+ conn.execute(
114
+ """INSERT INTO tokens(token, assigned_to, created_at)
115
+ VALUES (?, ?, ?)""",
116
+ (tok, assigned_to, now_iso()),
117
+ )
118
+ if assigned_to is not None:
119
+ conn.execute(
120
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
121
+ (tok, assigned_to),
122
+ )
123
+ return tok
124
+
125
+
126
+ def list_tokens():
127
+ with get_conn() as conn:
128
+ rows = conn.execute(
129
+ "SELECT * FROM tokens ORDER BY created_at DESC"
130
+ ).fetchall()
131
+ return [dict(r) for r in rows]
132
+
133
+
134
+ def revoke_token(token: str):
135
+ with get_conn() as conn:
136
+ conn.execute("UPDATE tokens SET is_active=0 WHERE token=?", (token,))
137
+ conn.execute(
138
+ "UPDATE users SET is_active=0 WHERE token=?", (token,)
139
+ )
140
+
141
+
142
+ def reassign_token(token: str, new_user_id: int):
143
+ with get_conn() as conn:
144
+ conn.execute(
145
+ "UPDATE tokens SET assigned_to=? WHERE token=?", (new_user_id, token)
146
+ )
147
+ conn.execute(
148
+ "UPDATE users SET token=?, is_active=1 WHERE user_id=?",
149
+ (token, new_user_id),
150
+ )
151
+
152
+
153
+ def bump_token_use(token: str):
154
+ with get_conn() as conn:
155
+ conn.execute(
156
+ """UPDATE tokens SET turns_used = turns_used + 1,
157
+ last_used = ?
158
+ WHERE token = ?""",
159
+ (now_iso(), token),
160
+ )
161
+
162
+
163
+ # ============================================================
164
+ # CONVERSATIONS (live context only — cleared by /reset)
165
+ # ============================================================
166
+ def add_message(user_id: int, role: str, content: str,
167
+ latency_ms: int = None, gpu_time_ms: int = None):
168
+ with get_conn() as conn:
169
+ conn.execute(
170
+ """INSERT INTO conversations
171
+ (user_id, role, content, timestamp, latency_ms, gpu_time_ms)
172
+ VALUES (?, ?, ?, ?, ?, ?)""",
173
+ (user_id, role, content, now_iso(), latency_ms, gpu_time_ms),
174
+ )
175
+
176
+
177
+ def get_history(user_id: int, limit_turns: int = 6):
178
+ """Return last N turns (2*N messages) in chronological order."""
179
+ with get_conn() as conn:
180
+ rows = conn.execute(
181
+ """SELECT role, content FROM conversations
182
+ WHERE user_id = ?
183
+ ORDER BY id DESC LIMIT ?""",
184
+ (user_id, limit_turns * 2),
185
+ ).fetchall()
186
+ rows = list(reversed(rows))
187
+ return [{"role": r["role"], "content": r["content"]} for r in rows]
188
+
189
+
190
+ def clear_history(user_id: int):
191
+ with get_conn() as conn:
192
+ conn.execute("DELETE FROM conversations WHERE user_id=?", (user_id,))
193
+
194
+
195
+ def list_users():
196
+ with get_conn() as conn:
197
+ rows = conn.execute(
198
+ "SELECT * FROM users ORDER BY created_at DESC"
199
+ ).fetchall()
200
+ return [dict(r) for r in rows]
201
+
202
+
203
+ def list_conversations(user_id: int = None, limit: int = 500):
204
+ with get_conn() as conn:
205
+ if user_id:
206
+ rows = conn.execute(
207
+ """SELECT * FROM conversations WHERE user_id=?
208
+ ORDER BY id DESC LIMIT ?""",
209
+ (user_id, limit),
210
+ ).fetchall()
211
+ else:
212
+ rows = conn.execute(
213
+ "SELECT * FROM conversations ORDER BY id DESC LIMIT ?",
214
+ (limit,),
215
+ ).fetchall()
216
+ return [dict(r) for r in rows]
217
+
218
+
219
+ def stats():
220
+ with get_conn() as conn:
221
+ total_users = conn.execute("SELECT COUNT(*) c FROM users").fetchone()["c"]
222
+ active_users = conn.execute(
223
+ "SELECT COUNT(*) c FROM users WHERE is_active=1"
224
+ ).fetchone()["c"]
225
+ total_msgs = conn.execute(
226
+ "SELECT COUNT(*) c FROM conversations"
227
+ ).fetchone()["c"]
228
+ today = datetime.now(timezone.utc).date().isoformat()
229
+ today_msgs = conn.execute(
230
+ "SELECT COUNT(*) c FROM conversations WHERE timestamp LIKE ?",
231
+ (today + "%",),
232
+ ).fetchone()["c"]
233
+ return {
234
+ "total_users": total_users,
235
+ "active_users": active_users,
236
+ "total_messages": total_msgs,
237
+ "messages_today": today_msgs,
238
+ }
239
+
240
+
241
+ # ============================================================
242
+ # SETTINGS
243
+ # ============================================================
244
+ def get_setting(key: str, default=None):
245
+ with get_conn() as conn:
246
+ row = conn.execute(
247
+ "SELECT value FROM settings WHERE key=?", (key,)
248
+ ).fetchone()
249
+ return row["value"] if row else default
250
+
251
+
252
+ def set_setting(key: str, value: str):
253
+ with get_conn() as conn:
254
+ conn.execute(
255
+ "INSERT INTO settings(key, value) VALUES (?, ?) "
256
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
257
+ (key, str(value)),
258
+ )
259
+
260
+
261
+ def all_settings():
262
+ with get_conn() as conn:
263
+ rows = conn.execute("SELECT key, value FROM settings").fetchall()
264
+ return {r["key"]: r["value"] for r in rows}
265
+
266
+
267
+ # ============================================================
268
+ # GPU LOG
269
+ # ============================================================
270
+ def log_gpu(user_id: int, duration_ms: int, status: str):
271
+ with get_conn() as conn:
272
+ conn.execute(
273
+ """INSERT INTO gpu_log(user_id, timestamp, duration_ms, status)
274
+ VALUES (?, ?, ?, ?)""",
275
+ (user_id, now_iso(), duration_ms, status),
276
+ )
277
+
278
+
279
+ def recent_gpu_log(limit: int = 50):
280
+ with get_conn() as conn:
281
+ rows = conn.execute(
282
+ "SELECT * FROM gpu_log ORDER BY id DESC LIMIT ?", (limit,)
283
+ ).fetchall()
284
+ return [dict(r) for r in rows]
285
+
286
+
287
+ # ============================================================
288
+ # ARCHIVE — one markdown file PER SESSION
289
+ # Path: /data/chat_logs/{user_id}/{timestamp}.md
290
+ # A new session starts whenever the previous one was closed by /reset
291
+ # (or when the user hasn't chatted before).
292
  # ============================================================
293
  import os
294
+ import re
295
+ from datetime import datetime as _dt
 
296
 
297
  ARCHIVE_DIR = os.environ.get("ARCHIVE_DIR", "/data/chat_logs")
298
 
299
+ # In-process tracker: user_id -> Path of the currently-open session file.
300
+ # Reset when /reset is called, so the next message opens a fresh file.
301
+ _active_session = {}
302
 
303
 
304
  def _user_dir(user_id: int) -> Path:
 
308
 
309
 
310
  def _new_session_path(user_id: int) -> Path:
311
+ """Generate a fresh session file path with a UTC timestamp."""
312
  d = _user_dir(user_id)
313
+ stamp = _dt.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
314
+ p = d / f"{stamp}.md"
315
+ # Extremely unlikely, but avoid clobbering if two messages land in the
316
+ # same second.
317
+ n = 1
318
  while p.exists():
319
+ p = d / f"{stamp}_{n}.md"
320
+ n += 1
 
 
 
 
 
321
  return p
322
 
323
 
324
+ def archive_append(user_id: int, role: str, content: str,
325
+ latency_ms: int = None):
326
+ """
327
+ Append a message to the user's *current* session markdown file.
328
+ If no session is open, start a new one.
329
+ """
330
+ p = _active_session.get(user_id)
331
+ if p is None or not p.exists():
 
 
 
 
 
332
  p = _new_session_path(user_id)
333
+ _active_session[user_id] = p
334
+ # Write the file header
335
+ p.write_text(
336
+ f"# Transcript — user {user_id}\n\n"
337
+ f"_Session started: {now_iso()}_\n\n---\n\n",
338
+ encoding="utf-8",
339
+ )
340
 
 
 
 
 
 
341
  header = "🧑 **User**" if role == "user" else "🤖 **Assistant**"
 
342
  with p.open("a", encoding="utf-8") as f:
343
+ f.write(f"### {header} — `{now_iso()}`\n\n")
344
  if role == "assistant" and latency_ms is not None:
345
  f.write(f"_(latency: {latency_ms} ms)_\n\n")
346
  f.write(content.strip() + "\n\n")
347
 
348
 
349
+ def archive_close_session(user_id: int):
350
+ """
351
+ Close the current session. The next message will open a new file.
352
+ Called by /reset.
353
+ """
354
+ p = _active_session.pop(user_id, None)
355
+ if p and p.exists():
356
+ with p.open("a", encoding="utf-8") as f:
357
+ f.write(f"\n---\n\n_Session closed: {now_iso()}_\n")
358
+
359
+
360
  def archive_list(user_id: int = None):
361
  """
362
+ List archived session files.
363
+ If user_id is None, list all users' files.
364
+ Returns list of dicts: {user_id, filename, path, size, modified}
 
365
  """
366
+ root = Path(ARCHIVE_DIR)
367
+ if not root.exists():
368
  return []
369
 
370
  out = []
371
+ user_dirs = [root / str(user_id)] if user_id else [d for d in root.iterdir() if d.is_dir()]
372
+ for d in user_dirs:
373
+ if not d.exists():
374
  continue
375
  try:
376
+ uid = int(d.name)
377
  except ValueError:
378
  continue
379
+ for f in sorted(d.glob("*.md"), reverse=True):
380
  stat = f.stat()
381
  out.append({
382
  "user_id": uid,
383
+ "filename": f.name,
384
  "path": str(f),
385
  "size": stat.st_size,
386
+ "modified": _dt.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(),
 
387
  })
388
  return out
389
 
390
 
391
+ def archive_read(user_id: int, filename: str) -> str:
392
+ p = Path(ARCHIVE_DIR) / str(user_id) / filename
 
393
  if not p.exists():
394
  return ""
395
  return p.read_text(encoding="utf-8")
396
 
397
 
398
+ def archive_delete(user_id: int, filename: str) -> bool:
399
+ p = Path(ARCHIVE_DIR) / str(user_id) / filename
400
  if p.exists():
401
  p.unlink()
402
+ # Close in-process session if we just deleted the active file
403
+ if _active_session.get(user_id) == p:
404
+ _active_session.pop(user_id, None)
405
  return True
406
  return False
407
 
408
 
409
  def archive_delete_user(user_id: int) -> int:
410
+ """Delete ALL session files for one user. Returns count deleted."""
411
  d = Path(ARCHIVE_DIR) / str(user_id)
412
  if not d.exists():
413
  return 0
 
415
  for f in d.glob("*.md"):
416
  f.unlink()
417
  n += 1
418
+ _active_session.pop(user_id, None)
 
 
 
 
 
419
  return n
420
 
421
 
422
+ def archive_delete_all():
423
+ """Delete every transcript for every user. Returns count deleted."""
424
+ root = Path(ARCHIVE_DIR)
425
+ if not root.exists():
426
  return 0
427
  n = 0
428
+ for d in root.iterdir():
429
+ if not d.is_dir():
430
  continue
431
+ for f in d.glob("*.md"):
432
  f.unlink()
433
  n += 1
434
+ _active_session.clear()
435
+ return n
436
+
437
+
438
+ def archive_export_user(user_id: int) -> str:
439
+ """Concatenate all of a user's sessions into one big markdown blob."""
440
+ sessions = archive_list(user_id)
441
+ # Oldest first
442
+ sessions = sorted(sessions, key=lambda x: x["filename"])
443
+ parts = [f"# Full transcript — user {user_id}\n"]
444
+ for s in sessions:
445
+ parts.append(f"\n\n## Session: {s['filename']}\n")
446
+ parts.append(archive_read(user_id, s["filename"]))
447
+ return "".join(parts)