Ran black code formatter on everything.
[python_utils.git] / google_assistant.py
index a50003c7eb2a41e8326714ad24e4eccd2ec6cc34..75ca6432cf76b9f84506aa549855e5cec25e1844 100644 (file)
@@ -2,6 +2,8 @@
 
 import logging
 from typing import NamedTuple
+import sys
+import warnings
 
 import requests
 import speech_recognition as sr  # type: ignore
@@ -19,14 +21,14 @@ parser.add_argument(
     type=str,
     default="http://kiosk.house:3000",
     metavar="URL",
-    help="How to contact the Google Assistant bridge"
+    help="How to contact the Google Assistant bridge",
 )
 parser.add_argument(
     "--google_assistant_username",
     type=str,
     metavar="GOOGLE_ACCOUNT",
     default="scott.gasch",
-    help="The user account for talking to Google Assistant"
+    help="The user account for talking to Google Assistant",
 )
 
 
@@ -45,10 +47,16 @@ 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,
@@ -86,15 +94,25 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
                     logger.debug(f"Transcription: '{audio_transcription}'")
                 except sr.UnknownValueError as e:
                     logger.exception(e)
-                    logger.warning('Unable to parse Google assistant\'s response.')
+                    msg = 'Unable to parse Google assistant\'s response.'
+                    logger.warning(msg)
+                    warnings.warn(msg, stacklevel=3)
                     audio_transcription = None
+        return GoogleResponse(
+            success=success,
+            response=response,
+            audio_url=audio,
+            audio_transcription=audio_transcription,
+        )
     else:
-        logger.error(
+        message = (
             f'HTTP request to {url} with {payload} failed; code {r.status_code}'
         )
-    return GoogleResponse(
-        success=success,
-        response=response,
-        audio_url=audio,
-        audio_transcription=audio_transcription,
-    )
+        logger.error(message)
+        return GoogleResponse(
+            success=False,
+            response=message,
+            audio_url=audio,
+            audio_transcription=audio_transcription,
+        )
+        sys.exit(-1)