rui3000 commited on
Commit
a556cd0
·
verified ·
1 Parent(s): 1f2c2f6

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +88 -73
db.py CHANGED
@@ -1,89 +1,104 @@
1
- import gradio as gr
2
- import torch
3
- import time
4
- import spaces
5
  import sqlite3
6
  import os
7
- import json
8
- from transformers import AutoModelForCausalLM, AutoTokenizer
9
 
10
- # --- Database Setup ---
11
- # Use the persistent storage location in Hugging Face Spaces
12
- DB_PATH = os.path.join("/data", "model_tests.db")
13
 
14
  def init_db():
15
  """Initialize the SQLite database with required tables if they don't exist"""
16
- with sqlite3.connect(DB_PATH) as conn:
17
- cursor = conn.cursor()
18
-
19
- # Create table for model inputs and outputs
20
- cursor.execute('''
21
- CREATE TABLE IF NOT EXISTS model_tests (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- analysis_mode TEXT NOT NULL,
24
- system_prompt TEXT NOT NULL,
25
- input_content TEXT,
26
- model_response TEXT NOT NULL,
27
- generation_time REAL NOT NULL,
28
- tokens_generated INTEGER NOT NULL,
29
- temperature REAL NOT NULL,
30
- top_p REAL NOT NULL,
31
- max_length INTEGER NOT NULL,
32
- timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
33
- )
34
- ''')
35
 
36
- conn.commit()
37
- print("Test database initialized successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Initialize the database when the app starts
40
- init_db()
41
-
42
- # Function to save test results
43
  def save_test_result(analysis_mode, system_prompt, input_content, model_response,
44
  generation_time, tokens_generated, temperature, top_p, max_length):
45
- with sqlite3.connect(DB_PATH) as conn:
46
- cursor = conn.cursor()
 
47
 
48
- cursor.execute('''
49
- INSERT INTO model_tests
50
- (analysis_mode, system_prompt, input_content, model_response,
51
- generation_time, tokens_generated, temperature, top_p, max_length)
52
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
53
- ''', (analysis_mode, system_prompt, input_content, model_response,
54
- generation_time, tokens_generated, temperature, top_p, max_length))
 
 
 
 
 
 
55
 
56
- test_id = cursor.lastrowid
57
- conn.commit()
58
-
59
- return test_id
60
 
61
- # Function to retrieve test history
62
  def get_test_history(limit=10):
63
- with sqlite3.connect(DB_PATH) as conn:
64
- cursor = conn.cursor()
65
- cursor.execute('''
66
- SELECT id, analysis_mode, timestamp, generation_time, tokens_generated
67
- FROM model_tests
68
- ORDER BY id DESC LIMIT ?
69
- ''', (limit,))
70
- history = cursor.fetchall()
71
-
72
- return history
 
 
 
 
 
73
 
74
- # Function to get test details by ID
75
  def get_test_details(test_id):
76
- with sqlite3.connect(DB_PATH) as conn:
77
- cursor = conn.cursor()
78
- cursor.execute('''
79
- SELECT * FROM model_tests WHERE id = ?
80
- ''', (test_id,))
81
- test = cursor.fetchone()
82
-
83
- if test:
84
- # Convert to dictionary
85
- columns = [col[0] for col in cursor.description]
86
- test_dict = {columns[i]: test[i] for i in range(len(columns))}
87
- return test_dict
88
- else:
89
- return None
 
 
 
 
 
 
 
 
 
 
1
  import sqlite3
2
  import os
3
+ import time
 
4
 
5
+ # Use the current directory instead of /data
6
+ DB_NAME = "model_tests.db"
7
+ DB_PATH = os.path.join(".", DB_NAME)
8
 
9
  def init_db():
10
  """Initialize the SQLite database with required tables if they don't exist"""
11
+ try:
12
+ print(f"Initializing database at {DB_PATH}")
13
+ # Ensure the directory exists
14
+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ with sqlite3.connect(DB_PATH) as conn:
17
+ cursor = conn.cursor()
18
+
19
+ # Create table for model inputs and outputs
20
+ cursor.execute('''
21
+ CREATE TABLE IF NOT EXISTS model_tests (
22
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
23
+ analysis_mode TEXT NOT NULL,
24
+ system_prompt TEXT NOT NULL,
25
+ input_content TEXT,
26
+ model_response TEXT NOT NULL,
27
+ generation_time REAL NOT NULL,
28
+ tokens_generated INTEGER NOT NULL,
29
+ temperature REAL NOT NULL,
30
+ top_p REAL NOT NULL,
31
+ max_length INTEGER NOT NULL,
32
+ timestamp TEXT NOT NULL
33
+ )
34
+ ''')
35
+
36
+ conn.commit()
37
+ print("Test database initialized successfully")
38
+ return True
39
+ except Exception as e:
40
+ print(f"Error initializing database: {e}")
41
+ return False
42
 
 
 
 
 
43
  def save_test_result(analysis_mode, system_prompt, input_content, model_response,
44
  generation_time, tokens_generated, temperature, top_p, max_length):
45
+ """Save a test result to the database"""
46
+ try:
47
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
48
 
49
+ with sqlite3.connect(DB_PATH) as conn:
50
+ cursor = conn.cursor()
51
+
52
+ cursor.execute('''
53
+ INSERT INTO model_tests
54
+ (analysis_mode, system_prompt, input_content, model_response,
55
+ generation_time, tokens_generated, temperature, top_p, max_length, timestamp)
56
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
57
+ ''', (analysis_mode, system_prompt, input_content, model_response,
58
+ generation_time, tokens_generated, temperature, top_p, max_length, timestamp))
59
+
60
+ test_id = cursor.lastrowid
61
+ conn.commit()
62
 
63
+ return test_id
64
+ except Exception as e:
65
+ print(f"Error saving test result: {e}")
66
+ return None
67
 
 
68
  def get_test_history(limit=10):
69
+ """Get recent test history"""
70
+ try:
71
+ with sqlite3.connect(DB_PATH) as conn:
72
+ cursor = conn.cursor()
73
+ cursor.execute('''
74
+ SELECT id, analysis_mode, timestamp, generation_time, tokens_generated
75
+ FROM model_tests
76
+ ORDER BY id DESC LIMIT ?
77
+ ''', (limit,))
78
+ history = cursor.fetchall()
79
+
80
+ return history
81
+ except Exception as e:
82
+ print(f"Error getting test history: {e}")
83
+ return []
84
 
 
85
  def get_test_details(test_id):
86
+ """Get details for a specific test"""
87
+ try:
88
+ with sqlite3.connect(DB_PATH) as conn:
89
+ cursor = conn.cursor()
90
+ cursor.execute('''
91
+ SELECT * FROM model_tests WHERE id = ?
92
+ ''', (test_id,))
93
+ test = cursor.fetchone()
94
+
95
+ if test:
96
+ # Convert to dictionary
97
+ columns = [col[0] for col in cursor.description]
98
+ test_dict = {columns[i]: test[i] for i in range(len(columns))}
99
+ return test_dict
100
+ else:
101
+ return None
102
+ except Exception as e:
103
+ print(f"Error getting test details: {e}")
104
+ return None