Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
226 lines (190 loc) · 7.84 KB
/
Copy pathapp.py
File metadata and controls
226 lines (190 loc) · 7.84 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import customtkinter as ctk
import tkinter as tk
from tkinter import ttk, messagebox
import pyodbc
from google import genai
import threading
import os
# CustomTkinter theme configuration
ctk.set_appearance_mode("Dark") # Options: "System", "Dark", "Light"
ctk.set_default_color_theme("blue") # Options: "blue", "green", "dark-blue"
SERVER = os.environ.get('DB_SERVER')
DATABASE = os.environ.get('DB_NAME')
USERNAME = os.environ.get('DB_USER')
PASSWORD = os.environ.get('DB_PASSWORD')
DRIVER = '{FreeTDS}'
CONNECTION_STRING = f'DRIVER={DRIVER};SERVER={SERVER};PORT=1433;DATABASE={DATABASE};UID={USERNAME};PWD={PASSWORD};Timeout=5;'
GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY')
try:
client = genai.Client(api_key=GEMINI_API_KEY)
except Exception as e:
print(f"Error initializing Gemini Client: {e}")
def execute_query(query):
try:
conn = pyodbc.connect(CONNECTION_STRING)
cursor = conn.cursor()
cursor.execute(query)
columns = [column[0] for column in cursor.description]
rows = cursor.fetchall()
update_table(columns, rows)
conn.close()
except Exception as e:
messagebox.showerror("Database Error", f"An error occurred during connection/execution:\n{e}")
# ==========================================
# QUERIES BASED ON REAL DATA
# ==========================================
def query_where_1():
sql = "SELECT title, genre, price, release_date FROM Games WHERE price >= 40.00 ORDER BY price DESC"
execute_query(sql)
def query_where_2():
sql = """
SELECT U.username, J.title, A.price_paid, CAST(CAST(A.discount * 100 AS INT) AS VARCHAR) + '%' AS Discount_Percent
FROM Purchases A
JOIN Users U ON A.id_user = U.id_user
JOIN Games J ON A.id_game = J.id_game
WHERE A.discount > 0
ORDER BY A.discount DESC
"""
execute_query(sql)
def query_where_3():
sql = """
SELECT U.username, J.title, S.duration_minutes, S.start_date
FROM GameSessions S
JOIN Users U ON S.id_user = U.id_user
JOIN Games J ON S.id_game = J.id_game
WHERE S.duration_minutes > 200
ORDER BY S.duration_minutes DESC
"""
execute_query(sql)
def query_having_1():
sql = """
SELECT J.title, COUNT(R.id_review) as Review_Count, CAST(AVG(CAST(R.rating AS FLOAT)) AS DECIMAL(10,2)) as Average_Rating
FROM Reviews R
JOIN Games J ON R.id_game = J.id_game
GROUP BY J.title
HAVING COUNT(R.id_review) >= 3
ORDER BY Average_Rating DESC
"""
execute_query(sql)
def query_having_2():
sql = """
SELECT TOP 10 U.username, SUM(A.price_paid) as Total_Spent
FROM Purchases A
JOIN Users U ON A.id_user = U.id_user
GROUP BY U.username
HAVING SUM(A.price_paid) > 50
ORDER BY SUM(A.price_paid) DESC
"""
execute_query(sql)
# ==========================================
# GEMINI AI INTEGRATION
# ==========================================
def call_gemini():
"""Reads the data from the table and sends it to Gemini for analysis."""
rows = table.get_children()
if not rows:
messagebox.showwarning("Warning", "The table is empty. Run a query first to have data to analyze!")
return
table_data = []
for row in rows[:15]:
values = table.item(row)['values']
table_data.append(str(values))
prompt = (
"Context: This is data extracted from my video game platform database.\n"
"The data may represent gaming sessions, purchase revenue, reviews, or user rankings.\n"
"Please analyze the following records and generate a useful business conclusion "
"in a maximum of 3-4 short, to-the-point sentences.\n\nExtracted data:\n"
)
prompt += "\n".join(table_data)
# CustomTkinter uses .configure() instead of .config(), and state takes strings
btn_ai.configure(text="Thinking...", state="disabled")
def run_request():
try:
response = client.models.generate_content(
model='gemini-3.5-flash',
contents=prompt
)
messagebox.showinfo("Gemini AI Analysis", response.text)
except Exception as e:
messagebox.showerror("Gemini API Error", f"A problem occurred:\n{e}")
finally:
btn_ai.configure(text="✨ Generate AI Conclusion", state="normal")
threading.Thread(target=run_request, daemon=True).start()
def update_table(columns, rows):
table.delete(*table.get_children())
table["columns"] = columns
for col in columns:
table.heading(col, text=col)
table.column(col, width=150, anchor=tk.CENTER)
for row in rows:
values = [str(val) for val in row]
table.insert("", tk.END, values=values)
def on_closing():
root.quit()
root.destroy()
# ==========================================
# MODERN GUI CONFIGURATION
# ==========================================
root = ctk.CTk()
root.title("Game Platform - AI Dashboard")
root.geometry("1050x750")
root.protocol("WM_DELETE_WINDOW", on_closing)
# Modern title
title_label = ctk.CTkLabel(root, text="Game Platform Reports", font=ctk.CTkFont(size=24, weight="bold"))
title_label.pack(pady=(20, 20))
# Frame for buttons
buttons_frame = ctk.CTkFrame(root, fg_color="transparent")
buttons_frame.pack(fill="x", pady=10, padx=20)
buttons_frame.grid_columnconfigure(0, weight=1)
buttons_frame.grid_columnconfigure(1, weight=1)
buttons_frame.grid_columnconfigure(2, weight=1)
def create_button(parent, text, command, fg_color, hover_color, row, column, span=1):
btn = ctk.CTkButton(
parent,
text=text,
command=command,
font=ctk.CTkFont(size=13, weight="bold"),
fg_color=fg_color,
hover_color=hover_color,
height=40,
corner_radius=8
)
btn.grid(row=row, column=column, columnspan=span, padx=10, pady=10, sticky="ew")
return btn
# Buttons with appropriate colors
create_button(buttons_frame, "Premium Games >= 40 (WHERE)", query_where_1, "#1f538d", "#14375e", 0, 0)
create_button(buttons_frame, "Discounted Purchases (WHERE)", query_where_2, "#1f538d", "#14375e", 0, 1)
create_button(buttons_frame, "Sessions > 200 min (WHERE)", query_where_3, "#1f538d", "#14375e", 0, 2)
create_button(buttons_frame, "Top Rating (Reviews >= 3)", query_having_1, "#663399", "#4b2670", 1, 0)
create_button(buttons_frame, "Top 10 Spending Customers", query_having_2, "#663399", "#4b2670", 1, 1)
create_button(buttons_frame, "Exit Application", on_closing, "#cc3333", "#992626", 1, 2)
btn_ai = create_button(buttons_frame, "✨ Generate AI Conclusion", call_gemini, "#2E8B57", "#21633d", 2, 0, span=3)
# Table container
table_frame = ctk.CTkFrame(root, corner_radius=10)
table_frame.pack(fill="both", expand=True, padx=20, pady=(10, 20))
# Modern style for Treeview (Dark Mode integration)
style = ttk.Style()
style.theme_use("default")
style.configure("Treeview",
background="#2b2b2b",
foreground="white",
rowheight=35,
fieldbackground="#2b2b2b",
font=("Arial", 11),
borderwidth=0)
style.configure("Treeview.Heading",
background="#1f538d",
foreground="white",
font=("Arial", 12, "bold"),
relief="flat",
padding=5)
style.map("Treeview", background=[("selected", "#3B82F6")])
style.map("Treeview.Heading", background=[("active", "#14375e")])
# Modern CustomTkinter scrollbar
scroll_y = ctk.CTkScrollbar(table_frame, orientation="vertical")
scroll_y.pack(side="right", fill="y", padx=(0, 5), pady=5)
table = ttk.Treeview(table_frame, yscrollcommand=scroll_y.set, show="headings", style="Treeview")
table.pack(fill="both", expand=True, padx=(5, 0), pady=5)
scroll_y.configure(command=table.yview)
if __name__ == "__main__":
root.mainloop()