File size: 1,702 Bytes
e419ba3 ab0d85a e419ba3 | 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 | import os
import sqlite3
import logging
from pathlib import Path
log = logging.getLogger("db")
DB_PATH = os.environ.get("DB_PATH", "/data/bot.db")
def _ensure_dir():
p = Path(DB_PATH).parent
p.mkdir(parents=True, exist_ok=True)
def get_conn():
_ensure_dir()
conn = sqlite3.connect(DB_PATH, timeout=10, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA foreign_keys=ON;")
return conn
def init_db():
_ensure_dir()
schema_path = Path(__file__).parent / "schema.sql"
with open(schema_path, "r", encoding="utf-8") as f:
schema = f.read()
with get_conn() as conn:
conn.executescript(schema)
# seed default settings
with get_conn() as conn:
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("conversation_window", "6"),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("max_new_tokens", "1024"),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("temperature", "0.7"),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("top_p", "0.9"),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("system_prompt", "You are a helpful assistant."),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES (?, ?)",
("daily_turn_limit", "100"),
)
log.info(f"DB initialised at {DB_PATH}") |