| |
| import tkinter as tk |
| import numpy as np |
| from autocorrect_package.autocorrection import Autocorrection |
|
|
| class AutoCorrectApp(tk.Tk): |
| def __init__(self): |
| super().__init__() |
|
|
| |
| self.checker = Autocorrection("autocorrect_package/corpus.txt") |
|
|
| |
| self.input_box = tk.Text(self, wrap="word") |
| self.input_box.pack() |
|
|
| |
| self.suggestion_listbox = tk.Listbox(self) |
| self.suggestion_listbox.pack() |
|
|
| |
| self.input_box.bind("<KeyRelease>", self.on_key_release) |
|
|
| |
| self.input_box.bind("<space>", self.on_space_bar_press) |
|
|
| |
| self.suggestion_listbox.bind("<<ListboxSelect>>", self.on_listbox_select) |
|
|
| |
| self.current_word = "" |
|
|
| def on_key_release(self, event): |
| |
| cursor_position = self.input_box.index(tk.INSERT) |
|
|
| |
| current_line = self.input_box.get("insert linestart", cursor_position).split() |
|
|
| |
| if current_line: |
| self.current_word = current_line[-1] |
| else: |
| self.current_word = "" |
|
|
| |
| self.after(2000, self.autocorrect_suggestions) |
|
|
| def on_space_bar_press(self, event): |
| |
| if self.suggestion_listbox.curselection(): |
| return |
|
|
| |
| word = self.current_word.lower() |
|
|
| |
| corrections = self.checker.correct_spelling(word) |
|
|
| if corrections: |
| |
| probs = np.array([c[1] for c in corrections]) |
|
|
| |
| best_ix = np.argmax(probs) |
| correct = corrections[best_ix][0] |
|
|
| highest_prob_word = correct |
|
|
| |
| if highest_prob_word != word: |
| self.input_box.delete(f"insert-{len(word)}c", "insert") |
| self.input_box.insert("insert", highest_prob_word + "") |
|
|
| |
| print(f"Did you mean {highest_prob_word}?") |
|
|
| def autocorrect_suggestions(self): |
| |
| word = self.current_word.lower() |
|
|
| |
| corrections = self.checker.correct_spelling(word) |
|
|
| |
| self.suggestion_listbox.delete(0, tk.END) |
|
|
| |
| if corrections: |
| for correction in corrections: |
| self.suggestion_listbox.insert(tk.END, correction[0]) |
|
|
| def on_listbox_select(self, event): |
| |
| selected_word = self.suggestion_listbox.get(self.suggestion_listbox.curselection()) |
|
|
| |
| self.input_box.delete(f"insert-{len(self.current_word)}c", "insert") |
| self.input_box.insert("insert", selected_word + " ") |
|
|
| |
| self.suggestion_listbox.delete(0, tk.END) |
|
|
| def run(self): |
| |
| self.mainloop() |
|
|
| |
| if __name__ == "__main__": |
| app = AutoCorrectApp() |
| app.run() |