platypush/platypush/backend/assistant/google/__init__.py

73 lines
2.5 KiB
Python
Raw Normal View History

2017-12-22 10:18:04 +01:00
import logging
import json
import os
2017-12-22 10:43:43 +01:00
import subprocess
2017-12-22 10:18:04 +01:00
import time
import google.oauth2.credentials
from google.assistant.library import Assistant
from google.assistant.library.event import EventType
from google.assistant.library.file_helpers import existing_file
2017-12-22 10:21:31 +01:00
from platypush.backend import Backend
from platypush.message.event.assistant import \
ConversationStartEvent, ConversationEndEvent, SpeechRecognizedEvent
2017-12-22 10:18:04 +01:00
class AssistantGoogleBackend(Backend):
""" Class for the Google Assistant backend. It creates and event source
that posts recognized phrases on the main bus """
def __init__(self, credentials_file=os.path.join(
os.path.expanduser('~/.config'),
'google-oauthlib-tool', 'credentials.json'), **kwargs):
2017-12-22 10:18:04 +01:00
""" Params:
credentials_file -- Path to the Google OAuth credentials file
2017-12-22 10:43:43 +01:00
(default: ~/.config/google-oauthlib-tool/credentials.json)
"""
2017-12-22 10:18:04 +01:00
super().__init__(**kwargs)
self.credentials_file = credentials_file
self.assistant = None
2017-12-22 10:18:04 +01:00
2017-12-22 10:43:43 +01:00
with open(self.credentials_file, 'r') as f:
2017-12-22 10:18:04 +01:00
self.credentials = google.oauth2.credentials.Credentials(token=None,
**json.load(f))
2017-12-24 13:15:37 +01:00
logging.info('Initialized Google Assistant backend')
2017-12-22 10:18:04 +01:00
def _process_event(self, event):
logging.info('Received assistant event: {}'.format(event))
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
self.bus.post(ConversationStartEvent())
elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
self.bus.post(ConversationEndEvent())
2017-12-22 10:43:43 +01:00
elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
phrase = event.args['text'].lower().strip()
logging.info('Speech recognized: {}'.format(phrase))
self.bus.post(SpeechRecognizedEvent(phrase=phrase))
2017-12-22 10:18:04 +01:00
def stop_conversation(self):
if self.assistant: self.assistant.stop_conversation()
2017-12-22 10:18:04 +01:00
def send_message(self, msg):
# Can't send a message on an event source, ignoring
# TODO Make a class for event sources like these. Event sources
# would be a subset of the backends which can fire events on the bus
# but not receive requests or process responses.
2017-12-22 10:43:43 +01:00
pass
2017-12-22 10:18:04 +01:00
def run(self):
super().run()
with Assistant(self.credentials) as assistant:
self.assistant = assistant
for event in assistant.start():
2017-12-22 10:18:04 +01:00
self._process_event(event)
# vim:sw=4:ts=4:et: