I have this code: from keras.layers import MultiHeadAttention
from PyQt5 import QtWidgets
import pickle
import sys
import numpy as np
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
Global variables
model = None
tokenizer = None
history = ""
dark_mode = False
class Chatbot(QtWidgets.QWidget):
def init(self):
super().init()
self.init_ui()
def init_ui(self):
self.layout = QtWidgets.QVBoxLayout()
# Model selection buttons
self.model_label = QtWidgets.QLabel("Select Model:")
self.model_button = QtWidgets.QPushButton("Browse...")
self.model_button.clicked.connect(self.select_model)
# Tokenizer selection buttons
self.tokenizer_label = QtWidgets.QLabel("Select Tokenizer:")
self.tokenizer_button = QtWidgets.QPushButton("Browse...")
self.tokenizer_button.clicked.connect(self.select_tokenizer)
self.input_box = QtWidgets.QLineEdit()
self.input_box.returnPressed.connect(self.on_text_input)
self.mode_switch = QtWidgets.QCheckBox("Chat mode")
self.mode_switch.stateChanged.connect(self.on_mode_switch)
self.dark_mode_button = QtWidgets.QPushButton("Dark Mode")
self.dark_mode_button.clicked.connect(self.toggle_dark_mode)
self.send_button = QtWidgets.QPushButton("Send")
self.send_button.clicked.connect(self.on_send_button)
self.load_model_button = QtWidgets.QPushButton("Load Model")
self.load_model_button.clicked.connect(self.select_model)
self.load_tokenizer_button = QtWidgets.QPushButton("Load Tokenizer")
self.load_tokenizer_button.clicked.connect(self.select_tokenizer)
self.chat_box = QtWidgets.QPlainTextEdit()
self.layout.addWidget(self.chat_box)
self.layout.addWidget(self.input_box)
self.layout.addWidget(self.mode_switch)
self.layout.addWidget(self.dark_mode_button)
self.layout.addWidget(self.send_button)
self.layout.addWidget(self.load_model_button)
self.layout.addWidget(self.load_tokenizer_button)
self.setLayout(self.layout)
self.setWindowTitle("Chatbot")
self.show()
def on_text_input(self):
global model, tokenizer
user_text = self.input_box.text()
self.input_box.clear()
if self.mode_switch.isChecked():
# Chat mode
self.generate_chat_response(user_text)
else:
# Text completion mode
self.complete_text(user_text)
def on_mode_switch(self):
if self.mode_switch.isChecked():
self.chat_box.appendPlainText("Chat mode activated.")
else:
self.chat_box.appendPlainText("Text completion mode activated.")
def toggle_dark_mode(self):
global dark_mode
dark_mode = not dark_mode
if dark_mode:
self.setStyleSheet("background-color: #222222; color: #fff;")
self.send_button.setStyleSheet("background-color: #444444; color: #fff;")
else:
self.setStyleSheet("background-color: #fff; color: #000;")
self.send_button.setStyleSheet("background-color: #eee; color: #000;")
def on_send_button(self):
global model, tokenizer
user_text = self.input_box.text()
self.input_box.clear()
self.chat_box.appendPlainText(f"You: {user_text}")
if self.mode_switch.isChecked():
# Chat mode
self.generate_chat_response(user_text)
else:
# Text completion mode
self.complete_text(user_text)
def select_model(self):
global model
model_path = QtWidgets.QFileDialog.getOpenFileName(self, "Select Model File")[0]
if model_path:
model = load_model(model_path)
def select_tokenizer(self):
global tokenizer
tokenizer_path = QtWidgets.QFileDialog.getOpenFileName(self, "Select Tokenizer File")[0]
if tokenizer_path:
tokenizer = pickle.load(open(tokenizer_path, "rb"))
def generate_chat_response(self, user_text):
global model, tokenizer, history
history += f" {user_text}"
Assistant
The error you're encountering indicates that the variable tokenizer is expected to be an instance of a tokenizer class (assuming from Keras or a similar library), which should have a method named texts_to_sequences. However, the actual content of is a tuple rather than the expected object. This is likely because when you loaded the tokenizer, you used the wrong assignment from the result of the file dialog.
User
This is what i get: Tokenizer type: <class 'tuple'>
Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 122, in select_tokenizer
assert hasattr(tokenizer, "texts_to_sequences"), "Loaded object does not have texts_to_sequences method"
AssertionError: Loaded object does not have texts_to_sequences method
Assistant
User
Does this code return the probability that has the largest value and the one the model predicts to be correct: # Sample the next token from the predicted probabilities
vocab_size = len(tokenizer.word_index) + 1 # The +1 accounts for the padding token.
sampled_token_ids = np.random.choice(vocab_size, size=1, p=last_prediction_probs)
return sampled_token_ids
Assistant
No, the provided code snippet does not return the token with the highest probability directly. Instead, it performs a random sampling, taking probabilities into account. Specifically, np.random.choice selects an element from the given range vocab_size with probabilities defined by last_prediction_probs.
Here's what the snippet does:
determines the range of possible token IDs ( to including padding token).
User
Assistant
The error IndexError: invalid index to scalar variable. in your decode_tokens method is raised because predicted_token_ids is expected to be an array (or list) of indices for tokens, but what you are returning from your predict method is a scalar value.
Here, np.argmax(last_prediction_probs) will return a scalar (the index of the highest probability), not an array. Therefore, when you try to access token_ids[0] in the decode_tokens method, you're trying to index a scalar which is not a valid operation.
You can fix this by modifying decode_tokens to accept the scalar directly without trying to index it:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
predicted_token_ids = self.predict(input_sequence)
predicted_text = self.decode_tokens(predicted_token_ids)
history += f" {predicted_text}"
Display response
self.chat_box.appendPlainText(f"Chatbot: {predicted_text}")
def complete_text(self, user_text):
global model, tokenizer
if not model:
raise RuntimeError("Model not loaded.")
# Preprocess user input
input_sequence = self.preprocess_text(user_text)
# Generate text completion using the model
predicted_token_ids = self.predict(input_sequence)
# Decode tokens and return completed text
completed_text = self.decode_tokens(predicted_token_ids)
self.chat_box.appendPlainText(f"Completion: {completed_text}")
def preprocess_text(self, text):
global model, tokenizer
# Check if tokenizer is loaded
if not tokenizer:
raise RuntimeError("Tokenizer not loaded.")
# Tokenize the text
token_ids = tokenizer.texts_to_sequences([text])
# Pad the sequence
padded_sequence = pad_sequences(token_ids, maxlen=model.input_shape[1])
return padded_sequence
def predict(self, input_sequence):
global model, tokenizer
# Check if model is loaded
if not model:
raise RuntimeError("Model not loaded.")
Make prediction using the model
predictions = model.predict(input_sequence)
Since predictions is 2-dimensional, we take the first (and only) row.
last_prediction_probs = predictions[0]
Sample the next token from the predicted probabilities
vocab_size = len(tokenizer.word_index) + 1 # The +1 accounts for the padding token.
sampled_token_ids = np.random.choice(vocab_size, size=1, p=last_prediction_probs)
return sampled_token_ids
def decode_tokens(self, token_ids):
global tokenizer
# Check if tokenizer is loaded
if not tokenizer:
raise RuntimeError("Tokenizer not loaded.")
# Decode the token IDs back to text
predicted_text = tokenizer.index_word.get(token_ids[0], "UNKNOWN_TOKEN")
return predicted_text
if name == "main":
app = QtWidgets.QApplication(sys.argv)
chatbot = Chatbot()
sys.exit(app.exec_()) and this is the error i get: Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 107, in on_send_button
self.complete_text(user_text)
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 142, in complete_text
input_sequence = self.preprocess_text(user_text)
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 156, in preprocess_text
token_ids = tokenizer.texts_to_sequences([text])
AttributeError: 'tuple' object has no attribute 'texts_to_sequences'
tokenizer
Here's the suspicious line where the tokenizer is loaded:
This line itself seems fine, so the issue might not be directly here. However, the error could potentially come from how the tokenizer was saved initially or if the file selected wasn't the correct pickle file. Ensure the file you're selecting is indeed a pickle file that contains just the tokenizer object.
You should also ensure that you are not accidentally altering the tokenizer variable somewhere else in your code in a way that would turn it into a tuple.
As an additional step, you could add a print statement right after you load the tokenizer to confirm its type and make sure it's been loaded correctly:
if tokenizer_path:
with open(tokenizer_path, "rb") as file:
tokenizer = pickle.load(file)
print(f"Tokenizer type: {type(tokenizer)}") # This should confirm the type
assert hasattr(tokenizer, 'texts_to_sequences'), "Loaded object does not have texts_to_sequences method"
This will print the type of the tokenizer right after it's loaded from the file, and the assert statement will raise an error if the texts_to_sequences method does not exist on the loaded object. If this prints tuple or raises the assertion error, then there is definitely an issue with the file you're loading or how you're loading it.
Please ensure that the file path you select for the tokenizer is indeed a file for a tokenizer and that you have the necessary permissions to read it. If not, the function may return only the file path instead of the actual tokenizer object. This scenario is less likely if you can confirm that the tokenizer_path returned by QFileDialog.getOpenFileName is a valid path to a pickle file containing the tokenizer.
The error and the printed output confirm that the object being loaded as tokenizer is not what you were expecting—it is a tuple rather than an instance of a tokenizer class. There appears to be a couple of potential reasons for this issue:
The pickle file that you are selecting in your select_tokenizer function might not contain the tokenizer instance but rather a tuple. It's possible that when the tokenizer was saved to the pickle file, it was saved incorrectly, or you may have inadvertently selected the wrong file.
The QFileDialog.getOpenFileName method actually returns a tuple where the first element is the filename and the second element is the filter used (in this case, it's probably empty since it wasn't specified). You may be mistakenly using this tuple instead of just the filename.
Take a look at how select_tokenizer function is implemented:
def select_tokenizer(self):
global tokenizer
tokenizer_path = QtWidgets.QFileDialog.getOpenFileName(self, "Select Tokenizer File")[0]
if tokenizer_path:
with open(tokenizer_path, "rb") as file:
tokenizer = pickle.load(file)
print(f"Tokenizer type: {type(tokenizer)}") # This should confirm the type
assert hasattr(tokenizer, 'texts_to_sequences'), "Loaded object does not have texts_to_sequences method"
The [0] after the getOpenFileName is correctly used to extract just the filename from the tuple. However, the saved file might still contain something other than expected.
To address the problem, you need to:
Ensure that the file you are loading actually contains the tokenizer object. Re-check how you saved the tokenizer initially to confirm it was saved correctly without wrapping it in any additional data structure like a tuple.
Make sure that you are selecting the correct file when you are using the file dialog. It must be the pickle file that contains the saved tokenizer.
Once you have confirmed the above points, try to load the tokenizer again using your code. If changes are needed, make them accordingly to correct how you save or load the tokenizer.
Here's a quick example of how you should save and load the tokenizer, assuming it's a Keras tokenizer:
Saving the tokenizer:
# Assuming 'tokenizer' is a Keras tokenizer instance
with open('tokenizer.pkl', 'wb') as file:
pickle.dump(tokenizer, file)
Loading the tokenizer:
# Correctly loading the tokenizer from the file
with open(tokenizer_path, 'rb') as file:
tokenizer = pickle.load(file)
Make sure that the operations are consistent and that the 'tokenizer.pkl' file is the file you are selecting with QFileDialog.getOpenFileName.
vocab_size
1
vocab_size
np.random.choice(vocab_size, size=1, p=last_prediction_probs) uses the probabilities of each token as provided by the model's predictions (last_prediction_probs) to randomly choose one ID according to their probability distribution.
In other words, the ID with the highest probability is more likely to be picked but it's not guaranteed, as the function draws from the distribution. This introduces randomness and can potentially generate more varied outputs compared to always choosing the most likely next token.
If you want to select the token ID with the largest probability, i.e., the most likely next token predicted by the model, you should use numpy.argmax instead:
In this case, numpy.argmax finds the index of the largest value in last_prediction_probs, which corresponds to the most probable next token according to the model's prediction.
Keep in mind this deterministic approach (using numpy.argmax) might repeat the same outputs more often in a conversational AI application, while the previous stochastic approach (using np.random.choice) can add diversity and mimic the unpredictability of human conversation.
Finally, please ensure that last_prediction_probs sums to 1.0 (i.e., it is a proper probability distribution) before using it as the p parameter in np.random.choice, as the function expects a probability distribution. If your model's output is logits (unnormalized scores), you will need to convert them to probabilities, typically using softmax before sampling.
After running this: from keras.layers import MultiHeadAttention
from PyQt5 import QtWidgets
import pickle
import sys
import numpy as np
from keras.preprocessing.sequence import pad_sequences
from keras.models import load_model
Global variables
model = None
tokenizer = None
history = ""
dark_mode = False
class Chatbot(QtWidgets.QWidget):
def init(self):
super().init()
self.init_ui()
def init_ui(self):
self.layout = QtWidgets.QVBoxLayout()
# Model selection buttons
self.model_label = QtWidgets.QLabel("Select Model:")
self.model_button = QtWidgets.QPushButton("Browse...")
self.model_button.clicked.connect(self.select_model)
# Tokenizer selection buttons
self.tokenizer_label = QtWidgets.QLabel("Select Tokenizer:")
self.tokenizer_button = QtWidgets.QPushButton("Browse...")
self.tokenizer_button.clicked.connect(self.select_tokenizer)
self.input_box = QtWidgets.QLineEdit()
self.input_box.returnPressed.connect(self.on_text_input)
self.mode_switch = QtWidgets.QCheckBox("Chat mode")
self.mode_switch.stateChanged.connect(self.on_mode_switch)
self.dark_mode_button = QtWidgets.QPushButton("Dark Mode")
self.dark_mode_button.clicked.connect(self.toggle_dark_mode)
self.send_button = QtWidgets.QPushButton("Send")
self.send_button.clicked.connect(self.on_send_button)
self.load_model_button = QtWidgets.QPushButton("Load Model")
self.load_model_button.clicked.connect(self.select_model)
self.load_tokenizer_button = QtWidgets.QPushButton("Load Tokenizer")
self.load_tokenizer_button.clicked.connect(self.select_tokenizer)
self.chat_box = QtWidgets.QPlainTextEdit()
self.layout.addWidget(self.chat_box)
self.layout.addWidget(self.input_box)
self.layout.addWidget(self.mode_switch)
self.layout.addWidget(self.dark_mode_button)
self.layout.addWidget(self.send_button)
self.layout.addWidget(self.load_model_button)
self.layout.addWidget(self.load_tokenizer_button)
self.setLayout(self.layout)
self.setWindowTitle("Chatbot")
self.show()
def on_text_input(self):
global model, tokenizer
user_text = self.input_box.text()
self.input_box.clear()
if self.mode_switch.isChecked():
# Chat mode
self.generate_chat_response(user_text)
else:
# Text completion mode
self.complete_text(user_text)
def on_mode_switch(self):
if self.mode_switch.isChecked():
self.chat_box.appendPlainText("Chat mode activated.")
else:
self.chat_box.appendPlainText("Text completion mode activated.")
def toggle_dark_mode(self):
global dark_mode
dark_mode = not dark_mode
if dark_mode:
self.setStyleSheet("background-color: #222222; color: #fff;")
self.send_button.setStyleSheet("background-color: #444444; color: #fff;")
else:
self.setStyleSheet("background-color: #fff; color: #000;")
self.send_button.setStyleSheet("background-color: #eee; color: #000;")
def on_send_button(self):
global model, tokenizer
user_text = self.input_box.text()
self.input_box.clear()
self.chat_box.appendPlainText(f"You: {user_text}")
if self.mode_switch.isChecked():
# Chat mode
self.generate_chat_response(user_text)
else:
# Text completion mode
self.complete_text(user_text)
def select_model(self):
global model
model_path = QtWidgets.QFileDialog.getOpenFileName(self, "Select Model File")[0]
if model_path:
model = load_model(model_path)
def select_tokenizer(self):
global tokenizer
tokenizer_path = QtWidgets.QFileDialog.getOpenFileName(self, "Select Tokenizer File")[0]
if tokenizer_path:
with open(tokenizer_path, "rb") as file:
tokenizer = pickle.load(file)
print(f"Tokenizer type: {type(tokenizer)}") # This should confirm the type
assert hasattr(tokenizer, "texts_to_sequences"), "Loaded object does not have texts_to_sequences method"
def generate_chat_response(self, user_text):
global model, tokenizer, history
history += f" {user_text}"
Preprocess user input and history
input_sequence = self.preprocess_text(history)
Generate response using the model
predicted_token_ids = self.predict(input_sequence)
predicted_text = self.decode_tokens(predicted_token_ids)
history += f" {predicted_text}"
Display response
self.chat_box.appendPlainText(f"Chatbot: {predicted_text}")
def complete_text(self, user_text):
global model, tokenizer
if not model:
raise RuntimeError("Model not loaded.")
# Preprocess user input
input_sequence = self.preprocess_text(user_text)
# Generate text completion using the model
predicted_token_ids = self.predict(input_sequence)
# Decode tokens and return completed text
completed_text = self.decode_tokens(predicted_token_ids)
self.chat_box.appendPlainText(f"Completion: {completed_text}")
def preprocess_text(self, text):
global model, tokenizer
# Check if tokenizer is loaded
if not tokenizer:
raise RuntimeError("Tokenizer not loaded.")
# Tokenize the text
token_ids = tokenizer.texts_to_sequences([text])
# Pad the sequence
padded_sequence = pad_sequences(token_ids, maxlen=model.input_shape[1])
return padded_sequence
def predict(self, input_sequence):
global model, tokenizer
# Check if model is loaded
if not model:
raise RuntimeError("Model not loaded.")
Make prediction using the model
predictions = model.predict(input_sequence)
Since predictions is 2-dimensional, we take the first (and only) row.
last_prediction_probs = predictions[0]
Sample the next token from the predicted probabilities
vocab_size = len(tokenizer.word_index) + 1 # The +1 accounts for the padding token.
sampled_token_ids = np.random.choice(vocab_size, size=1, p=last_prediction_probs)
highest_prob_token_id = np.argmax(last_prediction_probs)
return highest_prob_token_id
def decode_tokens(self, token_ids):
global tokenizer
# Check if tokenizer is loaded
if not tokenizer:
raise RuntimeError("Tokenizer not loaded.")
# Decode the token IDs back to text
predicted_text = tokenizer.index_word.get(token_ids[0], "UNKNOWN_TOKEN")
return predicted_text
if name == "main":
app = QtWidgets.QApplication(sys.argv)
chatbot = Chatbot()
sys.exit(app.exec_()) i get this: Traceback (most recent call last):
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 107, in on_send_button
self.complete_text(user_text)
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 151, in complete_text
completed_text = self.decode_tokens(predicted_token_ids)
File "c:\Users\Dell-PC\Desktop\Projets\Model-Creator\chat-C.py", line 192, in decode_tokens
predicted_text = tokenizer.index_word.get(token_ids[0], "UNKNOWN_TOKEN")
IndexError: invalid index to scalar variable.
def decode_tokens(self, token_id):
global tokenizer
# Check if tokenizer is loaded
if not tokenizer:
raise RuntimeError("Tokenizer not loaded.")
# Decode the token ID back to text
predicted_text = tokenizer.index_word.get(token_id, "UNKNOWN_TOKEN")
return predicted_text
Make sure that the argument you pass from complete_text and generate_chat_response to decode_tokens is correctly the scalar token id, not a sequence. Adjust the calling code accordingly:
predicted_text = self.decode_tokens(predicted_token_id) # single ID, not a list or array
With this adjustment, the code should no longer raise an IndexError and should work correctly assuming the tokenizer.index_word dictionary correctly maps token IDs to words.