from hobby to work i started making some automation and controle scripts.
so my knowledge is still very low atm.
but i pulled from gpt 4o and made this code mostly working.
but im stuck.
the idea of this script is to make a frame work where it is really easy to plug in functions for the front office to start some of the automation scripts
import tkinter as tk
from tkinter import scrolledtext, filedialog, messagebox
from openai import OpenAI
import os
import json
import time
import threading
import queue
import base64
import webbrowser
import tempfile
from datetime import datetime, timedelta
OpenAI API configuratie
API_KEY = “xxxxxxxxxxxxxxxxxxxxxxx”
assistant_id = “xxxxxxxxxxxxxxxx”
client = OpenAI(api_key=API_KEY)
Globale variabelen
uploaded_file_content = None
response_queue = queue.Queue()
thinking_animation = None
attached_files =
thread_id = None
def get_or_create_weekly_thread():
now = datetime.now()
week_start = now - timedelta(days=now.weekday())
week_name = f"Week van {week_start.strftime(‘%d-%m-%Y’)}"
# Probeer een bestaande thread te vinden voor deze week
try:
existing_thread = client.beta.threads.retrieve(thread_id)
if existing_thread.metadata.get('week_start') == week_start.isoformat():
return existing_thread.id
except:
pass # Als de thread niet bestaat, gaan we verder met het maken van een nieuwe
# Maak een nieuwe thread aan voor deze week
new_thread = client.beta.threads.create(
metadata={
'week_start': week_start.isoformat(),
'name': week_name
}
)
return new_thread.id
def send(event=None):
user_message = user_entry.get()
if user_message.strip() == “”:
return
display_message(user_message, “user”)
user_entry.delete(0, tk.END)
start_thinking_animation()
threading.Thread(target=get_response_thread, args=(user_message,), daemon=True).start()
root.after(100, check_response)
def check_response():
try:
bot_response = response_queue.get_nowait()
stop_thinking_animation()
display_message(bot_response, “bot”)
except queue.Empty:
root.after(100, check_response)
def get_response_thread(user_message):
bot_response = get_response_from_assistant(user_message)
response_queue.put(bot_response)
def upload_document():
global uploaded_file_content
file_path = filedialog.askopenfilename()
if file_path:
start_thinking_animation(“Document wordt geüpload”)
threading.Thread(target=upload_document_thread, args=(file_path,), daemon=True).start()
def upload_document_thread(file_path):
global uploaded_file_content, attached_files, thread_id
file_name = os.path.basename(file_path)
with open(file_path, "rb") as file:
file_content = file.read()
file = client.files.create(
file=file_content,
purpose='assistants'
)
attached_files.append(str(file.id))
uploaded_file_content = f"Bestand '{file_name}' is geüpload en gekoppeld aan de assistent. (File ID: {file.id})"
root.after(0, lambda: stop_thinking_animation())
root.after(0, lambda: display_message(uploaded_file_content, "bot"))
client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=f"Ik heb zojuist een bestand geüpload: '{file_name}' (File ID: {file.id}). Kun je de inhoud analyseren en bespreken?"
)
response = get_response_from_assistant(f"Ik heb zojuist het bestand '{file_name}' geüpload. Kun je de inhoud analyseren en samenvatten?")
root.after(0, lambda: display_message(response, "bot"))
def display_message(message, sender):
chat_frame.config(state=tk.NORMAL)
chat_frame.insert(tk.END, f"{sender.capitalize()}: {message}\n\n", sender)
if sender == "bot" and attached_files:
for file_id in attached_files:
file = client.files.retrieve(file_id)
create_download_link(file)
chat_frame.insert(tk.END, "\n")
chat_frame.config(state=tk.DISABLED)
chat_frame.yview(tk.END)
def log_message(message):
print(message)
root.after(0, lambda: display_message(message, “bot”))
def get_response_from_assistant(user_message):
global thread_id, attached_files
message = client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=user_message
)
if attached_files:
file_message = "De volgende bestanden zijn gekoppeld: " + ", ".join(attached_files)
client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=file_message
)
run = client.beta.threads.runs.create(
thread_id=thread_id,
assistant_id=assistant_id,
)
run = wait_on_run(run, thread_id)
messages = client.beta.threads.messages.list(thread_id=thread_id)
for message in messages.data:
if message.role == 'assistant':
full_response = ""
for content in message.content:
if content.type == 'text':
full_response += content.text.value
return full_response
return "Sorry, ik begrijp het niet."
def wait_on_run(run, thread_id):
while run.status == “queued” or run.status == “in_progress”:
run = client.beta.threads.runs.retrieve(
thread_id=thread_id,
run_id=run.id,
)
time.sleep(0.5)
return run
def reset_conversation():
global attached_files
attached_files =
log_message(“Bijlagen verwijderd. De conversatie thread blijft behouden.”)
def start_thinking_animation(prefix=“loading…”):
global thinking_animation
dots = [". ", "… ", “…”]
def animate(index=0):
global thinking_animation
thinking_text.set(f"{prefix}{dots[index]}")
next_index = (index + 1) % 3
thinking_animation = root.after(500, lambda: animate(next_index))
thinking_label.pack(side=tk.LEFT, padx=10)
animate()
def stop_thinking_animation():
global thinking_animation
if thinking_animation:
root.after_cancel(thinking_animation)
thinking_animation = None
thinking_text.set(“”)
thinking_label.pack_forget()
def create_download_link(file):
def download_file():
file_content = client.files.content(file.id)
with tempfile.NamedTemporaryFile(mode=‘wb’, delete=False, suffix=f’_{file.filename}‘) as temp_file:
temp_file.write(file_content.content)
temp_file_path = temp_file.name
webbrowser.open(f’file://{temp_file_path}’)
download_button = tk.Button(chat_frame, text=f"Download {file.filename}", command=download_file)
chat_frame.window_create(tk.END, window=download_button)
chat_frame.insert(tk.END, "\n")
def list_threads():
thread_listbox.delete(0, tk.END)
# Voeg alleen de huidige thread toe aan de lijst
if thread_id:
try:
thread = client.beta.threads.retrieve(thread_id)
thread_name = thread.metadata.get(‘name’, ‘Huidige week’)
thread_listbox.insert(tk.END, thread_name)
thread_listbox.itemconfig(tk.END, thread_id=thread.id)
except:
pass
def load_thread(event):
global thread_id
selection = thread_listbox.curselection()
if selection:
thread_id = thread_listbox.itemcget(selection[0], ‘thread_id’)
load_thread_messages(thread_id)
def load_thread_messages(thread_id):
messages = client.beta.threads.messages.list(thread_id=thread_id)
chat_frame.config(state=tk.NORMAL)
chat_frame.delete(‘1.0’, tk.END)
for message in reversed(messages.data):
role = ‘user’ if message.role == ‘user’ else ‘bot’
content = message.content[0].text.value if message.content else “”
display_message(content, role)
chat_frame.config(state=tk.DISABLED)
GUI setup
root = tk.Tk()
root.title(“chatbot”)
Hoofdframe
main_frame = tk.Frame(root, bg=“#1e1e1e”)
main_frame.pack(fill=tk.BOTH, expand=True)
Linker frame voor thread lijst
left_frame = tk.Frame(main_frame, bg=“#1e1e1e”, width=200)
left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
thread_listbox = tk.Listbox(left_frame, bg=“#333333”, fg=“white”, font=(“Helvetica”, 10), width=25)
thread_listbox.pack(fill=tk.BOTH, expand=True)
thread_listbox.bind(“<>”, load_thread)
refresh_button = tk.Button(left_frame, text=“Ververs Lijst”, command=list_threads, bg=“#4CAF50”, fg=“white”, font=(“Helvetica”, 10))
refresh_button.pack(pady=5)
Rechter frame voor chat
right_frame = tk.Frame(main_frame, bg=“#1e1e1e”)
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)
chat_frame = scrolledtext.ScrolledText(right_frame, wrap=tk.WORD, state=tk.DISABLED, bg=“#1e1e1e”, fg=“white”, font=(“Helvetica”, 12), spacing3=10)
chat_frame.pack(fill=tk.BOTH, expand=True)
chat_frame.tag_config(“user”, foreground=“#00ff00”, justify=“left”)
chat_frame.tag_config(“bot”, foreground=“#00ffff”, justify=“left”)
chat_frame.tag_config(“bot_thinking”, foreground=“#00ffff”, justify=“left”)
chat_frame.config(state=tk.NORMAL)
chat_frame.insert(tk.END, “its me mario \n\n”, “bot”)
chat_frame.config(state=tk.DISABLED)
user_entry = tk.Entry(right_frame, width=80, bg=“#333333”, fg=“white”, font=(“Helvetica”, 12))
user_entry.pack(pady=5, fill=tk.X)
user_entry.bind(“”, send)
button_frame = tk.Frame(right_frame, bg=“#1e1e1e”)
button_frame.pack(fill=tk.X)
send_button = tk.Button(button_frame, text=“Verstuur”, command=send, bg=“#4CAF50”, fg=“white”, font=(“Helvetica”, 12))
send_button.pack(side=tk.LEFT)
upload_button = tk.Button(button_frame, text=“Upload Document”, command=upload_document, bg=“#4CAF50”, fg=“white”, font=(“Helvetica”, 12))
upload_button.pack(side=tk.LEFT, padx=10)
reset_button = tk.Button(button_frame, text=“Reset Bijlagen”, command=reset_conversation, bg=“#FF5733”, fg=“white”, font=(“Helvetica”, 12))
reset_button.pack(side=tk.LEFT, padx=10)
thinking_text = tk.StringVar()
thinking_label = tk.Label(button_frame, textvariable=thinking_text, bg=“#1e1e1e”, fg=“white”, font=(“Helvetica”, 12))
Start nieuwe week thread of gebruik de bestaande voor deze week
thread_id = get_or_create_weekly_thread()
list_threads()
if name == “main”:
root.mainloop()