Since this thing is on the innerwebs I suppose it should have a
[python_utils.git] / google_assistant.py
index 0af4fa9271df3bf2e6de6f3571cfa6c2eb6d1f23..b767df75f4a56f4b4ec84be3abedd16b2e8a591b 100644 (file)
@@ -1,9 +1,16 @@
 #!/usr/bin/env python3
 
 #!/usr/bin/env python3
 
+# © Copyright 2021-2022, Scott Gasch
+
+"""A module to serve as a local client library around HTTP calls to
+the Google Assistant via a local gateway.
+
+"""
+
 import logging
 import logging
-import sys
-from typing import NamedTuple, Optional
 import warnings
 import warnings
+from dataclasses import dataclass
+from typing import Optional
 
 import requests
 import speech_recognition as sr  # type: ignore
 
 import requests
 import speech_recognition as sr  # type: ignore
@@ -32,11 +39,14 @@ parser.add_argument(
 )
 
 
 )
 
 
-class GoogleResponse(NamedTuple):
-    success: bool
-    response: str
-    audio_url: str
-    audio_transcription: Optional[str]  # None if not available.
+@dataclass
+class GoogleResponse:
+    """A response wrapper."""
+
+    success: bool = False
+    response: str = ''
+    audio_url: str = ''
+    audio_transcription: Optional[str] = None  # None if not available.
 
     def __repr__(self):
         return f"""
 
     def __repr__(self):
         return f"""
@@ -57,7 +67,7 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
     is True, perform speech recognition on the audio response from Google so as
     to translate it into text (best effort, YMMV).
     """
     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}'")
+    logging.debug("Asking google: '%s'", cmd)
     payload = {
         "command": cmd,
         "user": config.config['google_assistant_username'],
     payload = {
         "command": cmd,
         "user": config.config['google_assistant_username'],
@@ -70,12 +80,13 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
     audio_transcription: Optional[str] = ""
     if r.status_code == 200:
         j = r.json()
     audio_transcription: Optional[str] = ""
     if r.status_code == 200:
         j = r.json()
+        logger.debug(j)
         success = bool(j["success"])
         response = j["response"] if success else j["error"]
         if success:
             logger.debug('Google request succeeded.')
             if len(response) > 0:
         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}'")
+                logger.debug("Google said: '%s'", response)
         audio = f"{config.config['google_assistant_bridge']}{j['audio']}"
         if recognize_speech:
             recognizer = sr.Recognizer()
         audio = f"{config.config['google_assistant_bridge']}{j['audio']}"
         if recognize_speech:
             recognizer = sr.Recognizer()
@@ -91,7 +102,7 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
                     audio_transcription = recognizer.recognize_google(
                         speech,
                     )
                     audio_transcription = recognizer.recognize_google(
                         speech,
                     )
-                    logger.debug(f"Transcription: '{audio_transcription}'")
+                    logger.debug("Transcription: '%s'", audio_transcription)
                 except sr.UnknownValueError as e:
                     logger.exception(e)
                     msg = 'Unable to parse Google assistant\'s response.'
                 except sr.UnknownValueError as e:
                     logger.exception(e)
                     msg = 'Unable to parse Google assistant\'s response.'
@@ -113,4 +124,3 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
             audio_url=audio,
             audio_transcription=audio_transcription,
         )
             audio_url=audio,
             audio_transcription=audio_transcription,
         )
-        sys.exit(-1)