-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_app.py
More file actions
419 lines (355 loc) · 14.1 KB
/
chat_app.py
File metadata and controls
419 lines (355 loc) · 14.1 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/env python3
"""
Grok-Mini Chat - Windows GUI Application
A human-friendly ChatGPT-type interface for Grok-Mini V2
"""
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
import threading
import queue
from datetime import datetime
import os
import sys
try:
from grok_mini import GrokMiniV2, generate, config, tokenizer
import torch
except ImportError as e:
print(f"Error importing dependencies: {e}")
print("Please run: pip install -r requirements.txt")
sys.exit(1)
class GrokMiniChat:
def __init__(self, root):
self.root = root
self.root.title("Grok-Mini Chat")
self.root.geometry("900x700")
# Set icon and style
self.setup_styles()
# Model state
self.model = None
self.model_loaded = False
self.generation_queue = queue.Queue()
self.is_generating = False
# Chat history
self.chat_history = []
# Create UI
self.create_ui()
# Start model loading in background
self.load_model_async()
def setup_styles(self):
"""Setup UI styling"""
style = ttk.Style()
style.theme_use('clam')
# Configure colors
self.bg_color = "#1e1e1e"
self.fg_color = "#ffffff"
self.user_msg_color = "#2b5797"
self.ai_msg_color = "#2d2d2d"
self.input_bg = "#252525"
self.button_color = "#0e639c"
def create_ui(self):
"""Create the main UI layout"""
# Main container
main_frame = tk.Frame(self.root, bg=self.bg_color)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Title bar
title_frame = tk.Frame(main_frame, bg=self.bg_color)
title_frame.pack(fill=tk.X, pady=(0, 10))
title_label = tk.Label(
title_frame,
text="🤖 Grok-Mini Chat",
font=("Segoe UI", 20, "bold"),
bg=self.bg_color,
fg=self.fg_color
)
title_label.pack(side=tk.LEFT)
self.status_label = tk.Label(
title_frame,
text="Loading model...",
font=("Segoe UI", 10),
bg=self.bg_color,
fg="#ffaa00"
)
self.status_label.pack(side=tk.RIGHT)
# Chat display area
chat_frame = tk.Frame(main_frame, bg=self.bg_color)
chat_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
self.chat_display = scrolledtext.ScrolledText(
chat_frame,
wrap=tk.WORD,
font=("Segoe UI", 10),
bg=self.bg_color,
fg=self.fg_color,
insertbackground=self.fg_color,
relief=tk.FLAT,
padx=10,
pady=10
)
self.chat_display.pack(fill=tk.BOTH, expand=True)
self.chat_display.config(state=tk.DISABLED)
# Configure tags for message styling
self.chat_display.tag_config("user", foreground="#7eb6ff", font=("Segoe UI", 10, "bold"))
self.chat_display.tag_config("ai", foreground="#00ff88", font=("Segoe UI", 10, "bold"))
self.chat_display.tag_config("system", foreground="#ffaa00", font=("Segoe UI", 9, "italic"))
self.chat_display.tag_config("timestamp", foreground="#888888", font=("Segoe UI", 8))
# Input area
input_frame = tk.Frame(main_frame, bg=self.bg_color)
input_frame.pack(fill=tk.X)
# Input text box
self.input_text = tk.Text(
input_frame,
height=3,
font=("Segoe UI", 10),
bg=self.input_bg,
fg=self.fg_color,
insertbackground=self.fg_color,
relief=tk.FLAT,
padx=10,
pady=10,
wrap=tk.WORD
)
self.input_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 5))
self.input_text.bind("<Return>", self.on_enter_key)
self.input_text.bind("<Shift-Return>", lambda e: None) # Allow newline with Shift+Enter
# Button frame
button_frame = tk.Frame(input_frame, bg=self.bg_color)
button_frame.pack(side=tk.RIGHT, fill=tk.Y)
self.send_button = tk.Button(
button_frame,
text="Send",
command=self.send_message,
font=("Segoe UI", 10, "bold"),
bg=self.button_color,
fg=self.fg_color,
relief=tk.FLAT,
padx=20,
pady=10,
cursor="hand2"
)
self.send_button.pack(pady=(0, 5))
clear_button = tk.Button(
button_frame,
text="Clear",
command=self.clear_chat,
font=("Segoe UI", 9),
bg="#4a4a4a",
fg=self.fg_color,
relief=tk.FLAT,
padx=20,
pady=5,
cursor="hand2"
)
clear_button.pack()
# Settings bar
settings_frame = tk.Frame(main_frame, bg=self.bg_color)
settings_frame.pack(fill=tk.X, pady=(10, 0))
tk.Label(
settings_frame,
text="Temperature:",
bg=self.bg_color,
fg=self.fg_color,
font=("Segoe UI", 9)
).pack(side=tk.LEFT, padx=(0, 5))
self.temp_var = tk.DoubleVar(value=0.7)
temp_scale = tk.Scale(
settings_frame,
from_=0.1,
to=1.5,
resolution=0.1,
orient=tk.HORIZONTAL,
variable=self.temp_var,
bg=self.bg_color,
fg=self.fg_color,
highlightthickness=0,
length=150
)
temp_scale.pack(side=tk.LEFT, padx=(0, 20))
tk.Label(
settings_frame,
text="Max Tokens:",
bg=self.bg_color,
fg=self.fg_color,
font=("Segoe UI", 9)
).pack(side=tk.LEFT, padx=(0, 5))
self.max_tokens_var = tk.IntVar(value=150)
max_tokens_spin = tk.Spinbox(
settings_frame,
from_=50,
to=500,
textvariable=self.max_tokens_var,
width=8,
font=("Segoe UI", 9),
bg=self.input_bg,
fg=self.fg_color,
relief=tk.FLAT
)
max_tokens_spin.pack(side=tk.LEFT, padx=(0, 20))
# Load image button
load_img_button = tk.Button(
settings_frame,
text="📷 Load Image",
command=self.load_image,
font=("Segoe UI", 9),
bg="#4a4a4a",
fg=self.fg_color,
relief=tk.FLAT,
padx=10,
pady=5,
cursor="hand2"
)
load_img_button.pack(side=tk.LEFT)
self.image_path = None
self.image_label = tk.Label(
settings_frame,
text="",
bg=self.bg_color,
fg="#00ff88",
font=("Segoe UI", 8)
)
self.image_label.pack(side=tk.LEFT, padx=(10, 0))
# Welcome message
self.add_system_message("Welcome to Grok-Mini Chat! Loading model, please wait...")
def load_model_async(self):
"""Load model in background thread"""
def load():
try:
self.add_system_message(f"Initializing model on {config.device}...")
self.model = GrokMiniV2().to(config.device).to(config.dtype)
param_count = sum(p.numel() for p in self.model.parameters()) / 1e6
self.model_loaded = True
self.root.after(0, lambda: self.on_model_loaded(param_count))
except Exception as e:
self.root.after(0, lambda: self.on_model_error(str(e)))
thread = threading.Thread(target=load, daemon=True)
thread.start()
def on_model_loaded(self, param_count):
"""Called when model is loaded successfully"""
self.status_label.config(text=f"✓ Ready ({param_count:.1f}M params)", fg="#00ff88")
self.add_system_message(f"Model loaded successfully! ({param_count:.1f}M parameters)")
self.add_system_message("You can start chatting now. Type your message and press Send or Enter.")
self.input_text.focus()
def on_model_error(self, error):
"""Called when model loading fails"""
self.status_label.config(text="⚠ Error loading model", fg="#ff0000")
self.add_system_message(f"Error loading model: {error}")
messagebox.showerror("Model Error", f"Failed to load model:\n{error}")
def add_message(self, role, message, tag=None):
"""Add a message to the chat display"""
self.chat_display.config(state=tk.NORMAL)
# Add timestamp
timestamp = datetime.now().strftime("%H:%M:%S")
self.chat_display.insert(tk.END, f"[{timestamp}] ", "timestamp")
# Add role
role_tag = tag if tag else role.lower()
self.chat_display.insert(tk.END, f"{role}: ", role_tag)
# Add message
self.chat_display.insert(tk.END, f"{message}\n\n")
self.chat_display.config(state=tk.DISABLED)
self.chat_display.see(tk.END)
def add_system_message(self, message):
"""Add a system message"""
self.chat_display.config(state=tk.NORMAL)
timestamp = datetime.now().strftime("%H:%M:%S")
self.chat_display.insert(tk.END, f"[{timestamp}] ", "timestamp")
self.chat_display.insert(tk.END, f"{message}\n", "system")
self.chat_display.config(state=tk.DISABLED)
self.chat_display.see(tk.END)
def on_enter_key(self, event):
"""Handle Enter key press"""
if not event.state & 0x1: # Check if Shift is not pressed
self.send_message()
return "break" # Prevent default newline
def send_message(self):
"""Send user message and get AI response"""
if not self.model_loaded:
messagebox.showwarning("Model Not Ready", "Please wait for the model to finish loading.")
return
if self.is_generating:
messagebox.showinfo("Generating", "Please wait for the current response to complete.")
return
# Get user input
user_input = self.input_text.get("1.0", tk.END).strip()
if not user_input:
return
# Clear input
self.input_text.delete("1.0", tk.END)
# Add user message to chat
self.add_message("You", user_input, "user")
self.chat_history.append({"role": "user", "content": user_input})
# Disable send button
self.send_button.config(state=tk.DISABLED, text="Thinking...")
self.is_generating = True
# Generate response in background
def generate_response():
try:
# Prepare image if loaded
image_tensor = None
if self.image_path:
try:
from PIL import Image
import numpy as np
img = Image.open(self.image_path).resize((224, 224))
img_array = np.array(img).transpose(2, 0, 1).astype(np.float32) / 255.0
image_tensor = torch.from_numpy(img_array).unsqueeze(0).to(config.device).to(config.dtype)
except Exception as e:
print(f"Error loading image: {e}")
# Generate
response = generate(
self.model,
user_input,
max_new_tokens=self.max_tokens_var.get(),
temperature=self.temp_var.get(),
image=image_tensor
)
# Extract only the new part (after the prompt)
ai_response = response[len(user_input):].strip()
# Update UI in main thread
self.root.after(0, lambda: self.on_response_generated(ai_response))
except Exception as e:
self.root.after(0, lambda: self.on_generation_error(str(e)))
thread = threading.Thread(target=generate_response, daemon=True)
thread.start()
def on_response_generated(self, response):
"""Called when response is generated"""
self.add_message("Grok-Mini", response, "ai")
self.chat_history.append({"role": "assistant", "content": response})
# Re-enable send button
self.send_button.config(state=tk.NORMAL, text="Send")
self.is_generating = False
# Clear image after use
if self.image_path:
self.image_path = None
self.image_label.config(text="")
def on_generation_error(self, error):
"""Called when generation fails"""
self.add_system_message(f"Error generating response: {error}")
self.send_button.config(state=tk.NORMAL, text="Send")
self.is_generating = False
def clear_chat(self):
"""Clear chat history"""
if messagebox.askyesno("Clear Chat", "Are you sure you want to clear the chat history?"):
self.chat_display.config(state=tk.NORMAL)
self.chat_display.delete("1.0", tk.END)
self.chat_display.config(state=tk.DISABLED)
self.chat_history = []
self.add_system_message("Chat cleared. Start a new conversation!")
def load_image(self):
"""Load an image for vision input"""
file_path = filedialog.askopenfilename(
title="Select Image",
filetypes=[
("Image Files", "*.png *.jpg *.jpeg *.bmp *.gif"),
("All Files", "*.*")
]
)
if file_path:
self.image_path = file_path
filename = os.path.basename(file_path)
self.image_label.config(text=f"📷 {filename}")
self.add_system_message(f"Image loaded: {filename}")
def main():
"""Main entry point"""
root = tk.Tk()
app = GrokMiniChat(root)
root.mainloop()
if __name__ == "__main__":
main()