Spaces:
Sleeping
Sleeping
Create database.py
Browse files- database.py +53 -0
database.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# database.py
|
| 2 |
+
import sqlite3
|
| 3 |
+
import json
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class DB:
|
| 8 |
+
def __init__(self, path="experiments.db"):
|
| 9 |
+
self.conn = sqlite3.connect(path, check_same_thread=False)
|
| 10 |
+
self._create()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _create(self):
|
| 14 |
+
cur = self.conn.cursor()
|
| 15 |
+
cur.execute("""
|
| 16 |
+
CREATE TABLE IF NOT EXISTS experiments (
|
| 17 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 18 |
+
prompt TEXT,
|
| 19 |
+
generated TEXT,
|
| 20 |
+
layer_scores TEXT,
|
| 21 |
+
created_at TEXT
|
| 22 |
+
)
|
| 23 |
+
""")
|
| 24 |
+
self.conn.commit()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def save_experiment(self, prompt, generated, layer_scores):
|
| 28 |
+
cur = self.conn.cursor()
|
| 29 |
+
cur.execute("INSERT INTO experiments (prompt, generated, layer_scores, created_at) VALUES (?, ?, ?, ?)",
|
| 30 |
+
(prompt, generated, json.dumps(layer_scores), datetime.utcnow().isoformat()))
|
| 31 |
+
self.conn.commit()
|
| 32 |
+
return cur.lastrowid
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def fetch_experiment(self, id):
|
| 36 |
+
cur = self.conn.cursor()
|
| 37 |
+
cur.execute("SELECT id, prompt, generated, layer_scores, created_at FROM experiments WHERE id = ?", (id,))
|
| 38 |
+
row = cur.fetchone()
|
| 39 |
+
if not row:
|
| 40 |
+
return None
|
| 41 |
+
return {
|
| 42 |
+
"id": row[0],
|
| 43 |
+
"prompt": row[1],
|
| 44 |
+
"generated": row[2],
|
| 45 |
+
"layer_scores": json.loads(row[3]),
|
| 46 |
+
"created_at": row[4]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def list_experiments(self, limit=50):
|
| 51 |
+
cur = self.conn.cursor()
|
| 52 |
+
cur.execute("SELECT id, prompt, created_at FROM experiments ORDER BY id DESC LIMIT ?", (limit,))
|
| 53 |
+
return cur.fetchall()
|