|
| 1 | +import tkinter as tk |
| 2 | +from tkinter import Entry, scrolledtext |
| 3 | +from transformers import AutoTokenizer, AutoModelForCausalLM |
| 4 | + |
| 5 | +# Load the model and tokenizer |
| 6 | +tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1_5") |
| 7 | +model = AutoModelForCausalLM.from_pretrained( |
| 8 | + "microsoft/phi-1_5", trust_remote_code=True) |
| 9 | + |
| 10 | +# Function to generate a response from the model |
| 11 | + |
| 12 | + |
| 13 | +def generate_response(message): |
| 14 | + inputs = tokenizer(message, return_tensors='pt', truncation=True) |
| 15 | + outputs = model.generate( |
| 16 | + **inputs, |
| 17 | + max_length=150, |
| 18 | + pad_token_id=tokenizer.eos_token_id |
| 19 | + ) |
| 20 | + response = tokenizer.decode(outputs[0], skip_special_tokens=True) |
| 21 | + return response |
| 22 | + |
| 23 | +# Function to handle when the user sends a message |
| 24 | + |
| 25 | + |
| 26 | +def on_send(event=None): # event is passed by binders. |
| 27 | + message = user_input.get() |
| 28 | + if message: # Only process if there's a message |
| 29 | + # Display user message in the chat window |
| 30 | + chat_window.configure(state=tk.NORMAL) # Temporarily make it editable |
| 31 | + chat_window.insert(tk.END, f"You: {message}\n") |
| 32 | + chat_window.configure(state=tk.DISABLED) # Make it read-only again |
| 33 | + |
| 34 | + # Clear the user input field |
| 35 | + user_input.delete(0, tk.END) |
| 36 | + |
| 37 | + # Generate and display chatbot response |
| 38 | + response = generate_response(message) |
| 39 | + chat_window.configure(state=tk.NORMAL) |
| 40 | + chat_window.insert(tk.END, f"WebIdeasBot: {response}\n") |
| 41 | + chat_window.configure(state=tk.DISABLED) |
| 42 | + |
| 43 | + |
| 44 | +# Create the main window |
| 45 | +window = tk.Tk() |
| 46 | +window.title("WebIdeasBot") |
| 47 | + |
| 48 | +# Create the chat window |
| 49 | +chat_window = scrolledtext.ScrolledText( |
| 50 | + window, width=80, height=20, state=tk.DISABLED) |
| 51 | +chat_window.pack() |
| 52 | + |
| 53 | +# Create the user input field |
| 54 | +user_input = Entry(window, width=80) |
| 55 | +user_input.pack() |
| 56 | +user_input.focus_set() # Set focus to the input field |
| 57 | + |
| 58 | +# Bind the Enter key to the on_send function |
| 59 | +user_input.bind("<Return>", on_send) |
| 60 | + |
| 61 | +# Start the Tkinter event loop |
| 62 | +window.mainloop() |
0 commit comments