forked from dwiel/talon_community
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
280 lines (202 loc) · 6.94 KB
/
utils.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import string
import collections
import itertools
from talon import clip
from talon.voice import Str, Key, press
from time import sleep
import json
import os
mapping = json.load(open(os.path.join(os.path.dirname(__file__), "replace_words.json")))
mappings = collections.defaultdict(dict)
for k, v in mapping.items():
mappings[len(k.split(" "))][k] = v
punctuation = set(".,-!?")
def parse_word(word, force_lowercase=True):
word = str(word).lstrip("\\").split("\\", 1)[0]
if force_lowercase:
word = word.lower()
word = mapping.get(word, word)
return word
def replace_words(words, mapping, count):
if len(words) < count:
return words
new_words = []
i = 0
while i < len(words) - count + 1:
phrase = words[i : i + count]
key = " ".join(phrase)
if key in mapping:
new_words.append(mapping[key])
i = i + count
else:
new_words.append(phrase[0])
i = i + 1
new_words.extend(words[i:])
return new_words
def parse_words(m, natural=False):
if isinstance(m, list):
words = m
elif hasattr(m, "dgndictation"):
words = m.dgndictation[0]
else:
return []
# split compound words like "pro forma" into two words.
words = sum([word.split(" ") for word in words], [])
words = list(map(lambda current_word: parse_word(current_word, not natural), words))
words = replace_words(words, mappings[2], 2)
words = replace_words(words, mappings[3], 3)
return words
def join_words(words, sep=" "):
out = ""
for i, word in enumerate(words):
if i > 0 and word not in punctuation:
out += sep
out += str(word)
return out
def insert(s):
Str(s)(None)
def text(m):
insert(join_words(parse_words(m)).lower())
def spoken_text(m):
insert(join_words(parse_words(m, True)))
def sentence_text(m):
raw_sentence = join_words(parse_words(m, True))
sentence = raw_sentence[0].upper() + raw_sentence[1:]
insert(sentence)
def word(m):
try:
text = join_words(list(map(parse_word, m.dgnwords[0]._words)))
insert(text.lower())
except AttributeError:
pass
def surround(by):
def func(i, word, last):
if i == 0:
word = by + word
if last:
word += by
return word
return func
def rot13(i, word, _):
out = ""
for c in word.lower():
if c in string.ascii_lowercase:
c = chr((((ord(c) - ord("a")) + 13) % 26) + ord("a"))
out += c
return out
numeral_map = dict((str(n), n) for n in range(0, 20))
for n in range(20, 101, 10):
numeral_map[str(n)] = n
for n in range(100, 1001, 100):
numeral_map[str(n)] = n
for n in range(1000, 10001, 1000):
numeral_map[str(n)] = n
numeral_map["oh"] = 0 # synonym for zero
numeral_map["and"] = None # drop me
numerals = " (" + " | ".join(sorted(numeral_map.keys())) + ")+"
optional_numerals = " (" + " | ".join(sorted(numeral_map.keys())) + ")*"
def text_to_number(words):
tmp = [str(s).lower() for s in words]
words = [parse_word(word) for word in tmp]
result = 0
factor = 1
for word in reversed(words):
print("{} {} {}".format(result, factor, word))
if word not in numerals:
raise Exception("not a number: {}".format(words))
number = numeral_map[word]
if number is None:
continue
number = int(number)
if number > 10:
result = result + number
else:
result = result + factor * number
factor = (10 ** len(str(number))) * factor
return result
def m_to_number(m):
tmp = [str(s).lower() for s in m._words]
words = [parse_word(word) for word in tmp]
result = 0
factor = 1
for word in reversed(words):
if word not in numerals:
# we consumed all the numbers and only the command name is left.
break
result = result + factor * int(numeral_map[word])
factor = 10 * factor
return result
def text_to_range(words, delimiter="until"):
tmp = [str(s).lower() for s in words]
split = tmp.index(delimiter)
start = text_to_number(words[:split])
end = text_to_number(words[split + 1 :])
return start, end
number_conversions = {"oh": "0"} # 'oh' => zero
for i, w in enumerate(
["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
):
number_conversions[str(i)] = str(i)
number_conversions[w] = str(i)
number_conversions["%s\\number" % (w)] = str(i)
def parse_words_as_integer(words):
# TODO: Once implemented, use number input value rather than manually
# parsing number words with this function
# Ignore any potential non-number words
number_words = [w for w in words if str(w) in number_conversions]
# Somehow, no numbers were detected
if len(number_words) == 0:
return None
# Map number words to simple number values
number_values = list(map(lambda w: number_conversions[w.word], number_words))
# Filter out initial zero values
normalized_number_values = []
non_zero_found = False
for n in number_values:
if not non_zero_found and n == "0":
continue
non_zero_found = True
normalized_number_values.append(n)
# If the entire sequence was zeros, return single zero
if len(normalized_number_values) == 0:
normalized_number_values = ["0"]
# Create merged number string and convert to int
return int("".join(normalized_number_values))
def alternatives(options):
return " (" + " | ".join(sorted(map(str, options))) + ")+"
def select_single(options):
return " (" + " | ".join(sorted(map(str, options))) + ")"
def optional(options):
return " (" + " | ".join(sorted(map(str, options))) + ")*"
numeral_map = dict((str(n), n) for n in range(0, 20))
for n in [20, 30, 40, 50, 60, 70, 80, 90]:
numeral_map[str(n)] = n
numeral_map["oh"] = 0 # synonym for zero
numerals = " (" + " | ".join(sorted(numeral_map.keys())) + ")+"
optional_numerals = " (" + " | ".join(sorted(numeral_map.keys())) + ")*"
def preserve_clipboard(fn):
def wrapped_function(*args, **kwargs):
old = clip.get()
ret = fn(*args, **kwargs)
sleep(0.1)
clip.set(old)
return ret
return wrapped_function
@preserve_clipboard
def paste_text(text):
clip.set(text)
sleep(0.1)
press('cmd-v')
# The. following function is used to be able to repeat commands by following it by one or several numbers, e.g.:
# 'delete' + optional_numerals: repeat_function(1, 'delete'),
def repeat_function(numberOfWordsBeforeNumber, keyCode, delay=0):
def repeater(m):
line_number = parse_words_as_integer(m._words[numberOfWordsBeforeNumber:])
if line_number == None:
line_number = 1
for i in range(0, line_number):
sleep(delay)
press(keyCode)
return repeater
def delay(amount=0.1):
return lambda _: sleep(amount)