Spaces:
Sleeping
Sleeping
File size: 4,521 Bytes
6cff14b | 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | """
Database module for BrightMind AI
Handles all database operations including feedback storage and retrieval
"""
import sqlite3
from datetime import datetime
from config import DATABASE_FILE
def init_database():
"""Initialize the SQLite database"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
# Create feedback table
cursor.execute('''
CREATE TABLE IF NOT EXISTS feedback (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
feedback_type TEXT NOT NULL,
rating INTEGER NOT NULL,
comments TEXT NOT NULL,
user_email TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
print("✅ Database initialized successfully")
return True
except Exception as e:
print(f"❌ Database initialization error: {e}")
return False
def save_feedback_to_db(feedback_type, rating, comments, user_email=""):
"""Save feedback to SQLite database"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
# Convert feedback_type list to string
feedback_type_str = ', '.join(feedback_type) if isinstance(feedback_type, list) else str(feedback_type)
cursor.execute('''
INSERT INTO feedback (timestamp, feedback_type, rating, comments, user_email)
VALUES (?, ?, ?, ?, ?)
''', (
datetime.now().isoformat(),
feedback_type_str,
rating,
comments,
user_email
))
conn.commit()
conn.close()
print("✅ Feedback saved to database successfully")
return True
except Exception as e:
print(f"❌ Database save error: {e}")
return False
def get_feedback_stats():
"""Get feedback statistics for admin"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
# Get total feedback count
cursor.execute('SELECT COUNT(*) FROM feedback')
total_feedback = cursor.fetchone()[0]
# Get average rating
cursor.execute('SELECT AVG(rating) FROM feedback')
avg_rating = cursor.fetchone()[0]
avg_rating = round(avg_rating, 2) if avg_rating else 0
# Get recent feedback (last 5)
cursor.execute('''
SELECT timestamp, feedback_type, rating, comments, user_email
FROM feedback
ORDER BY created_at DESC
LIMIT 5
''')
recent_feedback = cursor.fetchall()
conn.close()
return {
'total_feedback': total_feedback,
'avg_rating': avg_rating,
'recent_feedback': recent_feedback
}
except Exception as e:
print(f"❌ Database stats error: {e}")
return {
'total_feedback': 0,
'avg_rating': 0,
'recent_feedback': []
}
def view_feedback_admin():
"""Admin function to view all feedback"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
cursor.execute('''
SELECT id, timestamp, feedback_type, rating, comments, user_email, created_at
FROM feedback
ORDER BY created_at DESC
''')
feedback_data = cursor.fetchall()
conn.close()
if not feedback_data:
return "No feedback found in database."
# Format feedback data
result = "# 📊 Feedback Database\n\n"
result += f"**Total Feedback Entries:** {len(feedback_data)}\n\n"
for entry in feedback_data:
id_val, timestamp, feedback_type, rating, comments, user_email, created_at = entry
result += f"## Entry #{id_val}\n"
result += f"**Date:** {timestamp}\n"
result += f"**Type:** {feedback_type}\n"
result += f"**Rating:** {rating}/5 ⭐\n"
result += f"**Comments:** {comments}\n"
result += f"**Email:** {user_email if user_email else 'Not provided'}\n"
result += f"**Created:** {created_at}\n"
result += "---\n\n"
return result
except Exception as e:
return f"❌ Error accessing database: {str(e)}"
|