4 from typing import NamedTuple
9 import speech_recognition as sr # type: ignore
13 logger = logging.getLogger(__name__)
15 parser = config.add_commandline_args(
16 f"Google Assistant ({__file__})",
17 "Args related to contacting the Google Assistant",
20 "--google_assistant_bridge",
22 default="http://kiosk.house:3000",
24 help="How to contact the Google Assistant bridge"
27 "--google_assistant_username",
29 metavar="GOOGLE_ACCOUNT",
30 default="scott.gasch",
31 help="The user account for talking to Google Assistant"
35 class GoogleResponse(NamedTuple):
39 audio_transcription: str
43 success: {self.success}
44 response: {self.response}
45 audio_transcription: {self.audio_transcription}
46 audio_url: {self.audio_url}"""
49 def tell_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
50 """Alias for ask_google."""
51 return ask_google(cmd, recognize_speech=recognize_speech)
54 def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse:
55 """Send a command string to Google via the google_assistant_bridge as the
56 user google_assistant_username and return the response. If recognize_speech
57 is True, perform speech recognition on the audio response from Google so as
58 to translate it into text (best effort, YMMV).
60 logging.debug(f"Asking google: '{cmd}'")
63 "user": config.config['google_assistant_username'],
65 url = f"{config.config['google_assistant_bridge']}/assistant"
66 r = requests.post(url, json=payload)
70 audio_transcription = ""
71 if r.status_code == 200:
73 success = bool(j["success"])
74 response = j["response"] if success else j["error"]
76 logger.debug('Google request succeeded.')
78 logger.debug(f"Google said: '{response}'")
79 audio = f"{config.config['google_assistant_bridge']}{j['audio']}"
81 recognizer = sr.Recognizer()
82 r = requests.get(audio)
83 if r.status_code == 200:
85 speech = sr.AudioData(
91 audio_transcription = recognizer.recognize_google(
94 logger.debug(f"Transcription: '{audio_transcription}'")
95 except sr.UnknownValueError as e:
97 msg = 'Unable to parse Google assistant\'s response.'
100 audio_transcription = None
101 return GoogleResponse(
105 audio_transcription=audio_transcription,
108 message = f'HTTP request to {url} with {payload} failed; code {r.status_code}'
109 logger.error(message)
110 return GoogleResponse(
114 audio_transcription=audio_transcription,