Stuff.
[python_utils.git] / google_assistant.py
index 500a909feae4f5f898cbd5fbb6812449043f4796..b34197a3e60d0db9eff5c9cc6609ebe04e581bab 100644 (file)
@@ -45,10 +45,17 @@ audio_url: {self.audio_url}"""
 
 
 def tell_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
+    """Alias for ask_google."""
     return ask_google(cmd, recognize_speech=recognize_speech)
 
 
 def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
+    """Send a command string to Google via the google_assistant_bridge as the
+    user google_assistant_username and return the response.  If recognize_speech
+    is True, perform speech recognition on the audio response from Google so as
+    to translate it into text (best effort, YMMV).
+    """
+    logging.debug(f"Asking google: '{cmd}'")
     payload = {
         "command": cmd,
         "user": config.config['google_assistant_username'],
@@ -63,6 +70,10 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
         j = r.json()
         success = bool(j["success"])
         response = j["response"] if success else j["error"]
+        if success:
+            logger.debug('Google request succeeded.')
+            if len(response) > 0:
+                logger.debug(f"Google said: '{response}'")
         audio = f"{config.config['google_assistant_bridge']}{j['audio']}"
         if recognize_speech:
             recognizer = sr.Recognizer()
@@ -74,9 +85,15 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
                     sample_rate=24000,
                     sample_width=2,
                 )
-                audio_transcription = recognizer.recognize_google(
-                    speech,
-                )
+                try:
+                    audio_transcription = recognizer.recognize_google(
+                        speech,
+                    )
+                    logger.debug(f"Transcription: '{audio_transcription}'")
+                except sr.UnknownValueError as e:
+                    logger.exception(e)
+                    logger.warning('Unable to parse Google assistant\'s response.')
+                    audio_transcription = None
     else:
         logger.error(
             f'HTTP request to {url} with {payload} failed; code {r.status_code}'