-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoty.py
executable file
·1964 lines (1767 loc) · 80.5 KB
/
doty.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
#!/usr/bin/env python3
import collections
import ctypes
import datetime
import logging
import subprocess
import multiprocessing
import threading
import functools
import hashlib
import html
import io
import itertools
import json
import os
import os.path
import queue
import random
import signal
import ssl
import struct
import subprocess
import tempfile
import time
import wave
import uuid
from enum import (
Enum,
auto,
)
import contexttimer
import googleapiclient.discovery
import irc.client
import irc.connection
import jsonschema
import larynx
import numpy
import requests
import samplerate
import setproctitle
import snips_nlu
import wolframalpha
import yaml
from bs4 import BeautifulSoup
from fuzzywuzzy import process
from google.cloud import texttospeech as gcloud_texttospeech
from numpy_ringbuffer import RingBuffer
import pymumble_py3 as pymumble
from pymumble_py3.constants import (
PYMUMBLE_AUDIO_PER_PACKET,
PYMUMBLE_SAMPLERATE,
PYMUMBLE_CLBK_CONNECTED,
PYMUMBLE_CLBK_USERCREATED,
PYMUMBLE_CLBK_USERUPDATED,
PYMUMBLE_CLBK_USERREMOVED,
PYMUMBLE_CLBK_CHANNELCREATED,
PYMUMBLE_CLBK_CHANNELUPDATED,
PYMUMBLE_CLBK_CHANNELREMOVED,
PYMUMBLE_CLBK_TEXTMESSAGERECEIVED,
PYMUMBLE_CLBK_SOUNDRECEIVED,
)
from pymumble_py3.errors import (
UnknownChannelError,
)
import stt as coqui_speechtotext
import TTS as coqui_texttospeech
from watson_developer_cloud import SpeechToTextV1 as watson_speechtotext
APP_NAME = 'doty'
LOG_LEVEL = logging.INFO
# this must be less than PYMUMBLE_AUDIO_PER_PACKET (0.02)
SHORT_POLL = PYMUMBLE_AUDIO_PER_PACKET / 2
LONG_POLL = 0.1
ZW_SPACE = u'\u200B'
# https://www.isip.piconepress.com/projects/speech/software/tutorials/production/fundamentals/v1.0/section_02/s02_01_p05.html
WAV_HEADER_LEN = 44
# https://cloud.google.com/speech-to-text/quotas
MAX_TRANSCRIPTION_TIME = 60.0
BASE_CONFIG_FILENAME = 'config.yml.example'
SCHEMA_FILENAME = 'config.schema'
SOUNDCHUNK_SIZE = 1920
AUDIO_CHANNELS = 1
SAMPLE_FRAME_FORMAT = '<h'
SAMPLE_FRAME_SIZE = struct.calcsize(SAMPLE_FRAME_FORMAT)
VOLUME_ADJUSTMENT_STEP = 0.2
DEFAULT_MEDIA_VOLUME = 0.5
signal.signal(signal.SIGINT, signal.SIG_IGN)
logging.basicConfig(
level=LOG_LEVEL,
format='%(asctime)s.%(msecs)03d [%(process)07d] %(levelname)-7s %(name)s: %(message)s',
datefmt='%Y-%m-%dT%H:%M:%S',
)
logging.captureWarnings(True)
def multiprocessify(func):
@functools.wraps(func)
def wrapper(*pargs, **kwargs):
proc = multiprocessing.Process(target=func, args=pargs, kwargs=kwargs)
proc.start()
return proc
return wrapper
def getWorkerLogger(worker_name, level=logging.DEBUG):
log = logging.getLogger('{}.{}'.format(APP_NAME, worker_name))
log.setLevel(level)
return log
def deep_merge_dict(a, b):
for k, v in b.items():
if isinstance(b[k], dict):
if k in a:
if not isinstance(a[k], dict):
raise ValueError('Non-matching types for key: {}'.format(k))
else:
a[k] = deep_merge_dict(a[k], b[k])
continue
a[k] = b[k]
return a
log = getWorkerLogger('main')
def normalize_callback_args(callback_type, args):
if callback_type == PYMUMBLE_CLBK_TEXTMESSAGERECEIVED:
return ({
'actor': args[0].actor,
'channel_id': list(args[0].channel_id),
'message': BeautifulSoup(args[0].message.strip(), 'html.parser').get_text(),
},)
elif callback_type == PYMUMBLE_CLBK_USERREMOVED:
return (dict(args[0]), {'session': args[1].session})
else:
return tuple([dict(e) if isinstance(e, dict) else e for e in args])
def denote_callback(clbk_type):
def outer_wrapper(func):
@functools.wraps(func)
def inner_wrapper(*args):
return func(clbk_type, *args)
return inner_wrapper
return outer_wrapper
generate_uuid = lambda: str(uuid.uuid4())
sha1sum = lambda data: hashlib.sha1(data if type(data) in (bytes, bytearray) else data.encode('utf-8')).hexdigest()
group_iter = lambda iterable, group_size: zip(*[iter(iterable)] * group_size)
def denotify_username(username):
if len(username) > 1:
return ZW_SPACE.join([username[0], username[1:-1], username[-1]]).replace(ZW_SPACE * 2, ZW_SPACE)
else:
return username
def audio_resample(buf, src_sr, dest_sr, method='sinc_best'):
sr_ratio = float(dest_sr) / src_sr
return samplerate.resample(buf, sr_ratio, converter_type=method).astype(numpy.int16)
def halt_process(proc):
try:
# only available in 3.7+
proc.kill()
except:
proc.terminate()
class QueuePipe:
@staticmethod
def wait(*queue_pipes, timeout=None):
return [qp for qp in queue_pipes if qp._in._reader in \
multiprocessing.connection.wait([qp._in._reader for qp in queue_pipes], timeout)]
def __init__(self):
self._in = multiprocessing.Queue()
self._out = multiprocessing.Queue()
self._buffer = []
self._in.cancel_join_thread()
self._out.cancel_join_thread()
def __setstate__(self, state):
super().__setstate__(state)
self._swap()
def send(self, data):
return self._out.put(data)
def recv(self):
try:
return self._buffer.pop()
except IndexError:
return self._in.get()
def poll(self, timeout=None):
try:
self._buffer.insert(0, self._in.get(timeout=timeout))
return True
except queue.Empty:
return False
def _swap(self):
self._in, self._out = self._out, self._in
def join(self):
try:
self._out.close()
self._out.join_thread()
except Exception: pass
class AssignableRingBuffer(RingBuffer):
def _normalize_slice(self, idx):
if idx.step not in (None, 1):
raise IndexError('Slice stepping not supported')
if idx.start is None:
idx = slice(0, idx.stop, idx.step)
elif idx.start < 0:
idx = slice(self._capacity + idx.start, idx.stop, idx.step)
if idx.stop in (None, 0):
idx = slice(idx.start, self._capacity, idx.step)
elif idx.stop < 0:
idx = slice(idx.start, self._capacity + idx.stop, idx.step)
return idx
def __setitem__(self, idx, value):
if isinstance(idx, slice):
idx = self._normalize_slice(idx)
assert (idx.stop - idx.start) == len(value), 'len(slice) != len(value): idx.start={} idx.stop={} diff={} len(value)={}'.format(idx.start, idx.stop, idx.stop - idx.start, len(value))
assert len(value) < self._capacity, 'slice too large: len(value)={}'.format(len(value))
# first chunk
sl_start = (self._left_index + idx.start) % self._capacity
sl_end = (self._left_index + idx.stop) % self._capacity
if sl_start < sl_end:
# simple case, doesn't wrap
self._arr[sl_start:sl_end] = value
else:
sl1 = value[:len(self._arr[sl_start:])]
self._arr[sl_start:] = sl1
self._arr[:sl_end] = value[len(sl1):]
elif isinstance(idx, int):
if idx >= 0:
self._arr[self._left_index+idx % self._capacity] = value
else:
self._arr[self._capacity+idx] = value
else:
raise IndexError('Invalid index type: %s'.format(idx))
class MixingBuffer:
MIN_SILENCE_EXTENSION = 0.5
DTYPE_SHORT = numpy.dtype(SAMPLE_FRAME_FORMAT)
DTYPE_FLOAT = numpy.float32
@staticmethod
def _mix_frames(left, right):
SCALE_VALUE = (2 ** ((SAMPLE_FRAME_SIZE * 8) - 1)) - 1
scale_factor = 1/SCALE_VALUE
left = left.astype(MixingBuffer.DTYPE_FLOAT) * scale_factor
right = right.astype(MixingBuffer.DTYPE_FLOAT) * scale_factor
out = (left + right) - (left * right)
out *= SCALE_VALUE
out = numpy.clip(out, -SCALE_VALUE, SCALE_VALUE).astype(MixingBuffer.DTYPE_SHORT)
return out
def __init__(self, buffer_len, log=None):
if log is None:
log = getWorkerLogger('mixer', level=LOG_LEVEL)
self._log = log
self._buffer_len = buffer_len
self._reset()
def add_chunk(self, chunk):
if chunk.time < (self._current_head - self._frames_to_seconds(len(self._buffer))):
# chunk is too far in the past, ignore it
self._log.debug('Ignoring very old chunk: %s', chunk.time)
return
if (chunk.time + chunk.duration) > self._current_head:
# chunk is ahead of us, fill with silence to mix against
diff = (chunk.time + chunk.duration) - self._current_head
if diff > self._frames_to_seconds(len(self._buffer)):
# the chunk is far ahead of us, drop the entire buffer
self._reset()
else:
self._extend_with_silence(diff)
buf = numpy.frombuffer(chunk.pcm, dtype=self.DTYPE_SHORT)
mix_start_pos = -self._seconds_to_frames(self._current_head - chunk.time)
mix_end_pos = mix_start_pos + len(buf)
if mix_end_pos == 0:
mix_end_pos = None
try:
self._buffer[mix_start_pos:mix_end_pos] = self._mix_frames(
self._buffer[mix_start_pos:mix_end_pos], buf)
except Exception as err:
log.warning('Failed to mix audio: [%d:%d]', mix_start_pos, mix_end_pos)
log.debug('Mix stats: _buffer._left_index=%d _buffer._right_index=%d len(buf)=%d',
self._buffer._left_index, self._buffer._right_index, len(buf))
log.exception(err)
def add_buffer(self, buf):
now = time.time()
if self._current_head > now:
fake_chunk = pymumble.soundqueue.SoundChunk(
buf,
0,
len(buf),
now,
None,
None,
timestamp=now,
)
self.add_chunk(fake_chunk)
else:
self._extend_with_silence(exact=True)
buf = numpy.frombuffer(buf, dtype=self.DTYPE_SHORT)
self._buffer.extend(buf)
self._current_head += self._frames_to_seconds(len(buf))
def _extend_with_silence(self, silence_length=None, exact=False):
if silence_length is None:
now = time.time()
if now > self._current_head:
silence_length = now - self._current_head
else:
# self._current_head is in the future, don't need to come up to date
return
if not exact:
silence_length = max(min(silence_length, self._buffer_len), self.MIN_SILENCE_EXTENSION)
self._buffer.extend(numpy.zeros(self._seconds_to_frames(silence_length), dtype=self.DTYPE_SHORT))
self._current_head += silence_length
def _reset(self):
self._buffer = AssignableRingBuffer(self._seconds_to_frames(self._buffer_len), dtype=self.DTYPE_SHORT)
self._buffer.extend(numpy.zeros(self._buffer._capacity, dtype=self.DTYPE_SHORT))
self._current_head = time.time()
def get_last(self, seconds):
seconds = min(self._frames_to_seconds(len(self._buffer) - 1), seconds)
frame_count = self._seconds_to_frames(seconds)
buf = self._buffer[-frame_count:].tobytes()
# round to PYMUMBLE_AUDIO_PER_PACKET
return buf[len(buf) % SOUNDCHUNK_SIZE:]
def get_all(self):
buf = self._buffer[:].tobytes()
# round to PYMUMBLE_AUDIO_PER_PACKET
return buf[len(buf) % SOUNDCHUNK_SIZE:]
def _seconds_to_frames(self, seconds):
return int(round(seconds * PYMUMBLE_SAMPLERATE))
def _frames_to_seconds(self, frames):
return frames / PYMUMBLE_SAMPLERATE
class RNNoise:
# Based on https://github.com/Shb742/rnnoise_python/blob/master/rnnoise.py
SAMPLE_RATE = 48000
SAMPLE_SIZE = SAMPLE_FRAME_SIZE
SAMPLES_IN_FRAME = 480
FRAME_SIZE = SAMPLES_IN_FRAME * SAMPLE_SIZE
_lib = None
@classmethod
def _load_library(cls):
# a few sanity checks just in case
assert cls.SAMPLE_RATE == PYMUMBLE_SAMPLERATE
assert cls.SAMPLES_IN_FRAME * 100 == cls.SAMPLE_RATE
lib_path = ctypes.util.find_library('rnnoise')
logging.getLogger('.'.join([APP_NAME, 'transcriber', 'rnnoise'])).debug(
'Loading rnnoise lib: path=%s', lib_path)
lib = ctypes.cdll.LoadLibrary(lib_path)
lib.rnnoise_process_frame.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_float)
]
lib.rnnoise_process_frame.restype = ctypes.c_float
lib.rnnoise_create.restype = ctypes.c_void_p
lib.rnnoise_destroy.argtypes = [ctypes.c_void_p]
return lib
@classmethod
@property
def lib(cls):
if cls._lib is None:
cls._lib = cls._load_library()
return cls._lib
def __init__(self):
self._log = getWorkerLogger('transcriber.rnnoise')
self._state = self.lib.rnnoise_create(None)
def __del__(self):
if self._state is not None:
self.lib.rnnoise_destroy(self._state)
self._state = None
def process_frame(self, buffer):
in_buf = numpy.ndarray((self.SAMPLES_IN_FRAME,), numpy.int16, buffer).astype(ctypes.c_float)
in_ptr = in_buf.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
out_buf = numpy.ndarray((self.SAMPLES_IN_FRAME,), ctypes.c_float)
out_ptr = out_buf.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
vad_prob = self.lib.rnnoise_process_frame(self._state, out_ptr, in_ptr)
output = out_buf.astype(ctypes.c_short).tobytes()
assert len(output) == len(buffer)
return output, vad_prob
def denoise(self, buffer):
# append silence to pad out to the right length
buffer += bytes([0]) * (len(buffer) % (self.SAMPLES_IN_FRAME * self.SAMPLE_SIZE))
return b''.join(self.process_frame(bytes(chunk))[0] \
for chunk in group_iter(buffer, self.SAMPLES_IN_FRAME * self.SAMPLE_SIZE))
class MumbleControlCommand(Enum):
EXIT = auto()
USER_CREATE = auto()
USER_UPDATE = auto()
USER_REMOVE = auto()
CHANNEL_CREATE = auto()
CHANNEL_UPDATE = auto()
CHANNEL_REMOVE = auto()
MOVE_TO_CHANNEL = auto()
RECV_CHANNEL_TEXT_MSG = auto()
SEND_CHANNEL_TEXT_MSG = auto()
RECV_USER_TEXT_MSG = auto()
SEND_USER_TEXT_MSG = auto()
RECV_CHANNEL_AUDIO = auto()
SEND_CHANNEL_AUDIO_MSG = auto()
RECV_USER_AUDIO = auto()
SEND_USER_AUDIO_MSG = auto()
DROP_CHANNEL_AUDIO_BUFFER = auto()
DROP_USER_AUDIO_BUFFER = auto()
class IrcControlCommand(Enum):
EXIT = auto()
USER_CREATE = auto()
USER_UPDATE = auto()
USER_REMOVE = auto()
RECV_CHANNEL_TEXT_MSG = auto()
SEND_CHANNEL_TEXT_MSG = auto()
RECV_USER_TEXT_MSG = auto()
SEND_USER_TEXT_MSG = auto()
RECV_CHANNEL_ACTION = auto()
SEND_CHANNEL_ACTION = auto()
class TranscriberControlCommand(Enum):
EXIT = auto()
TRANSCRIBE_MESSAGE = auto()
TRANSCRIBE_MESSAGE_RESPONSE = auto()
class SpeakerControlCommand(Enum):
EXIT = auto()
SPEAK_MESSAGE = auto()
SPEAK_MESSAGE_RESPONSE = auto()
class MediaControlCommand(Enum):
EXIT = auto()
PLAY_AUDIO_URL = auto()
PLAY_VIDEO_URL = auto()
AUDIO_CHUNK_READY = auto()
STOP = auto()
SET_VOLUME = auto()
SET_VOLUME_LOWER = auto()
SET_VOLUME_HIGHER = auto()
class RouterControlCommand(Enum):
EXIT = auto()
@multiprocessify
def proc_irc(irc_config, router_conn):
setproctitle.setproctitle('doty: irc worker')
log = getWorkerLogger('irc', level=LOG_LEVEL)
keep_running = True
log.debug('Starting irc process')
client = irc.client.Reactor()
server = client.server()
if irc_config['ssl']:
ssl_ctx = ssl.create_default_context()
if not irc_config['ssl_verify']:
ssl_ctx.verify_mode = ssl.CERT_NONE
conn_factory = irc.connection.Factory(
wrapper=lambda s: ssl_ctx.wrap_socket(s, server_hostname=irc_config['server']),
ipv6=irc_config['allow_ipv6'],
)
else:
conn_factory = irc.connection.Factory(ipv6=irc_config['allow_ipv6'])
e2d = lambda ev: {
'type': ev.type,
'source': ev.source.split('!')[0] if '!' in ev.source else ev.source,
'target': ev.target,
'args': ev.arguments,
}
def handle_irc_message(conn, event):
log.debug('Recieved IRC event: %s', event)
cmd_data = e2d(event)
if event.type == 'pubmsg':
cmd_data['cmd'] = IrcControlCommand.RECV_CHANNEL_TEXT_MSG
elif event.type == 'privmsg':
cmd_data['cmd'] = IrcControlCommand.RECV_USER_TEXT_MSG
elif event.type == 'action':
cmd_data['cmd'] = IrcControlCommand.RECV_CHANNEL_ACTION
else:
log.warning('Unrecognized event type: %s', event.type)
return
if cmd_data['source'] == irc_config['username']:
# it's something we sent or triggered, ignore it
log.debug('Ignoring event from ourself: %r', cmd_data)
else:
router_conn.send(cmd_data)
for ev_type in ['pubmsg', 'privmsg', 'action']:
client.add_global_handler(ev_type, handle_irc_message)
def handle_membership_change(conn, event):
log.debug('Recieved IRC join/part: %s', event)
cmd_data = e2d(event)
if event.type == 'join':
cmd_data['cmd'] = IrcControlCommand.USER_CREATE
elif event.type in ['kick', 'part', 'quit']:
cmd_data['cmd'] = IrcControlCommand.USER_REMOVE
elif event.type == 'nick':
cmd_data['cmd'] = IrcControlCommand.USER_UPDATE
else:
log.warning('Unrecognized event type: %s', event.type)
return
if cmd_data['source'] == irc_config['username']:
# it's something we sent or triggered, ignore it
log.debug('Ignoring event from ourself: %r', cmd_data)
else:
router_conn.send(cmd_data)
for ev_type in ['join', 'kick', 'part', 'quit', 'nick']:
client.add_global_handler(ev_type, handle_membership_change)
log.info('IRC client running')
while keep_running:
if not server.connected:
server.connect(irc_config['server'], irc_config['port'],
irc_config['username'], connect_factory=conn_factory)
server.join(irc_config['channel'])
client.process_once(SHORT_POLL)
if router_conn.poll(LONG_POLL):
cmd_data = router_conn.recv()
log.debug('Recieved control command: %r', cmd_data)
if cmd_data['cmd'] == IrcControlCommand.EXIT:
log.debug('Recieved EXIT command from router')
server.disconnect()
keep_running = False
elif cmd_data['cmd'] == IrcControlCommand.SEND_CHANNEL_TEXT_MSG:
log.info('Sending message: %s', cmd_data['msg'].replace(ZW_SPACE, ''))
server.privmsg(irc_config['channel'], cmd_data['msg'])
elif cmd_data['cmd'] == IrcControlCommand.SEND_USER_TEXT_MSG:
log.info('Sending message to user: %s -> %s',
cmd_data['user'], cmd_data['msg'])
server.privmsg(cmd_data['user'], cmd_data['msg'])
elif cmd_data['cmd'] == IrcControlCommand.SEND_CHANNEL_ACTION:
log.info('Sending action: %s', cmd_data['msg'].replace(ZW_SPACE, ''))
server.action(irc_config['channel'], cmd_data['msg'])
else:
log.warning('Unrecognized command: %r', cmd_data)
log.debug('IRC process exiting')
@multiprocessify
def proc_mmbl(mmbl_config, router_conn, pymumble_debug=False):
setproctitle.setproctitle('doty: mumble worker')
log = getWorkerLogger('mmbl', level=LOG_LEVEL)
keep_running = True
clbk_lock = threading.Lock()
EVENT_MAP = {
PYMUMBLE_CLBK_USERCREATED: MumbleControlCommand.USER_CREATE,
PYMUMBLE_CLBK_USERUPDATED: MumbleControlCommand.USER_UPDATE,
PYMUMBLE_CLBK_USERREMOVED: MumbleControlCommand.USER_REMOVE,
PYMUMBLE_CLBK_CHANNELCREATED: MumbleControlCommand.CHANNEL_CREATE,
PYMUMBLE_CLBK_CHANNELUPDATED: MumbleControlCommand.CHANNEL_UPDATE,
PYMUMBLE_CLBK_CHANNELREMOVED: MumbleControlCommand.CHANNEL_REMOVE,
PYMUMBLE_CLBK_TEXTMESSAGERECEIVED: MumbleControlCommand.RECV_CHANNEL_TEXT_MSG,
PYMUMBLE_CLBK_SOUNDRECEIVED: MumbleControlCommand.RECV_CHANNEL_AUDIO,
}
log.debug('Starting mumble process')
mmbl = pymumble.Mumble(mmbl_config['server'],
mmbl_config['username'], password=mmbl_config['password'],
port=mmbl_config['port'],
debug=pymumble_debug,
reconnect=False,
)
mmbl.set_receive_sound(True)
log.debug('Setting up callbacks')
def handle_callback(ev_type, *args):
args = normalize_callback_args(ev_type, args)
if ev_type == PYMUMBLE_CLBK_SOUNDRECEIVED:
# avoid memory leak in pymumble
try:
mmbl.users[args[0]['session']].sound.get_sound()
except Exception: pass
else:
log.debug('Callback event: %s => %r', ev_type, args)
cmd_data = {'cmd': EVENT_MAP.get(ev_type, None)}
if cmd_data['cmd'] in (MumbleControlCommand.USER_CREATE, MumbleControlCommand.USER_UPDATE, MumbleControlCommand.USER_REMOVE):
cmd_data['user'] = args[0]
if cmd_data['cmd'] == MumbleControlCommand.USER_UPDATE:
cmd_data['changes'] = args[1]
elif cmd_data['cmd'] == MumbleControlCommand.USER_REMOVE:
cmd_data['session'] = args[1]
elif cmd_data['cmd'] in (MumbleControlCommand.CHANNEL_CREATE, MumbleControlCommand.CHANNEL_UPDATE, MumbleControlCommand.CHANNEL_REMOVE):
cmd_data['channel'] = args[0]
if cmd_data['cmd'] == MumbleControlCommand.CHANNEL_UPDATE:
cmd_data['changes'] = args[1]
elif cmd_data['cmd'] == MumbleControlCommand.RECV_CHANNEL_TEXT_MSG:
if not args[0]['channel_id']:
# it's a private message
cmd_data['cmd'] = MumbleControlCommand.RECV_USER_TEXT_MSG
cmd_data.update(args[0])
elif cmd_data['cmd'] == MumbleControlCommand.RECV_CHANNEL_AUDIO:
if not args[0]['channel_id']:
# it's a private message
cmd_data['cmd'] = MumbleControlCommand.RECV_USER_AUDIO
cmd_data.update(args[0])
cmd_data['chunk'] = args[1]
else:
log.warning('Unrecognized event type: %s', ev_type)
return
with clbk_lock:
router_conn.send(cmd_data)
for callback_type in mmbl.callbacks.get_callbacks_list():
clbk = denote_callback(callback_type)(handle_callback)
mmbl.callbacks.add_callback(callback_type, clbk)
log.debug('Starting mumble connection')
mmbl.start()
mmbl.is_ready()
log.info('Connected to mumble server: %s:%d',
mmbl_config['server'], mmbl_config['port'])
log.debug('Entering control loop')
while keep_running:
if router_conn.poll(SHORT_POLL):
cmd_data = router_conn.recv()
if cmd_data['cmd'] == MumbleControlCommand.EXIT:
log.debug('Recieved exit command from router')
keep_running = False
elif cmd_data['cmd'] == MumbleControlCommand.SEND_CHANNEL_TEXT_MSG:
if 'channel_id' not in cmd_data:
cmd_data['channel_id'] = mmbl.users.myself['channel_id']
log.info('Sending text message to channel: %s => %s',
mmbl.channels[cmd_data['channel_id']]['name'], cmd_data['msg'])
mmbl.channels[cmd_data['channel_id']].send_text_message(html.escape(cmd_data['msg']))
elif cmd_data['cmd'] == MumbleControlCommand.SEND_USER_TEXT_MSG:
log.info('Sending text message to user: %s => %s',
mmbl.users[cmd_data['session_id']]['name'], cmd_data['msg'])
mmbl.users[cmd_data['session_id']].send_message(html.escape(cmd_data['msg']))
elif cmd_data['cmd'] == MumbleControlCommand.MOVE_TO_CHANNEL:
log.info('Joining channel: %s', cmd_data['channel_name'])
try:
target_channel = mmbl.channels.find_by_name(cmd_data['channel_name'])
except UnknownChannelError:
log.debug('Channel doesnt exist, attempting to create: %s', cmd_data['channel_name'])
mmbl.channels.new_channel(0, cmd_data['channel_name'])
else:
mmbl.users.myself.move_in(target_channel['channel_id'])
elif cmd_data['cmd'] == MumbleControlCommand.SEND_CHANNEL_AUDIO_MSG:
# log.debug('Sending audio message: %d bytes', len(cmd_data['buffer']))
mmbl.sound_output.add_sound(cmd_data['buffer'])
elif cmd_data['cmd'] == MumbleControlCommand.DROP_CHANNEL_AUDIO_BUFFER:
log.debug('Dropping outgoing audio buffer')
mmbl.sound_output.clear_buffer()
else:
log.warning('Unrecognized command: %r', cmd_data)
if not mmbl.is_alive():
log.warning('Mumble connection has died')
keep_running = False
log.debug('Mumble process exiting')
class BaseSTTEngine:
def __init__(self, engine_params, logger):
self._log = logger
self._denoiser = RNNoise()
def transcribe(self, buf, phrases=[]):
return self._transcribe(self._denoise(buf), phrases)
def _denoise(self, buffer):
return self._denoiser.denoise(buffer)
class CoquiSTTEngine(BaseSTTEngine):
def __init__(self, engine_params, logger):
super().__init__(engine_params, logger)
self._model = coqui_speechtotext.Model(engine_params['model_path'])
self._model.enableExternalScorer(engine_params['scorer_path'])
self._resample_method = engine_params['resample_method']
def _transcribe(self, buf, phrases=[]):
audio_data = numpy.frombuffer(buf, dtype=numpy.int16)
model_samplerate = self._model.sampleRate()
if model_samplerate != PYMUMBLE_SAMPLERATE:
audio_data = audio_resample(audio_data, PYMUMBLE_SAMPLERATE,
model_samplerate, self._resample_method)
try:
result = self._model.sttWithMetadata(audio_data)
except Exception as err:
self._log.exception(err)
else:
for transcript in result.transcripts:
value = ''.join(t.text for t in transcript.tokens).strip()
if value:
return {
'transcript': value,
'confidence': transcript.confidence / len(transcript.tokens),
}
return None
class VoskSTTEngine(BaseSTTEngine):
def __init__(self, engine_params, logger):
from vosk import Model, KaldiRecognizer, SetLogLevel
super().__init__(engine_params, logger)
SetLogLevel(0 if EXTRA_DEBUG else -1000)
model = Model(engine_params['model_path'])
self._recognizer = KaldiRecognizer(model, PYMUMBLE_SAMPLERATE)
def _transcribe(self, buf, phrases=[]):
self._recognizer.AcceptWaveform(buf)
result = json.loads(self._recognizer.FinalResult())
try:
if result['text'].strip():
return {
'transcript': result['text'].strip(),
'confidence': sum(t['conf'] for t in result['result']) / len(result['result']) \
if 'result' in result else 0.0,
}
except Exception as err:
log.exception(err)
return None
class IBMWatsonEngine(BaseSTTEngine):
def __init__(self, engine_params, logger):
super().__init__(engine_params, logger)
self._client = watson_speechtotext(
iam_apikey=engine_params['api_key'],
url=engine_params['service_url'],
)
self._hint_phrases = engine_params['hint_phrases']
self._model = engine_params['model']
def _transcribe(self, buf, phrases=[]):
resp = self._client.recognize(
audio=io.BytesIO(buf),
content_type='audio/l16; rate={:d}; channels=1; endianness=little-endian'.format(PYMUMBLE_SAMPLERATE),
model=self._model,
keywords=list(set(phrases + self._hint_phrases)),
keywords_threshold=0.8,
profanity_filter=False,
)
try:
results = resp.get_result()['results']
except KeyError as err:
self._log.exception(err)
return None
value = '. '.join(alt['transcript'].replace('%HESITATION', '...').strip() \
for result in results \
for alt in result['alternatives']).strip()
if value:
conf = [alt['confidence'] \
for result in results
for alt in result['alternatives'] \
]
return {
'transcript': value,
'confidence': sum(conf) / len(conf),
}
return None
@multiprocessify
def proc_transcriber(transcription_config, router_conn):
setproctitle.setproctitle('doty: transcriber worker')
log = getWorkerLogger('transcriber', level=LOG_LEVEL)
keep_running = True
log.debug('Transcribing starting up')
try:
engine = {
'coqui-stt': CoquiSTTEngine,
'vosk': VoskSTTEngine,
'ibm-watson': IBMWatsonEngine,
}.get(transcription_config['engine'])(transcription_config['engine_params'], log)
except Exception as err:
keep_running = False
log.error('Failed to load transcription engine')
log.exception(err)
log.info('Transcriber running: %s', transcription_config['engine'])
while keep_running:
if router_conn.poll(LONG_POLL):
cmd_data = router_conn.recv()
if cmd_data['cmd'] == TranscriberControlCommand.EXIT:
log.debug('Recieved EXIT command from router')
keep_running = False
elif cmd_data['cmd'] == TranscriberControlCommand.TRANSCRIBE_MESSAGE:
if transcription_config['save_only']:
result = {'transcript': 'NO_DATA', 'confidence': 0.0}
else:
with contexttimer.Timer(output=log.debug, prefix='engine.transcribe()'):
result = engine.transcribe(cmd_data['buffer'], cmd_data['phrases'])
if result:
if not transcription_config['save_only']:
log.debug('Transcription result: txid=%s actor=%d result=%r',
cmd_data['txid'], cmd_data['actor'], result)
router_conn.send({
'cmd': TranscriberControlCommand.TRANSCRIBE_MESSAGE_RESPONSE,
'actor': cmd_data['actor'],
'result': result,
'txid': cmd_data['txid'],
})
if transcription_config['save_to']:
base_path = os.path.join(transcription_config['save_to'], cmd_data['username'])
if not os.path.exists(os.path.join(base_path, 'wavs')):
os.makedirs(os.path.join(base_path, 'wavs'), mode=0o755)
wav_fname = cmd_data['txid'] + '.wav'
map_fname = 'metadata.csv'
with wave.open(os.path.join(base_path, 'wavs', wav_fname), 'wb') as wav_file:
wav_file.setnchannels(AUDIO_CHANNELS)
wav_file.setsampwidth(SAMPLE_FRAME_SIZE)
wav_file.setframerate(PYMUMBLE_SAMPLERATE)
wav_file.writeframes(cmd_data['buffer'])
with open(os.path.join(base_path, map_fname), 'a') as map_file:
map_file.write('{},{}\n'.format(wav_fname, result['transcript']))
else:
log.debug('No transcription result for: txid=%s, actor=%d',
cmd_data['txid'], cmd_data['actor'])
else:
log.warning('Unrecognized command: %r', cmd_data)
log.debug('Transcriber process exiting')
class BaseTTSEngine:
def __init__(self, engine_params, logger):
self._log = logger
def _speak(self, text):
raise NotImplemented()
def speak(self, text):
return self._speak(text)
class CoquiTTSEngine(BaseTTSEngine):
def __init__(self, engine_params, logger):
super().__init__(engine_params, logger)
from TTS.utils.manage import ModelManager
from TTS.utils.synthesizer import Synthesizer
self._resample_method = engine_params['resample_method']
self._model_manager = ModelManager(
os.path.join(os.path.dirname(coqui_texttospeech.__file__), '.models.json'))
model_path, model_config_path, model_item = self._model_manager.download_model(
'tts_models/' + engine_params['model'])
vocoder_path, vocoder_config_path, _ = self._model_manager.download_model(
'vocoder_models/' + engine_params['vocoder'] if engine_params['vocoder'] else model_item['default_vocoder'])
self._synth = Synthesizer(
model_path,
model_config_path,
None, # speakers_file_path
vocoder_path,
vocoder_config_path,
None, # encoder_path
None, # encoder_config_path
False, # use_cuda
)
def _speak(self, text):
text = text.strip()
if text[-1] not in '.!?':
# coqui can have a stroke if it doesn't get a input end token
text += '.'
audio = numpy.array(self._synth.tts(text, None, None))
norm_audio = audio * (32767 / max(0.01, numpy.max(numpy.abs(audio))))
resampled_audio = audio_resample(norm_audio,
self._synth.output_sample_rate, PYMUMBLE_SAMPLERATE, self._resample_method)
return bytes(resampled_audio)
class LarynxTTSEngine(BaseTTSEngine):
def __init__(self, engine_params, logger):
import gruut
super().__init__(engine_params, logger)
self._resample_method = engine_params['resample_method']
with open(os.path.join(engine_params['model_path'], 'config.json')) as model_config_file:
model_config = json.load(model_config_file)
self._model_samplerate = model_config['audio']['sample_rate']
self._tts_config = {
'gruut_lang': gruut.Language.load('en-us'),
'tts_model': larynx.load_tts_model(
model_type=larynx.constants.TextToSpeechType.GLOW_TTS,
model_path=engine_params['model_path'],
),
'tts_settings': {
'noise_scale': engine_params['noise_scale'],
'length_scale': engine_params['length_scale'],
},
'vocoder_model': larynx.load_vocoder_model(
model_type=larynx.constants.VocoderType.HIFI_GAN,
model_path=engine_params['vocoder_path'],
denoiser_strength=engine_params['denoiser_strength'],
),
'audio_settings': larynx.audio.AudioSettings(**model_config['audio']),
}
def _speak(self, text):
results = larynx.text_to_speech(text=text, **self._tts_config)
combined_audio = bytes().join(
bytes(audio_resample(audio,
self._model_samplerate, PYMUMBLE_SAMPLERATE, self._resample_method))
for _, audio in results
)
return combined_audio
class GoogleTTSEngine(BaseTTSEngine):
def __init__(self, engine_params, logger):
super().__init__(engine_params, logger)
self._client = gcloud_texttospeech.TextToSpeechClient.from_service_account_json(engine_params['credentials_path'])
self._voice = gcloud_texttospeech.VoiceSelectionParams(
language_code=engine_params['language'],
name=engine_params['voice'],
)
self._config = gcloud_texttospeech.AudioConfig(
audio_encoding=gcloud_texttospeech.AudioEncoding.LINEAR16,
sample_rate_hertz=PYMUMBLE_SAMPLERATE,
effects_profile_id=engine_params['effect_profiles'],
speaking_rate=engine_params['speed'],
pitch=engine_params['pitch'],
volume_gain_db=engine_params['volume'],
)
def _speak(self, text):
text_input = gcloud_texttospeech.SynthesisInput(text=text)
response = self._client.synthesize_speech(input=text_input,
voice=self._voice, audio_config=self._config)
return response.audio_content[WAV_HEADER_LEN:]
@multiprocessify
def proc_speaker(speaker_config, router_conn):
setproctitle.setproctitle('doty: speaker worker')
log = getWorkerLogger('speaker', level=LOG_LEVEL)
keep_running = True
log.debug('Speaker starting up')
os.nice(5)
try:
engine = {
'coqui-tts': CoquiTTSEngine,
'larynx-tts': LarynxTTSEngine,
'gcloud-tts': GoogleTTSEngine,
}.get(speaker_config['engine'])(speaker_config['engine_params'], log)
except Exception as err:
keep_running = False
log.error('Failed to load speaker engine')
log.exception(err)
@functools.lru_cache
def speak(msg):
return engine.speak(msg)
log.info('Speaker running: %s', speaker_config['engine'])
while keep_running:
if router_conn.poll(LONG_POLL):
cmd_data = router_conn.recv()
if cmd_data['cmd'] == SpeakerControlCommand.EXIT:
log.debug('Recieved EXIT command from router')
keep_running = False
elif cmd_data['cmd'] == SpeakerControlCommand.SPEAK_MESSAGE:
log.debug('Recieved speaker request: txid=%s session=%d msg=%s',
cmd_data['txid'], cmd_data['actor'], cmd_data['msg'])
try:
with contexttimer.Timer(output=log.debug, prefix='engine.speak()'):
audio = speak(cmd_data['msg'].replace(ZW_SPACE, ''))
log.debug('Generated audio duration: %0.2f seconds',