-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocorrect_win.py
242 lines (215 loc) · 8.48 KB
/
autocorrect_win.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import time
import keyboard
import pynput
import sys
import os
import subprocess
import configparser
import json
from ast import literal_eval as leval
from pynput.keyboard import Key
config = configparser.ConfigParser()
keycode = {"LEFTCTRL": Key.ctrl_l, "RIGHTCTRL": Key.ctrl_r, "LEFTSHIFT": Key.shift_l, "RIGHTSHIFT": Key.shift_r, "LEFTALT": Key.alt_l, "RIGHTALT": Key.alt_r}
ctrl_keycode = ["\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\t", "\n", "\x0b", "\x0c", "\r", "\x0e", "\x0f", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1a"]
def read_key_comb(config, config_key, default):
try:
if config.get("Main", config_key).upper() == "NONE":
return [None]
else:
key_comb = config.get("Main", config_key).upper().split(" + ")
ctrl = "LEFTCTRL" in key_comb or "RIGHTCTRL" in key_comb
return [keycode[x] if len(x)>1 else (ctrl_keycode[ord(x.lower())-97] if ctrl else x.lower()) for x in key_comb]
except:
return default
config.read("config.ini")
past_len = config.getint("Main", "past_len")
aspell_mode = config.get("Main", "aspell_mode")
debug = leval(config.get("Main", "debug"))
aspell_path = config.get("Windows", "aspell_path")
toast = config.get("Windows", "toast")
languages = config.get("Main", "languages").replace(", ", ",").split(",")
keymaps = config.get("Main", "keymaps").replace(", ", ",").split(",")
keymaps = config.get("Main", "custom").replace(", ", ",").split(",")
toggle_key = read_key_comb(config, "toggle_key", [Key.ctrl_l, Key.shift_l, "\x05"])
cycle_key = read_key_comb(config, "cycle_key", [Key.ctrl_l, Key.shift_l, "\x12"])
blacklist_key = read_key_comb(config, "blacklist_key", [Key.ctrl_l, Key.shift_l, "\x02"])
if toast == "win10":
from win10toast import ToastNotifier
toast = ToastNotifier()
elif toast == "win11":
import win11toast
mod_keys = (pynput.keyboard.Key.ctrl_l, pynput.keyboard.Key.ctrl_r)
cmd = [aspell_path, "-a", f"--sug-mode={aspell_mode}", f"--lang={languages[0]}"]
def spell_check(word):
aspell = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, error = aspell.communicate(word.encode())
try:
check = output.decode().split("\n")[1]
except Exception:
check = str(output).split("\\r\\n")[1]
if check == "*":
return None
else:
try:
return check.split(": ")[1].split(", ")[0]
except Exception:
return None
def delete(num):
for _ in range(num):
keyboard.press("backspace")
keyboard.release("backspace")
def press(key):
keyboard.press(key)
keyboard.release(key)
def type(word, end=None):
global keymap
word = word.translate(keymap)
for letter in word:
press(letter)
if end:
press(end)
def notify_send(header, message):
if toast == "win10":
toast.show_toast(header, message, duration=5, threaded=True)
elif toast == "win11":
win11toast.toast(header, message)
def add_to_blacklist(word):
try:
with open("blacklist.json", "r") as f:
blacklist = json.load(f)
except FileNotFoundError:
blacklist = []
if word:
blacklist.append(word)
with open("blacklist.json", "w") as f:
json.dump(blacklist, f, indent=2)
return blacklist
def load_keymap(keymap):
if keymap is not None:
with open(path + "keymaps/" + keymap + ".json", "r") as f:
keymap_raw = json.load(f)
return str.maketrans(keymap_raw), keymap_raw
else:
return str.maketrans({}), {}
def load_custom(custom):
if custom is not None:
with open(path + "custom/" + custom + ".json", "r") as f:
return {k.upper(): v for k, v in json.load(f).items()}
else:
return {}
dev = None
past = [None] * past_len
keybind_past = [None] * len(toggle_key)
backspace = None
enable = True
skip = False
lang = 0
blacklist = add_to_blacklist(None)
# load keymap and remove invalid keymaps
keymaps = [None if x == "None" else x for x in keymaps if (os.path.exists("keymaps/" + x + ".json") or x == "None")]
if len(keymaps) > len(languages):
keymaps = keymaps[:len(languages)]
if len(keymaps) < len(languages):
languages = languages[:len(keymaps)]
keymap, raw_keymap = load_keymap(keymaps[lang])
# load custom replacements and remove invalid ones
custom = [None if x == "None" else x for x in custom if (os.path.exists(path + "custom/" + x + ".json") or x == "None")]
if len(custom) > len(custom):
custom = keymaps[:len(custom)]
if len(keymaps) < len(languages):
custom.append(None)
custom_repl = load_custom(custom[lang])
# keyboard events
def on_release(key):
global enable, past, backspace, skip, keybind_past, cmd, blacklist
keybind_past = [None] * len(toggle_key)
if enable:
try:
if skip:
skip = False
else:
if key.char in raw_keymap.values():
key = [x for x in raw_keymap if raw_keymap[x] == letter][0]
past.append(key)
else:
past.append(key.char)
past.pop(0)
except AttributeError:
pass
# reset when: backspace, arrows
if key in (pynput.keyboard.Key.backspace, pynput.keyboard.Key.left, pynput.keyboard.Key.right, pynput.keyboard.Key.up, pynput.keyboard.Key.down):
backspace = True
# space and enter trigger
elif key in (pynput.keyboard.Key.space, pynput.keyboard.Key.enter):
if backspace:
backspace = None
else:
# check word
word = "".join([x for x in past if x is not None and len(x) == 1])
if word:
if word in blacklist:
correct = None
if debug:
print(f'Word "{word}" is found in blacklist')
elif word.upper() in custom_repl.keys():
correct = custom_repl[word.upper()]
if debug:
print(f'Word "{word}" is found in custom replacement')
else:
correct = spell_check(word)
else:
correct = None
# if word is bad
if correct:
if debug:
print(f"Word {word} corrected to: {correct}")
# delete old word
delete(len(word)+1)
# write corrected word
if key == pynput.keyboard.Key.space:
type(correct, "space")
elif key == pynput.keyboard.Key.enter:
type(correct, "enter")
elif debug:
print(f"Word {word} is OK")
past = [None] * past_len
elif skip:
skip = False
def on_press(key):
global enable, past, keybind_past, skip, cmd, lang, blacklist, keymap, keymap_raw, custom_repl
try:
key = key.char.lower()
except AttributeError:
pass
if keybind_past[-1] != key:
keybind_past.append(key)
keybind_past.pop(0)
# toggle autocorrect
if keybind_past == toggle_key:
enable = not enable
past = [None] * past_len
if enable:
message = "Automatic text corrections enabled"
else:
message = "Automatic text corrections disabled"
notify_send("Autocorrect", message)
# change language
if keybind_past == cycle_key:
lang += 1
if lang >= len(languages):
lang = 0
cmd = [aspell_path, "-a", f"--sug-mode={aspell_mode}", f"--lang={languages[lang]}"]
keymap, raw_keymap = load_keymap(keymaps[lang])
custom_repl = load_custom(custom[lang])
notify_send("Autocorrect", f"Changed language to {languages[lang]} and keymap to {keymaps[lang]}")
# blacklist word
if keybind_past == blacklist_key:
word = "".join([x for x in past if x is not None and len(x) == 1])
past = [None] * past_len
blacklist = add_to_blacklist(word)
notify_send("Autocorrect", f'Word "{word}" added to blacklist')
if any(x in mod_keys for x in keybind_past[:-1]):
# key is not typed
skip = True
with pynput.keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()