Hfzune commited on
Commit
e419ba3
·
verified ·
1 Parent(s): 04c65a2

Create db/init.py

Browse files
Files changed (1) hide show
  1. db/init.py +58 -0
db/init.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sqlite3
3
+ import logging
4
+ from pathlib import Path
5
+
6
+ log = logging.getLogger("db")
7
+
8
+ DB_PATH = os.environ.get("DB_PATH", "/data/bot.db")
9
+
10
+
11
+ def _ensure_dir():
12
+ p = Path(DB_PATH).parent
13
+ p.mkdir(parents=True, exist_ok=True)
14
+
15
+
16
+ def get_conn():
17
+ _ensure_dir()
18
+ conn = sqlite3.connect(DB_PATH, timeout=10, check_same_thread=False)
19
+ conn.row_factory = sqlite3.Row
20
+ conn.execute("PRAGMA journal_mode=WAL;")
21
+ conn.execute("PRAGMA foreign_keys=ON;")
22
+ return conn
23
+
24
+
25
+ def init_db():
26
+ _ensure_dir()
27
+ schema_path = Path(__file__).parent / "schema.sql"
28
+ with open(schema_path, "r", encoding="utf-8") as f:
29
+ schema = f.read()
30
+ with get_conn() as conn:
31
+ conn.executescript(schema)
32
+ # seed default settings
33
+ with get_conn() as conn:
34
+ conn.execute(
35
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
36
+ ("conversation_window", "6"),
37
+ )
38
+ conn.execute(
39
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
40
+ ("max_new_tokens", "512"),
41
+ )
42
+ conn.execute(
43
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
44
+ ("temperature", "0.7"),
45
+ )
46
+ conn.execute(
47
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
48
+ ("top_p", "0.9"),
49
+ )
50
+ conn.execute(
51
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
52
+ ("system_prompt", "You are a helpful assistant."),
53
+ )
54
+ conn.execute(
55
+ "INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
56
+ ("daily_turn_limit", "100"),
57
+ )
58
+ log.info(f"DB initialised at {DB_PATH}")