-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoicecontrol.py
1675 lines (1440 loc) · 66.4 KB
/
voicecontrol.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -- coding: utf8 --
"""
TODO:
- X11-Check vorm Mitschreiben
- Steckdose ansteuern
- Auf Raspi testen
"""
import psutil
import logging
from datetime import datetime
import threading, collections, queue, os, os.path
import deepspeech
import numpy as np
import pyaudio
import wave
import webrtcvad
from halo import Halo
import scipy
import sys
try:
import pyautogui
import pyperclip
import wmctrl
except Exception as e:
print(str(e))
from subprocess import check_output
import time
from urllib.request import urlopen
import random
import argparse
import os.path
import re
from colored import fg, bg, attr
import secrets
import zahlwort2num as w2n
import urllib.parse
import json
import wikipediaapi
from datetime import date, datetime
from babel.dates import format_date, format_datetime, format_time
import string
from pathlib import Path
import getpass
import tempfile
from datetime import datetime
import calendar
import signal
def signal_handler(sig, frame):
this_pid = os.getpid()
parent = psutil.Process(this_pid)
this_children = parent.children(recursive=True)
if len(this_children):
for child in this_children:
if not child.pid == this_pid:
try:
child.kill()
except Exception as e:
print(str(e))
else:
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def green_text(string):
print(str(fg('white')) + str(bg('green')) + str(string) + str(attr('reset')))
def red_text(string):
print(str(fg('white')) + str(bg('red')) + str(string) + str(attr('reset')))
def yellow_text(string):
print(str(fg('white')) + str(bg('yellow')) + str(string) + str(attr('reset')))
def blue_text(string):
print(str(fg('white')) + str(bg('blue')) + str(string) + str(attr('reset')))
logging.basicConfig(level=20)
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
class BaseFeatures():
def __init__(self):
self.original_sound_volume = self.get_current_audio_level()
self.home = str(Path.home())
self.assistant_name_file = self.home + "/.assistant_name"
self.default_city_file = self.home + "/.default_city"
self.ssh_x_server = self.home + "/.ssh_x_server"
def has_x_server (self):
retval = os.environ.get('DISPLAY')
if retval is None:
return False
else:
return True
def get_ssh_x_server (self):
return self.ssh_x_server
def get_ssh_x_server_connect(self):
yellow_text("Add " + self.ssh_x_server + " file with login credentials if you want to access X11 related data from another computer (like 'user@ip'). Don't forget to make ssh passwordless then!")
ssh_x_server_connect = self.read_first_line_of_file_if_exists(self.ssh_x_server, "ssh server", getpass.getuser() + "@localhost")
return ssh_x_server_connect
def get_assistant_name(self):
assistant_name = self.read_first_line_of_file_if_exists(self.assistant_name_file, "Assistentenname", "juli")
return assistant_name
def get_default_city(self):
default_city = self.read_first_line_of_file_if_exists(self.default_city_file, "Default-City", "Dresden")
return default_city;
def read_first_line_of_file_if_exists (self, filename, name, default):
if os.path.isfile(filename):
with open(filename) as f:
first_line = f.readline()
first_line = first_line.replace("\n", "")
return first_line
else:
red_text("Die Datei " + filename + " existiert nicht. Typ: " + str(name) + ", Default-Wert: " + str(default));
return default
def x_server_is_running(self):
self.run_command_get_output("echo $DISPLAY")
def save_current_audio_level_as_original(self):
self.original_sound_volume = self.get_current_audio_level()
def get_unixtime(self):
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
return unixtime
def run_command_get_output(self, command):
f = tempfile.NamedTemporaryFile(delete=False)
tmp = f.name
os.system(command + ' > ' + tmp)
stdout = open(tmp, 'r').read()
os.unlink(f.name)
stdout = stdout.rstrip("\n")
return stdout
def get_current_audio_level(self):
out = ''
command = "amixer -D pulse get Master | awk -F 'Left:|[][]' 'BEGIN {RS=\"\"}{ print $3 }'"
blue_text(command)
return self.run_command_get_output(command)
def save_original_volume_set_other_value (self, other_value):
self.original_sound_volume = self.get_current_audio_level()
self.set_audio_level(other_value)
def restore_original_sound_level(self):
self.set_audio_level(self.original_sound_volume)
def set_audio_level(self, volume):
command = "amixer set Master " + str(volume)
blue_text(command)
return self.run_command_get_output(command)
def remove_text_in_brackets(self, text):
ret = ''
skip1c = 0
skip2c = 0
for i in text:
if i == '[':
skip1c += 1
elif i == '(':
skip2c += 1
elif i == ']' and skip1c > 0:
skip1c -= 1
elif i == ')'and skip2c > 0:
skip2c -= 1
elif skip1c == 0 and skip2c == 0:
ret += i
return ret
def download_file_get_string (self, url):
yellow_text(url)
this_str = None
try:
downloaded = urlopen(url)
blue_text("Status-Code: " + str(downloaded.getcode()))
output = downloaded.read()
this_str = output.decode('utf-8')
except Exception as e:
red_text("FEHLER!!!")
red_text(str(e))
return this_str
def random_element_from_array(self, array):
return secrets.choice(array)
def run_system_command(self, command):
blue_text(command)
os.system(command)
class Features():
def __init__ (self, interact, controlkeyboard, textreplacements, guitools, basefeatures):
self.interact = interact
self.basefeatures = basefeatures
self.controlkeyboard = controlkeyboard
self.textreplacements = textreplacements
self.guitools = guitools
self.radio_streams = {
"(?:radio )?eine?s": {
"link": "https://www.radioeins.de/live.m3u",
"name": "Radio Eins"
},
"sachsen(\s*radio)?": {
"link": "http://avw.mdr.de/streams/284280-0_mp3_high.m3u",
"name": "Sachsenradio"
},
"deutschland\s*funk": {
"link": "https://st01.sslstream.dlf.de/dlf/01/64/mp3/stream.mp3",
"name": "Deutschlandfunk"
}
}
def speak_system_command(self, command):
pico2wave = " | pico2wave --lang de-DE --wave /tmp/Test.wav ; play /tmp/Test.wav; rm /tmp/Test.wav"
full_command = command + pico2wave
blue_text(full_command)
self.interact.vad_audio.stream.stop_stream()
self.basefeatures.run_system_command(full_command)
self.interact.vad_audio.stream.start_stream()
def get_weekday(self):
today = date.today()
return ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag")[today.weekday()]
def talk_weekday(self):
weekday = self.get_weekday()
self.interact.talk(weekday)
def talk_calendar_week (self):
calweek = date.today().isocalendar()[1]
self.interact.talk("Es ist die Kalenderwoche " + str(calweek))
def talk_current_date (self):
d = datetime.today()
date_string = "Heute ist " + self.get_weekday() + " der " + str(format_date(d, locale='de_DE'))
self.interact.talk(date_string)
def get_available_radio_names (self):
names = []
for key in self.radio_streams:
names.append(self.radio_streams[key]["name"])
return names
def read_wikipedia_article(self, article):
wiki_wiki = wikipediaapi.Wikipedia('de')
words = article.split(" ")
words_new = []
for word in words:
words_new.append(word.capitalize())
article = ' '.join(words_new)
page_py = wiki_wiki.page(article)
summary = page_py.summary
summary = summary.replace("[", "")
summary = summary.replace("]", "")
re.sub("[\(\[].*?[\)\]]", "", summary)
summary = self.basefeatures.remove_text_in_brackets(summary)
self.interact.talk(summary)
def start_dr_house (self):
self.basefeatures.run_system_command("vlc ~/mailserver/filme_und_serien/Dr-House/")
def bitcoin_price (self):
self.speak_system_command('echo "Ein Bitcoin = $(curl -s https://api.coindesk.com/v1/bpi/currentprice/usd.json | grep -o \'rate\\":\\"[^\\"]*\' | cut -d\\" -f3 | sed -e \"s/\..*//\") US Dollar" | sed -e "s/\,//"')
def grenzwert(self):
self.interact.talk("Seh ich aus wie WolframAlpha? Diese Aufgabe ist mir viel zu schwer")
def stop_radio(self):
this_pid = os.getpid()
parent = psutil.Process(this_pid)
for child in parent.children(recursive=True):
if not child.pid == this_pid:
try:
child.kill()
except Exception as e:
print(str(e))
def play_radio (self, regex, text):
radioname = '';
m = REMatcher(text)
#if m.match(r"(?:(?:v|sp)iel(?:e?r?)?|[nm]ach|star?te) radio (.+)(\s+a[nb])?"):
if regex is not None and m.match(regex):
radioname = m.group(1)
else:
radioname = text
radio_stream = None
radio_name = None
for regex in self.radio_streams:
if radio_stream is None:
mr = REMatcher(radioname)
if mr.match(regex):
radio_stream = self.radio_streams[regex]["link"]
radio_name = self.radio_streams[regex]["name"]
if radio_stream is not None:
self.interact.talk("Ich spiele " + str(radio_name) + " ab")
newpid = os.fork()
if newpid == 0:
self.basefeatures.run_system_command("cvlc " + str(radio_stream))
else:
pids = (os.getpid(), newpid)
print("Forked process, parent: %d, child: %d\n" % pids)
else:
self.interact.talk("Das Radio mit dem Namen " + str(radioname) + " ist mir nicht bekannt")
def how_are_you(self):
array = [
"Ich kann mich aktuell nicht beklagen. Wahrscheinlich deshalb, weil ich nur eine Maschine bin und gar nichts fühle.",
"Wenn ich ganz tief in mich schaue, sehe ich nur Nullen und Einsen",
"Mein aktueller Status ist in Ordnung, danke der Nachfrage!",
"Wenn in meiner Software noch Fehler sind, dann merke ich sie gerade zumindest nicht!"
]
self.interact.talk(self.basefeatures.random_element_from_array(array))
def start_editor (self):
self.basefeatures.run_system_command("kate &")
def go_to_end_of_line (self):
self.controlkeyboard.hotkey('end')
def save (self):
if self.guitools.is_console:
self.controlkeyboard.hotkey('esc')
self.controlkeyboard.hotkey(':')
self.controlkeyboard.hotkey('w')
self.controlkeyboard.hotkey('q')
self.controlkeyboard.hotkey('!')
self.controlkeyboard.hotkey('enter')
else:
self.controlkeyboard.hotkey('ctrl', 's')
def suicide (self):
self.interact.talk("ok, ich beende mich selbst")
sys.exit(0)
def get_weather_json (self, place):
url = 'https://wttr.in/' + urllib.parse.quote(str(place)) + '?format=j1&lang=de'
this_str = self.basefeatures.download_file_get_string(url)
datastore = None
if not this_str is None:
datastore = json.loads(this_str)
return datastore
def talk_current_weather (self, place):
datastore = self.get_weather_json(place)
if not datastore is None:
current_feels_like_temp = datastore['current_condition'][0]["FeelsLikeC"]
current_humidity = datastore['current_condition'][0]["humidity"]
current_temp = datastore['current_condition'][0]["temp_C"]
current_weather_desc = datastore['current_condition'][0]["lang_de"][0]["value"]
current_windspeed = datastore['current_condition'][0]["windspeedKmph"]
temperature_string = ''
if current_feels_like_temp == current_temp:
temperature_string = "einer Temperatur von %s Grad" % (current_temp)
else:
temperature_string = "einer realen Temperatur von %s Grad und einer gefühlten von %s Grad" % (current_temp, current_feels_like_temp)
weather_string = "In %s ist es %s bei %s. Die Windgeschwindigkeit ist %s km/h bei einer Luftfeuchtigkeit von %s Prozent" % (place, current_weather_desc, temperature_string, current_windspeed, current_humidity)
self.interact.talk(weather_string)
else:
self.interact.talk("Aktuell krieg ich die Wetterdaten aus technischen Gründen leider nicht. Tut mir leid.")
def talk_weather_tomorrow (self, place):
datastore = self.get_weather_json(place)
if not datastore is None:
(mintemp, maxtemp, tag, hourly_status) = self.create_weather_string(datastore, 1)
weather_string = "In %s liegt die Temperatur morgen zwischen %s und %s Grad. %s %s" % (place, mintemp, maxtemp, tag, hourly_status)
self.interact.talk(weather_string)
else:
self.interact.talk("Aktuell krieg ich die Wetterdaten aus technischen Gründen leider nicht. Tut mir leid.")
def talk_weather_the_day_after_tomorrow (self, place):
datastore = self.get_weather_json(place)
if not datastore is None:
(mintemp, maxtemp, tag, hourly_status) = self.create_weather_string(datastore, 2)
weather_string = "In %s liegt die Temperatur übermorgen zwischen %s und %s Grad. %s %s" % (place, mintemp, maxtemp, tag, hourly_status)
self.interact.talk(weather_string)
else:
self.interact.talk("Aktuell krieg ich die Wetterdaten aus technischen Gründen leider nicht. Tut mir leid.")
def create_weather_string (self, datastore, number):
maxtemp = datastore['weather'][number]["maxtempC"]
mintemp = datastore['weather'][number]["mintempC"]
weather_status = []
hourly = datastore['weather'][number]["hourly"]
for item in hourly:
this_item = item['lang_de'][0]['value']
if len(weather_status) == 0 or weather_status[len(weather_status) - 1] != this_item:
weather_status.append(this_item)
tag = "Es wird"
hourly_status = ""
if len(weather_status) > 1:
hourly_status = "erst "
tag = "Über den Tag verteilt wird es"
hourly_status = hourly_status + ", dann ".join(weather_status)
return (mintemp, maxtemp, tag, hourly_status)
def calculate(self, text):
math_text = self.textreplacements.replace_in_formula_mode(text)
m = REMatcher(math_text)
if m.match("^\d+(?:,\d+)?((\+|-|\*|/)\d+(?:,\d+)?)$"):
self.controlkeyboard.copy(math_text)
self.basefeatures.run_system_command('qalc -t $(xsel --clipboard) | sed -e "s/ or / oder /"')
self.speak_system_command('qalc -t $(xsel --clipboard) | sed -e "s/ or / oder /g" | sed -e "s/-/ minus /g" | sed -e "s/\/ durch //g" | sed -e "s/^/' + str(math_text) + ' gleich/" | sed -e "s/\\*/ mal /"')
else:
red_text("Erkannt: " + str(math_text))
self.interact.talk("Diese Rechnung ist mir zu kompliziert oder ich habe sie nicht richtig verstanden");
def solve_equation (self):
self.controlkeyboard.hotkey('home')
self.controlkeyboard.hotkey('shift', 'end')
self.controlkeyboard.hotkey('ctrl', 'c')
self.speak_system_command('qalc -t $(xsel --clipboard) | sed -e "s/ or / oder /" | sed -e "s/-/ minus /"')
def read_aloud(self):
self.controlkeyboard.hotkey('ctrl', 'a')
self.controlkeyboard.hotkey('ctrl', 'c')
self.controlkeyboard.hotkey('ctrl', 'a')
self.controlkeyboard.hotkey('ctrl', 'c')
self.controlkeyboard.hotkey('right')
self.speak_system_command('xsel --clipboard | tr "\n" " "')
def lalelu (self):
self.interact.talk("Nur der Mann im Mond hört zu")
def lalalalala(self):
self.interact.talk("La la la la la")
def read_line_aloud(self):
self.guitools.select_current_line()
self.controlkeyboard.hotkey('ctrl', 'c')
self.speak_system_command('xsel --clipboard | tr "\n" " "')
def say_something_philosophical (self):
array = [
"Das ontisch Nächste ist das ontologisch Fernste",
"Jedes Wort ist ein Vorurteil",
"Man verdirbt einen Jüngling am sichersten, wenn man ihn verleitet, den Gleichdenkenden höher zu achten als den Andersdenkenden.",
]
self.interact.talk(self.basefeatures.random_element_from_array(array))
def random_string(self, string_length=16):
letters = string.ascii_letters + string.digits
return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(string_length))
def say_current_sound_volume(self):
audio_level = self.basefeatures.get_current_audio_level()
self.interact.talk(audio_level)
def create_password(self):
random_string = self.random_string(25)
print("Das zufällig generierte Passwort ist: " + random_string)
self.controlkeyboard.copy(random_string)
self.controlkeyboard.copy(random_string)
self.interact.talk("Ein Passwort wurde erstellt und in das Clipboard kopiert")
def favourite_song (self):
array = [
"Monoton und Minimal von Welle Erdball",
"Digital ist Besser von Tocotronic",
"Starless von King Krimson",
"Technologik von Däft Pank"
]
self.interact.talk(self.basefeatures.random_element_from_array(array))
def hello (self):
self.interact.talk("Hallo, " + os.getenv("USER"))
def tell_day (self):
from datetime import date
heute = date.today()
string_day = ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag")[heute.weekday()]
self.interact.talk("Heute ist " + string_day)
def tell_time (self):
now = datetime.now()
current_hour = now.strftime("%H")
current_minute = now.strftime("%M")
string_time = str(current_hour) + " Uhr " + str(current_minute)
self.interact.talk(string_time)
def tell_joke(self):
array = [
"Was ist weiß und steht hinter einem Baum? Eine scheue Milch",
"Gott sprach: Es werde Licht! Tschack Norris antwortete! Sag bitte!",
"Kommt ein Wektor zur Drogenberatung: Hilfe, ich bin line ar abhängig.",
"Was macht ein Mathematiker im Garten? Wurzeln ziehen.",
"Mathematiker sterben nie! sie verlieren nur einige ihrer Funktionen.",
"Wie viele Informatiker braucht man, um eine Glühbirne zu wechseln? Keinen, das ist ein Hardwärproblem!",
"Linux wird nie das meistinstallierte Betriebssystem sein, wenn man bedenkt, wie oft man Windows neu installieren muss!",
"Wie viele Glühbirnen braucht man, um eine Glühbirne zu wechseln? Genau zwei, die Alte und die Neue.",
"5 von 4 Leuten haben Probleme mit Mathematik!",
"Sagt ein Mathestudent zum Kommilitonen: Ich habe gehört, die Ehe des Professors soll sehr unglücklich sein! Meint der andere: Das wundert mich nicht. Er ist Mathematiker, und sie unberechenbar.",
"Was ist die Lieblingsbeschäftigung von Bits und Bytes? Busfahren.",
"Der kürzeste Programmiererwitz: Gleich bin ich fertig!",
"Ein Informatiker schiebt einen Kinderwagen durch den Park. Kommt ein älteres Ehepaar und fragt: Junge oder Mädchen? Da sagt der Informatiker: Richtig!"
]
self.interact.talk(self.basefeatures.random_element_from_array(array))
class TextReplacements():
def replace_in_text_mode (self, text):
text = text.replace("komma", ",")
text = text.replace("ausrufezeichen", "!")
text = text.replace("punkt", ".")
text = text.replace("neue zeile", "\n")
text = text.replace("neuer zeile", "\n")
text = text.replace("neu zeile", "\n")
text = text.replace("leerzeichen", " ")
text = text.replace("geschweifte klammer auf", "{")
text = text.replace("geschweifte klammer zu", "}")
text = text.replace("eckige klammer auf", "[")
text = text.replace("eckige klammer zu", "]")
text = text.replace("klammer auf", "(")
text = text.replace("klammer zu", ")")
text = text.replace(" ,", ",")
text = text.replace(" !", "!")
text = text.replace(" .", ".")
text = text.replace(" ", " ")
text = text.replace("\n ", "\n")
text = text.replace(" \n", "\n")
return text
def replace_in_formula_mode(self, text):
text = text.replace("ein hundert", "100")
text = text.replace("zweihundert", "200")
text = text.replace("zwei hundert", "200")
text = text.replace("drei hundert", "300")
text = text.replace("dreihundert", "300")
text = text.replace("vierhundert", "400")
text = text.replace("vier hundert", "400")
text = text.replace("fünfhundert", "500")
text = text.replace("fünf hundert", "500")
text = text.replace("sechs hundert", "600")
text = text.replace("sechshundert", "600")
text = text.replace("sieben hundert", "700")
text = text.replace("siebenhundert", "700")
text = text.replace("acht hundert", "800")
text = text.replace("achthundert", "800")
text = text.replace("neun hundert", "900")
text = text.replace("neunhundert", "900")
text = text.replace("hundert", "100")
text = text.replace("hundert", "100")
text = text.replace("eine million", "1000000")
text = text.replace("ein million", "1000000")
text = text.replace("einmillion", "1000000")
text = text.replace("million", "1000000")
words = text.split(" ")
words_new = []
for word in words:
try:
word = w2n.convert(word)
except Exception as e:
pass
words_new.append(str(word))
text = ' '.join(words_new)
text = text.replace("null", "0")
text = text.replace("eins", "1")
text = text.replace("zwei", "2")
text = text.replace("drei", "3")
text = text.replace("vier", "4")
text = text.replace("von", "5")
text = text.replace("fünf", "5")
text = text.replace("sechs", "6")
text = text.replace("sieben", "7")
text = text.replace("acht", "8")
text = text.replace("neun", "9")
text = text.replace("zehn", "10")
text = text.replace("elf", "11")
text = text.replace("zwölf", "12")
text = text.replace("dreizehn", "13")
text = text.replace("vierzehn", "14")
text = text.replace("fünfzehn", "15")
text = text.replace("sechszehn", "16")
text = text.replace("siebzehn", "17")
text = text.replace("achtzehn", "18")
text = text.replace("neunzehn", "19")
text = text.replace("zwanzig", "20")
text = text.replace("komma", ",")
text = text.replace("plus", "+")
text = text.replace("wurzel", "sqrt ")
text = text.replace(" ex ", "x")
text = text.replace("fluss", "+")
text = text.replace("hoch", "^")
text = text.replace("minus", "-")
text = text.replace("gleich", "=")
text = text.replace("mal", "*")
text = text.replace("geteiltdurch", "/")
text = text.replace("geteilt durch", "/")
text = text.replace(" ", "")
text = text.replace("geschweifte klammer auf", "{")
text = text.replace("geschweifteklammerauf", "{")
text = text.replace("geschweifte klammer zu", "}")
text = text.replace("geschweifteklammerzu", "}")
text = text.replace("eckige klammer auf", "[")
text = text.replace("eckigeklammerauf", "[")
text = text.replace("eckige klammer zu", "]")
text = text.replace("eckigeklammerzu", "]")
text = text.replace("klammer auf", "(")
text = text.replace("klammerauf", "(")
text = text.replace("klammer zu", ")")
text = text.replace("klammerzu", ")")
text = text.replace("ausrufezeichen", "!")
text = text.replace("fakultät", "!")
return text
class Interaction():
def __init__ (self, vad_audio, controlkeyboard, basefeatures):
self.vad_audio = vad_audio
self.controlkeyboard = controlkeyboard
self.consolemode = False
self.basefeatures = basefeatures
self.ssh_x_server_connect = self.basefeatures.get_ssh_x_server_connect()
def is_console(self):
self.consolemode = True
def is_not_console(self):
self.consolemode = False
def talk(self, something):
yellow_text(str(something))
if not something == "":
self.vad_audio.stream.stop_stream()
self.basefeatures.run_system_command('pico2wave --lang de-DE --wave /tmp/Test.wav "' + str(something) + '" ; play /tmp/Test.wav; rm /tmp/Test.wav')
self.vad_audio.stream.start_stream()
def can_you_hear_me(self):
array = [
"Ja, kann ich",
"Ja, sonst könnte ich dir auch nicht antworten",
"Nein. ähhh Doch. Ich meine ja."
]
self.talk(self.basefeatures.random_element_from_array(array))
def do_you_hear_me (self):
self.talk("Ja, ich höre dich")
def play_sound_ok(self):
self.play_sound(os.path.dirname(os.path.realpath(__file__)) + "/bleep.wav")
def play_sound_not_ok(self):
self.play_sound(os.path.dirname(os.path.realpath(__file__)) + "/line_end.wav")
def play_sound (self, path):
self.vad_audio.stream.stop_stream()
if os.path.isfile(path):
self.basefeatures.run_system_command("play " + path)
else:
self.talk("Die Datei " + str(path) + " konnte nicht gefunden werden!")
self.vad_audio.stream.start_stream()
def type_unicode(self, word):
if self.basefeatures.has_x_server():
self.controlkeyboard.copy(word)
if self.consolemode:
self.controlkeyboard.hotkey("ctrl", "shift", "v")
else:
self.controlkeyboard.hotkey("ctrl", "v")
else:
red_text("No X11")
class ControlKeyboard():
def copy(self, word):
word_debug = word
word_debug = word_debug.replace("\n", "\\n")
yellow_text("Copying `" + str(word_debug) + "` to clipboard")
pyperclip.copy(word)
pyperclip.copy(word)
def hotkey(self, *argv):
yellow_text("Pressing `" + ' + '.join(argv) + "`")
pyautogui.hotkey(*argv)
class GUITools():
def __init__ (self, interact):
self.interact = interact
self.consolemode = False
def is_console(self):
self.interact.consolemode = True
self.consolemode = True
def is_not_console(self):
self.interact.consolemode = False
self.consolemode = False
def start_browser(self):
self.interact.basefeatures.run_system_command("firefox")
def toggle_volume(self):
self.interact.talk("OK")
command = "amixer set Master toggle"
blue_text(command)
self.interact.basefeatures.run_system_command(command)
def volume_up (self):
self.interact.controlkeyboard.hotkey('volumeup')
def volume_down (self):
self.interact.controlkeyboard.hotkey('volumedown')
def say_current_window(self):
self.interact.talk(self.get_current_window())
def switch_window (self):
self.interact.controlkeyboard.hotkey('alt', 'tab')
time.sleep(1)
self.say_current_window()
def next_tab (self):
self.interact.controlkeyboard.hotkey('ctrl', 'tab')
time.sleep(1)
self.say_current_window()
def get_current_window (self):
out = b''
if os.path.isfile(self.interact.basefeatures.get_ssh_x_server()):
out = check_output(['ssh', self.interact.basefeatures.get_ssh_x_server_connect(), 'env DISPLAY=:0 XAUTHORITY=/home/$USER/.Xauthority xdotool getwindowfocus getwindowname'])
else:
out = check_output(["xdotool", "getwindowfocus", "getwindowname"])
this_str = out.decode("utf-8")
return this_str
def all_windows(self):
Window = wmctrl.Window
x = Window.list()
for wn in Window.list():
self.interact.talk(wn.wm_name)
def close_tab(self):
self.interact.controlkeyboard.hotkey('ctrl', 'w')
def previous_tab(self):
self.interact.controlkeyboard.hotkey('ctrl', 'shift', 'tab')
time.sleep(1)
self.interact.talk(self.get_current_window())
def mark_and_delete_all(self):
self.interact.controlkeyboard.hotkey('ctrl', 'a')
self.interact.controlkeyboard.hotkey('del')
def repeat (self):
self.interact.controlkeyboard.hotkey('ctrl', 'y')
def escape (self):
self.interact.controlkeyboard.hotkey('esc')
def new_tab(self):
self.interact.controlkeyboard.hotkey('ctrl', 't')
def new_window(self):
self.interact.controlkeyboard.hotkey('ctrl', 'n')
def close_window(self):
self.interact.controlkeyboard.hotkey('alt', 'f4')
def copy (self):
self.interact.controlkeyboard.hotkey('ctrl', 'c')
def select_all(self):
self.interact.controlkeyboard.hotkey('ctrl', 'a')
def undo (self):
self.interact.controlkeyboard.hotkey('ctrl', 'z')
def cut(self):
self.interact.controlkeyboard.hotkey('ctrl', 'x')
def delete(self):
self.interact.controlkeyboard.hotkey('del')
def select_current_line(self):
self.interact.controlkeyboard.hotkey('home')
self.interact.controlkeyboard.hotkey('shift', 'end')
def delete_current_line (self):
self.select_current_line()
self.delete()
def paste (self):
if self.consolemode:
self.interact.controlkeyboard.hotkey('ctrl', 'shift', 'v')
else:
self.interact.controlkeyboard.hotkey('ctrl', 'v')
def delete_last_word(self):
self.interact.controlkeyboard.hotkey('ctrl', 'backspace')
def press_enter(self):
self.interact.controlkeyboard.hotkey('enter')
def press_space(self):
self.interact.controlkeyboard.hotkey('space')
class Routines():
def __init__ (self, guitools, interact, features):
self.guitools = guitools
self.interact = interact
self.features = features
def morning_routine(self):
self.interact.talk("Guten Morgen")
self.features.talk_current_date()
self.features.talk_calendar_week()
self.features.talk_current_weather(self.features.basefeatures.get_default_city())
self.features.play_radio(None, "radio eins")
class AnalyzeAudio ():
def __init__ (self, guitools, interact, features, routines):
self.guitools = guitools
self.interact = interact
self.features = features
self.routines = routines
self.regexes = {
"^(?:(?:wiederhole was ich sage)|(?:sprich [wm]ir nach))$": {
"isfake": 1,
"help": "Spricht das, was gesagt worden ist, erneut aus",
"say": ["Wiederhole was ich sage", "Sprich mir nach"]
},
"^konsolenmodus aktivieren$": {
"isfake": 1,
"help": "Startet den Konsolen-Modus",
"say": ["Konsolenmodus aktivieren"]
},
"^konsolenmodus deaktivieren$": {
"isfake": 1,
"help": "Deaktiviert den Konsolen-Modus",
"say": ["Konsolenmodus deaktivieren"]
},
"^formel eingeben$": {
"isfake": 1,
"help": "Startet den Formel-Modus",
"say": ["Formel eingeben"]
},
"^text eingeben$": {
"isfake": 1,
"help": "Beendet den Formel-Modus und gibt wieder normalen Text ein",
"say": ["Text eingeben"]
},
"^mitschreiben$": {
"isfake": 1,
"help": "Tippt das, was gesagt worden ist, über eine virtuelle Tastatur ein",
"say": ["Mitschreiben"]
},
"^nicht mehr mitschreiben$": {
"isfake": 1,
"help": "Hört auf mitzuschreiben",
"say": ["Nicht mehr mitschreiben"]
},
"^leiser$": {
"fn": "self.guitools.volume_down",
"help": "Lautstärke leiser machen",
"say": ["leiser"]
},
"^lauter$": {
"fn": "self.guitools.volume_up",
"help": "Lautstärke lauter machen",
"say": ["lauter"]
},
"(?:(?:(?:(?:ka(?:nn|m)st\s*)?du )?(?:mich|nicht) hören))$": {
"fn": "self.interact.can_you_hear_me",
"help": "Antwortet, wenn das Gerät dich hören kann",
"say": ["Kannst du mich hören?"]
},
"^(?:(?:hörst du mich))$": {
"fn": "self.interact.do_you_hear_me",
"help": "Antwortet, wenn das Gerät dich hören kann",
"say": ["Hörst du mich?"]
},
"^star?te internet$": {
"fn": "self.guitools.start_browser",
"help": "Startet einen Internet-Browser",
"say": ["Starte Interent"]
},
"(?:wochentag|welcher\s*tag)": {
"fn": "self.features.talk_weekday",
"help": "Sagt, welcher Wochentag ist",
"say": ["Welcher Wochentag ist?"]
},
"kalenderwoche": {
"fn": "self.features.talk_calendar_week",
"help": "Sagt, welches Kalenderwoche ist",
"say": ["Welche Kalenderwoche ist?"]
},
"^.*datum ist heute$": {
"fn": "self.features.talk_current_date",
"help": "Sagt, welches Datum heute ist",
"say": ["Welches Datum ist heute?"]
},
"^alles vorlesen$": {
"fn": "self.features.read_aloud",
"help": "Lese vor, was gerade an markierbarem Text vor dir ist",
"say": ["Alles vorlesen"]
},
"^(?:diese|aktuelle?)\s*zeile\s*vorlesen$": {
"fn": "self.features.read_line_aloud",
"help": "Lese die aktuelle Zeile vor",
"say": ["Diese Zeile vorlesen", "Aktuelle Zeile vorlesen"]
},
"^löschen$": {
"fn": "self.guitools.delete",
"help": "Drücke die ENTF Taste",
"say": ["Löschen"]
},
"^(?:aktuelle|dieser?) zeile (?:auswählen|markieren)$": {
"fn": "self.guitools.select_current_line",
"help": "Aktuelle Zeile auswählen",
"say": ["Aktuelle Zeile auswählen", "Diese Zeile auswählen", "Aktuelle Zeile markieren", "Diese Zeile markieren"]
},
"^(?:dieser?|aktuelle) zeile löschen$": {
"fn": "self.guitools.delete_current_line",
"help": "Aktuelle Zeile löschen",
"say": ["Aktuelle Zeile löschen", "Diese Zeile löschen"]
},
"^aus\s*rechnen$": {
"fn": "self.features.solve_equation",
"help": "Aktuelle Zeile als Formel betrachten und ausrechnen",
"say": ["Ausrechnen"]
},
"^wieder\s*holen$": {
"fn": "self.guitools.repeat",
"help": "Hole die letzte rückgängig gemachte Änderung wieder",
"say": ["Wiederholen"]
},
"^abbrechen$": {
"fn": "self.guitools.escape",
"help": "Bricht aktuellen Vorgang ab (mit ESC)",
"say": ["Abbrechen"]
},
"^kopieren$": {
"fn": "self.guitools.copy",
"help": "Kopiere die aktuelle Auswahl",
"say": ["Kopieren"]
},
"^(?:schließe (?:fenster|elster|fester))|(?:(?:fenster|elster|fester) schließen)$": {
"fn": "self.guitools.close_window",
"help": "Schließe aktuelles Fenster",
"say": ["Schließe Fenster", "Fenster schließen"]
},