Przeglądaj źródła

#14 Merge tts.py and clips.py into a single audio output service

Martin 10 lat temu
rodzic
commit
b9809c310a

+ 0 - 27
voice_control/clips.py

@@ -1,27 +0,0 @@
-import os
-import time
-import wave
-import pyaudio
-import tts
-
-_CLIP_FOLDER = '/home/martin/workspaces/visual-code/voice_control/resources/clips'
-_CLIP_DATA_CACHE = {}
-
-class Clips(object):
-    SUCCESS = 'ding.wav'
-    FAILURE = 'dong.wav'
-
-    DING = 'ding.wav'
-    DONG = 'dong.wav'
-
-def play(clip):
-    """Simple callback function to play a wave file. By default it plays
-    a Ding sound.
-
-    :param str fname: wave file name
-    :return: None
-    """
-
-    fname = os.path.join(_CLIP_FOLDER, clip)
-    tts._play(fname, True)
-    return

+ 4 - 4
voice_control/ears.py

@@ -1,7 +1,7 @@
 import logging
-import speech_recognition as sr
 import time
-import clips
+import speech_recognition as sr
+import output
 
 def _get_recognizer(pause_threshold):
     recognizer = sr.Recognizer()
@@ -89,11 +89,11 @@ def _speech_to_text(audio, recognizer, tokenize, return_all, language, preferred
         logging.error("Could not request results from Google Speech Recognition service: %s", e)
 
     if res and res.strip():
-        clips.play(clips.Clips.SUCCESS)
+        output.success()
         return [t.strip() for t in res.split(' ') if t.strip()] if tokenize else res.strip() 
 
     else:
-        clips.play(clips.Clips.FAILURE)
+        output.failure()
         return None
 
 def listen(pause_threshold=5, tokenize=False, return_all=False, language='en-GB', preferred_phrases=None):

+ 6 - 6
voice_control/functions/email_mailgun.py

@@ -1,9 +1,9 @@
 import logging
 import requests
 import requests.exceptions
-import tts
 import ears
 import base
+import output
 
 _RECIPIENTS = {
     'martin': 'martin@gerner.co',
@@ -36,7 +36,7 @@ class Email(base.BaseFunction):
     def _send(self, recipient):
         logging.info('email _send: %s', recipient)
 
-        tts.tts(recipient)
+        output.text(recipient)
 
         lines, terminator = ears.listen_until_terminated()
 
@@ -45,13 +45,13 @@ class Email(base.BaseFunction):
             logging.info('Sending email: %s: %s', _RECIPIENTS[recipient], lines)
             try:
                 _send_by_sendgrid(_RECIPIENTS[recipient], 'snowbody email', body)
-                tts.tts('done')
+                output.success()
             except requests.exceptions.HTTPError, e:
-                tts.tts('error')
+                output.failure()
                 logging.error(e)
 
         else:
-            tts.tts('cancelled')
+            output.cancelled()
 
     def call(self, additional_tokens=None, **_):
         logging.info('email: %s', additional_tokens)
@@ -61,7 +61,7 @@ class Email(base.BaseFunction):
                 self._send(t)
                 return
 
-        tts.tts('to whom?')
+        output.text('to whom?')
         recipient = ears.listen(pause_threshold=1, preferred_phrases=self.preferred_phrases())
         if recipient in _RECIPIENTS:
             self._send(recipient)

+ 4 - 4
voice_control/functions/music.py

@@ -2,8 +2,8 @@ import subprocess
 import os
 import logging
 import base
-import tts
 import ears
+import output
 
 _FOLDER = '/mnt/nas/music/albums'
 
@@ -43,13 +43,13 @@ class Music(base.BaseFunction):
         if additional_tokens:
             f = self._search(additional_tokens)
         if not f:
-            tts.tts('ready')
+            output.text('ready')
             tokens = ears.listen(pause_threshold=3, preferred_phrases=self.folders.keys()[:300])
             f = self._search(tokens)
 
         if f:
-            tts.tts('playing %s' % f)
+            output.text('playing %s' % f)
             self.current_process = subprocess.Popen(['cvlc', '-Z', f, ]) 
 
         else:
-            tts.tts('failed')
+            output.failure()

+ 4 - 5
voice_control/functions/todo_wunderlist.py

@@ -1,9 +1,8 @@
 import logging
 import base
-import tts
-import clips
 import ears
 import requests
+import output
 
 _LISTEN_TIMEOUT = 600
 _GROCERIES = ['milk', 'bread']
@@ -71,13 +70,13 @@ class Wunderlist(base.BaseFunction):
     def call(self, **_):
         list_name = self._get_list()
         if list_name is None:
-            clips.play(clips.Clips.FAILURE)
+            output.failure()
             return
 
         lines, terminator = ears.listen_until_terminated(timeout=_LISTEN_TIMEOUT, preferred_phrases=_GROCERIES)
 
         if terminator == 'cancel':
-            tts.tts('cancelled')
+            output.cancelled()
             return
 
         else:
@@ -88,4 +87,4 @@ class Wunderlist(base.BaseFunction):
             for item in items:
                 self.client.create_task(self.list_name, item)
 
-            tts.tts('ok')
+            output.success()

+ 13 - 0
voice_control/output/__init__.py

@@ -0,0 +1,13 @@
+import audio_output
+
+def success():
+    audio_output.play_clip(audio_output.Clips.SUCCESS)
+
+def failure():
+    audio_output.play_clip(audio_output.Clips.FAILURE)
+
+def cancelled():
+    audio_output.tts('cancelled')
+
+def text(s):
+    audio_output.tts(s)

+ 29 - 7
voice_control/tts.py → voice_control/output/audio_output.py

@@ -1,18 +1,28 @@
-import logging
 import os
-import hashlib
 import time
+import logging
+import hashlib
 
+import pyaudio
 from gtts import gTTS
 import pygame.mixer
 
+_SOUND_ENABLED = False
+_CLIP_FOLDER = '/home/martin/workspaces/visual-code/voice_control/resources/clips'
+
+_CLIP_DATA_CACHE = {}
 if not os.path.isdir('/tmp/snowboy'):
     os.mkdir('/tmp/snowboy')
 TMP_DIR = '/tmp/snowboy/tts-cache'
 if not os.path.isdir(TMP_DIR):
     os.mkdir(TMP_DIR)
 
-_SOUND_ENABLED = False
+class Clips(object):
+    SUCCESS = 'ding.wav'
+    FAILURE = 'dong.wav'
+
+    DING = 'ding.wav'
+    DONG = 'dong.wav'
 
 def _play(fname, block):
     pygame.mixer.init()
@@ -32,14 +42,26 @@ def tts(text, lang='en', block=True):
     if not _SOUND_ENABLED:
         return
 
-    hash = hashlib.md5(text.lower()).hexdigest()
-    cache_fname = os.path.join(TMP_DIR, hash) + '.mp3'
+    tts_hash = hashlib.md5(text.lower()).hexdigest()
+    cache_fname = os.path.join(TMP_DIR, tts_hash) + '.mp3'
     if os.path.isfile(cache_fname):
         _play(cache_fname, block)
         return
 
-    tts = gTTS(text=text, lang=lang)
+    tts_stream = gTTS(text=text, lang=lang)
     with open(cache_fname, 'w') as f:
-        tts.write_to_fp(f)
+        tts_stream.write_to_fp(f)
 
     _play(cache_fname, block)
+
+def play_clip(clip):
+    """Simple callback function to play a wave file. By default it plays
+    a Ding sound.
+
+    :param str fname: wave file name
+    :return: None
+    """
+
+    fname = os.path.join(_CLIP_FOLDER, clip)
+    _play(fname, True)
+    return