-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGPT-Interface-v1.02-public.py
304 lines (267 loc) · 13.3 KB
/
GPT-Interface-v1.02-public.py
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
import tkinter as tk
import tkinter.scrolledtext as scrolledtext
from tkinter import messagebox, ttk
import pyperclip
import openai
import threading
import time
# Initial setup for OpenAI API key
openai.api_key = '' # replace with your actual key
# Define IdeaGenerator class to handle interactions with OpenAI and the user interface
class IdeaGenerator:
def __init__(self, root):
self.progress = None
self.cancel_button = None
self.is_generating = None
self.estimated_duration = None
self.is_running = True
self.messages = []
self.valid_key = False
root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.durations = []
self.root = root
root.title("OpenAI ChatGPT 3.5 Turbo")
self.cancel_flag = False
# GUI Components
self.create_gui_elements(root)
self.configure_grid(root)
def create_gui_elements(self, root):
# API Key Entry Section
self.create_api_key_section(root)
# Prompt Entry Section
self.create_prompt_section(root)
# Message Entry Section
self.create_message_section(root)
# Output and Controls Section
self.create_output_and_controls_section(root)
def create_api_key_section(self, root):
"""Creates components for API Key entry"""
self.api_key_label = tk.Label(root, text="API Key:")
self.api_key_label.grid(row=0, column=0, sticky='w', columnspan=4)
self.api_key_entry = tk.Entry(root)
self.api_key_entry.grid(row=1, column=0, columnspan=3, sticky='ew')
self.submit_key_button = tk.Button(root, text="Submit Key", command=self.submit_key)
self.submit_key_button.grid(row=1, column=3, sticky='ew')
def create_prompt_section(self, root):
"""Creates components for Prompt entry"""
self.prompt_content = tk.StringVar()
self.prompt_label = tk.Label(root, text="System Prompt:")
self.prompt_label.grid(row=2, column=0, sticky='w', columnspan=4)
self.prompt_entry = tk.Text(root, height=4, width=50)
self.prompt_entry.grid(row=3, column=0, columnspan=4, sticky='nsew')
def create_message_section(self, root):
"""Creates components for Message entry"""
self.message_label = tk.Label(root, text="User Message:")
self.message_label.grid(row=4, column=0, sticky='w', columnspan=4)
self.message_entry = tk.Text(root, height=7, width=50)
self.message_entry.grid(row=5, column=0, columnspan=4, sticky='nsew')
def create_output_and_controls_section(self, root):
"""Creates components for Output box and Control buttons"""
self.is_generating = False
self.estimated_duration = 5
self.idea_box = scrolledtext.ScrolledText(root, wrap=tk.WORD)
self.idea_box.grid(row=7, column=0, columnspan=4, sticky='nsew')
self.progress = ttk.Progressbar(root, mode='determinate', maximum=self.estimated_duration*100)
self.progress.grid(row=8, column=0, columnspan=4, sticky='ew')
self.progress.grid_remove()
# Control Buttons
self.create_control_buttons(root)
self.cancel_button = tk.Button(root, text="Cancel Request", command=self.cancel_request, state='normal')
self.cancel_button.grid(row=10, column=0, columnspan=4, sticky='ew')
self.cancel_button.grid_remove() # Hide the button initially
def create_control_buttons(self, root):
"""Creates control buttons"""
self.generate_button = tk.Button(root, text="Submit Prompt", command=self.start_generate_thread)
self.generate_button.grid(row=6, column=0, sticky='nsew')
self.message_button = tk.Button(root, text="Submit Message", command=self.start_message_thread)
self.message_button.grid(row=6, column=1, sticky='nsew')
self.copy_button = tk.Button(root, text="Copy Output", command=self.copy_idea)
self.copy_button.grid(row=6, column=2, sticky='nsew')
self.clear_button = tk.Button(root, text="Clear Output", command=self.clear_idea)
self.clear_button.grid(row=6, column=3, sticky='nsew')
self.empty_label = tk.Label(root, text="")
self.empty_label.grid(row=6, column=4, sticky='nsew')
def configure_grid(self, root):
"""Configures grid for the root window"""
root.grid_columnconfigure(0, weight=1) # Adjust weight here
root.grid_columnconfigure(1, weight=1) # Adjust weight here
root.grid_columnconfigure(2, weight=1) # Adjust weight here
root.grid_columnconfigure(3, weight=1) # Adjust weight here
# Adjust row configurations as needed
root.grid_rowconfigure(0, weight=0, pad=5) # api_key_label
root.grid_rowconfigure(1, weight=0, pad=5) # api_key_entry
root.grid_rowconfigure(2, weight=0, pad=5) # prompt_label
root.grid_rowconfigure(3, weight=1, pad=5) # prompt_entry
root.grid_rowconfigure(4, weight=0, pad=5) # message_label
root.grid_rowconfigure(5, weight=1, pad=5) # message_entry
root.grid_rowconfigure(6, weight=0, pad=5) # control buttons
root.grid_rowconfigure(7, weight=5, pad=5) # idea_box
root.grid_rowconfigure(8, weight=0, pad=5) # progress bar
root.grid_rowconfigure(9, weight=0, pad=5) # status_label
root.grid_rowconfigure(10, weight=0, pad=5) # cancel_button
def generate_idea(self):
prompt_content = self.prompt_entry.get("1.0",'end-1c').strip()
if not prompt_content:
messagebox.showinfo("Prompt Required!", "Please enter a prompt.")
return
self.is_generating = True
self.progress.grid()
self.cancel_button.grid() # Show the button when generating idea
self.progress['value'] = 0
start_time = time.time()
prompt_content = self.prompt_entry.get("1.0",'end-1c')
self.messages.append({'role': 'system', 'content': prompt_content}) # Use 'system' role for prompt
response = self._call_openai_api()
if response is None:
return
if self.is_running and not self.cancel_flag:
self.messages.append(response['choices'][0]['message'])
self.idea_box.insert('1.0', "\n----------------\n")
self.idea_box.insert('1.0', response['choices'][0]['message']['content'].strip())
end_time = time.time()
self.durations.append(end_time - start_time)
self.estimated_duration = sum(self.durations) / len(self.durations)
self.progress['maximum'] = self.estimated_duration*100
self.progress.stop()
self.progress.grid_remove()
self.cancel_flag = False
self.cancel_button.config(state='disabled')
self.cancel_button.grid_remove() # Hide the button
self.cancel_button.config(state='normal', text='Cancel Request')
else:
self.progress.stop()
self.progress.grid_remove()
self.cancel_flag = False
self.cancel_button.config(state='disabled')
self.cancel_button.grid_remove() # Hide the button
self.cancel_button.config(state='normal', text='Cancel Request')
self.is_generating = False
def generate_message(self):
prompt_content = self.prompt_entry.get("1.0",'end-1c').strip()
if not prompt_content:
messagebox.showinfo("Prompt Required!", "Please enter a prompt.")
return
self.is_generating = True
self.progress.grid()
self.cancel_button.grid() # Show the button when generating message
self.progress['value'] = 0
start_time = time.time()
message_content = self.message_entry.get("1.0",'end-1c')
self.messages.append({'role': 'user', 'content': message_content}) # Use 'user' role for message
response = self._call_openai_api()
if response is None:
return
if self.is_running and not self.cancel_flag:
self.messages.append(response['choices'][0]['message'])
self.idea_box.insert('1.0', "\n----------------\n")
self.idea_box.insert('1.0', response['choices'][0]['message']['content'].strip())
end_time = time.time()
self.durations.append(end_time - start_time)
self.estimated_duration = sum(self.durations) / len(self.durations)
self.progress['maximum'] = self.estimated_duration*100
self.progress.stop()
self.progress.grid_remove()
self.cancel_flag = False
self.cancel_button.config(state='disabled')
self.cancel_button.grid_remove() # Hide the button
self.cancel_button.config(state='normal', text='Cancel Request')
else:
self.progress.stop()
self.progress.grid_remove()
self.cancel_flag = False
self.cancel_button.config(state='disabled')
self.cancel_button.grid_remove() # Hide the button
self.cancel_button.config(state='normal', text='Cancel Request')
self.is_generating = False
def start_generate_thread(self):
if not self.is_generating and self.valid_key:
self.cancel_button.config(state='normal')
self.cancel_flag = False
self.messages = []
threading.Thread(target=self.generate_idea).start()
threading.Thread(target=self.run_progress).start() # Start progress thread
else:
if not self.valid_key:
messagebox.showinfo("API Key Required!", "Please submit a valid API Key.")
def start_message_thread(self):
if not self.is_generating and self.valid_key and self.messages:
self.cancel_button.config(state='normal')
self.cancel_flag = False
threading.Thread(target=self.generate_message).start()
threading.Thread(target=self.run_progress).start() # Start progress thread
else:
if not self.valid_key:
messagebox.showinfo("API Key Required!", "Please submit a valid API Key.")
def copy_idea(self):
pyperclip.copy(self.idea_box.get('1.0', tk.END))
messagebox.showinfo("Copied!", "Output has been copied to clipboard")
def clear_idea(self):
self.idea_box.delete('1.0', tk.END)
def run_progress(self):
self.progress.grid()
self.progress['value'] = 0
while self.is_generating and not self.cancel_flag:
# Increment progress bar every 100ms up to maximum
if self.progress['value'] < self.progress['maximum']:
self.progress['value'] += 1
else:
self.progress['value'] = 0
time.sleep(0.01)
self.progress.stop()
self.progress.grid_remove()
def on_closing(self):
self.is_running = False
self.root.destroy()
def submit_key(self):
# Debug comment: Submit the API key and validate it by making a test API call.
test_key = self.api_key_entry.get().strip()
if test_key:
openai.api_key = test_key
try:
# Debug comment: Make a test API call to OpenAI.
openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "system", "content": "You are a helpful assistant."}],
max_tokens=5,
)
# Debug comment: If the API call is successful, the API key is valid.
self.valid_key = True
self.api_key_entry.delete(0, 'end') # Clear the API key entry box
messagebox.showinfo("API Key Updated!", "The API Key has been updated successfully")
except openai.error.OpenAIError as error:
# Debug comment: If the API call results in an error, the API key is invalid.
self.valid_key = False
messagebox.showinfo("API Key Invalid!", "The entered API Key is invalid. Please enter a valid key.")
else:
messagebox.showinfo("API Key Required!", "Please enter an API Key.")
def cancel_request(self):
# Debug comment: Cancel the current generation request and reset the progress bar.
if self.is_generating:
self.cancel_flag = True
self.cancel_button.config(text='Cancelling...', state='disabled')
self.progress['value'] = 0 # Reset the progress bar
def _call_openai_api(self):
retries = 0
while retries < 3 and self.is_running and not self.cancel_flag:
try:
if not self.is_running or self.cancel_flag:
break
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.messages,
)
return response
except openai.error.RateLimitError:
retries += 1
time.sleep(1)
except openai.error.AuthenticationError:
self.idea_box.insert('1.0', "\n----------------\n")
self.idea_box.insert('1.0', "Invalid OpenAI API key!")
return None
return None
# Debug comment: Create the main window and start the Tkinter event loop.
root = tk.Tk()
root.geometry("600x400")
root.minsize(600, 600)
gui = IdeaGenerator(root)
root.mainloop()