I’m working on a Machine Learning based word predictor. All the logic has been implemented already, but now I have to create a basic GUI with gradio
which needs to have the following shape and behavior:
-
Two main components: a text input box where the user can type, and a row with buttons displaying the last typed word’s predictions.
-
Behavior: each time the user enters a character in the input text box, the interface should output in the predictions box the most probable autocompletions of that word, in the form of buttons. When the user presses one of those buttons, the last typed word should be replaced with the chosen prediction.
This is the code I’ve written:
model = NGramTester(N)
gram_model = [fn for fn in trained_grams if "model_" + str(N) in fn][0]
model.read_model(gram_model)
ngram = True
# Function to handle text updates with selected prediction
def update_text_with_prediction(input_text, chosen_word):
input_text = input_text.split(' ')
input_text[-1] = chosen_word
return gr.Textbox(input_text)
def get_predictions(input_text):
splitted_text = input_text.split(' ')
last_word = splitted_text[-1]
if len(splitted_text) == 1:
splitted_text.insert(0, START_SYMBOL)
# Obtain the last n - 1 words before the typed word
prev_words = splitted_text[-(model.n - 1):]
pred_words, _ = model.predict(prev_words, last_word, NUM_PREDICTIONS)
if len(pred_words) == 0:
empty_preds = gr.Row()
empty_preds.add(gr.Textbox(placeholder="No predictions", label="Predictions"))
return empty_preds
# Create new set of predictions.
new_predictions = gr.Row()
for word in pred_words:
button = gr.Button(word)
button.click(update_text_with_prediction,
inputs=[input_text, word],
outputs=input_text)
new_predictions.add(button)
return new_predictions
with gr.Blocks() as demo:
# Text input area
with gr.Row():
input_text = gr.Textbox(placeholder="Type your text here...", label="Input text")
with gr.Row():
predictions = gr.Row(gr.Textbox("No predictions"))
# Event handlers
input_text.change(fn=get_predictions, inputs=input_text, outputs=predictions)
# Launch the interface
demo.launch(share=True)
However, I don’t know how to handle the error:
Cannot call click outside of a gradio.Blocks context
Could I get some help with it?
Notes:
-
model.predict(...)
returns a usual Python list with the most
probable word predictions. All the prediction logic has been
implemented! -
The exists the possibility that there are no predictions available. In that case, I’d like the predictions box to display some text informing of the situation.
-
I just started today with
gradio
so any suggestions on cleaner
gradio
code are welcome.
Thanks!