Skip to content
This repository was archived by the owner on Oct 19, 2023. It is now read-only.

Commit ff5300a

Browse files
Google Assistant SDK Teamproppy
authored andcommitted
google-assistant-library: sync sample changes
- update README - device model caching - unify command line flag - fix python 2.7 printing - fixes device actions handler without params GitOrigin-RevId: 24254b4c46abdc5245d4d0da4f45765f67b6c641 Change-Id: I64458cfd87f3ee5e7aa23540309df59a2a545a96
1 parent a81a8e0 commit ff5300a

File tree

2 files changed

+86
-83
lines changed

2 files changed

+86
-83
lines changed

google-assistant-library/README.rst

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Google Assistant Library for Python
33

44
This package contains high level Python_ bindings for the `Google Assistant Library`_.
55

6-
It is part of the `Google Assistant SDK`_.
6+
It is part of the `Google Assistant SDK for devices`_.
77

88
It includes the following features:
99

@@ -13,8 +13,10 @@ It includes the following features:
1313
- Timer and alarm features
1414
- Volume ducking and control
1515
- Conversation state management
16+
- Playback of podcasts and news
17+
- Broadcast voice messages
1618

17-
See `Introduction to the Google Assistant Library`_ for a step by step guide on how to get started with the library on the Raspberry Pi 3.
19+
See `Introduction to the Google Assistant Library`_ for a step by step guide on how to get started with the library on Raspberry Pi 3.
1820

1921
Supported configuration
2022
-----------------------
@@ -32,23 +34,27 @@ Installing
3234
Authorization
3335
-------------
3436

35-
- Follow the steps to `configure the Actions Console project and the Google account <httpsb://developers.google.com/assistant/sdk/guides/library/python/embed/config-dev-project-and-account>`_.
37+
- Follow the steps to `configure the Actions Console project and the Google account <https://developers.google.com/assistant/sdk/guides/library/python/embed/config-dev-project-and-account>`_.
3638
- Follow the steps to `register a new device model and download the client secrets file <https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device>`_.
37-
- Generate device credentials using ``google-oauthlib-tool``:
39+
- Generate credentials using ``google-oauth-tool``.::
3840

3941
pip install --upgrade google-auth-oauthlib[tool]
40-
google-oauthlib-tool --client-secrets path/to/credentials.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --save --headless
42+
google-oauthlib-tool --client-secrets path/to/client_secret_XXXXX.json --scope https://www.googleapis.com/auth/assistant-sdk-prototype --scope https://www.googleapis.com/auth/gcm --save --headless
4143

4244
Usage
4345
-----
4446

4547
- Run the demo::
4648

47-
google-assistant-demo --device_model_id 'my-model-identifier'
49+
google-assistant-demo
4850

4951
- Say "Ok Google" or "Hey Google" followed by a voice query. The demo should
5052
play back the Assistant's response and log events to the screen.
5153

54+
- Register the device and run the demo with device actions::
55+
56+
google-assistant-demo --project-id PROJECT_ID --device-model-id DEVICE_MODEL
57+
5258
Reference
5359
---------
5460

@@ -62,11 +68,10 @@ See `LICENSE`_ and `LICENSE.third_party`_.
6268

6369
.. _Python: https://www.python.org/
6470
.. _Google Assistant Library: https://developers.google.com/assistant/sdk/reference/library/python
65-
.. _Google Assistant SDK: https://developers.google.com/assistant/sdk
66-
.. _Introduction to the Google Assistant Library: https://developers.google.com/assistant/sdk/guides/library/python/
71+
.. _Google Assistant SDK for devices: https://developers.google.com/assistant/sdk
72+
.. _Introduction to the Google Assistant Library: https://developers.google.com/assistant/sdk/guides/library/python
6773
.. _pip: https://pip.pypa.io/
6874
.. _GitHub releases page: https://github.com/googlesamples/assistant-sdk-python/releases
69-
.. _Google API Console Project credentials section: https://console.developers.google.com/apis/credentials
7075
.. _LICENSE: https://github.com/googlesamples/assistant-sdk-python/tree/master/google-assistant-library/LICENSE
7176
.. _LICENSE.third_party: https://github.com/googlesamples/assistant-sdk-python/tree/master/google-assistant-library/LICENSE.third_party
7277
.. _google/assistant/library/LICENSE.third_party: https://github.com/googlesamples/assistant-sdk-python/tree/master/google-assistant-library/google/assistant/library/LICENSE.third_party

google-assistant-sdk/googlesamples/assistant/library/hotword.py

Lines changed: 72 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -18,44 +18,40 @@
1818
from __future__ import print_function
1919

2020
import argparse
21-
import os.path
2221
import json
22+
import os.path
23+
import pathlib2 as pathlib
2324

24-
import google.auth.transport.requests
2525
import google.oauth2.credentials
2626

2727
from google.assistant.library import Assistant
2828
from google.assistant.library.event import EventType
2929
from google.assistant.library.file_helpers import existing_file
30+
from google.assistant.library.device_helpers import register_device
3031

32+
try:
33+
FileNotFoundError
34+
except NameError:
35+
FileNotFoundError = IOError
3136

32-
DEVICE_API_URL = 'https://embeddedassistant.googleapis.com/v1alpha2'
3337

38+
WARNING_NOT_REGISTERED = """
39+
This device is not registered. This means you will not be able to use
40+
Device Actions or see your device in Assistant Settings. In order to
41+
register this device follow instructions at:
3442
35-
def process_device_actions(event, device_id):
36-
if 'inputs' in event.args:
37-
for i in event.args['inputs']:
38-
if i['intent'] == 'action.devices.EXECUTE':
39-
for c in i['payload']['commands']:
40-
for device in c['devices']:
41-
if device['id'] == device_id:
42-
if 'execution' in c:
43-
for e in c['execution']:
44-
if 'params' in e:
45-
yield e['command'], e['params']
46-
else:
47-
yield e['command'], None
43+
https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device
44+
"""
4845

4946

50-
def process_event(event, device_id):
47+
def process_event(event):
5148
"""Pretty prints events.
5249
5350
Prints all events that occur with two spaces between each new
5451
conversation and a single space between turns of a conversation.
5552
5653
Args:
5754
event(event.Event): The current event to process.
58-
device_id(str): The device ID of the new instance.
5955
"""
6056
if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
6157
print()
@@ -66,85 +62,87 @@ def process_event(event, device_id):
6662
event.args and not event.args['with_follow_on_turn']):
6763
print()
6864
if event.type == EventType.ON_DEVICE_ACTION:
69-
for command, params in process_device_actions(event, device_id):
65+
for command, params in event.actions:
7066
print('Do command', command, 'with params', str(params))
7167

7268

73-
def register_device(project_id, credentials, device_model_id, device_id):
74-
"""Register the device if needed.
75-
76-
Registers a new assistant device if an instance with the given id
77-
does not already exists for this model.
78-
79-
Args:
80-
project_id(str): The project ID used to register device instance.
81-
credentials(google.oauth2.credentials.Credentials): The Google
82-
OAuth2 credentials of the user to associate the device
83-
instance with.
84-
device_model_id(str): The registered device model ID.
85-
device_id(str): The device ID of the new instance.
86-
"""
87-
base_url = '/'.join([DEVICE_API_URL, 'projects', project_id, 'devices'])
88-
device_url = '/'.join([base_url, device_id])
89-
session = google.auth.transport.requests.AuthorizedSession(credentials)
90-
r = session.get(device_url)
91-
print(device_url, r.status_code)
92-
if r.status_code == 404:
93-
print('Registering....')
94-
r = session.post(base_url, data=json.dumps({
95-
'id': device_id,
96-
'model_id': device_model_id,
97-
'client_type': 'SDK_LIBRARY'
98-
}))
99-
if r.status_code != 200:
100-
raise Exception('failed to register device: ' + r.text)
101-
print('\rDevice registered.')
102-
103-
10469
def main():
10570
parser = argparse.ArgumentParser(
10671
formatter_class=argparse.RawTextHelpFormatter)
72+
parser.add_argument('--device-model-id', '--device_model_id', type=str,
73+
metavar='DEVICE_MODEL_ID', required=False,
74+
help='the device model ID registered with Google')
75+
parser.add_argument('--project-id', '--project_id', type=str,
76+
metavar='PROJECT_ID', required=False,
77+
help='the project ID used to register this device')
78+
parser.add_argument('--device-config', type=str,
79+
metavar='DEVICE_CONFIG_FILE',
80+
default=os.path.join(
81+
os.path.expanduser('~/.config'),
82+
'googlesamples-assistant',
83+
'device_config_library.json'
84+
),
85+
help='path to store and read device configuration')
10786
parser.add_argument('--credentials', type=existing_file,
10887
metavar='OAUTH2_CREDENTIALS_FILE',
10988
default=os.path.join(
11089
os.path.expanduser('~/.config'),
11190
'google-oauthlib-tool',
11291
'credentials.json'
11392
),
114-
help='Path to store and read OAuth2 credentials')
115-
parser.add_argument('--device_model_id', type=str,
116-
metavar='DEVICE_MODEL_ID', required=True,
117-
help='The device model ID registered with Google')
118-
parser.add_argument(
119-
'--project_id',
120-
type=str,
121-
metavar='PROJECT_ID',
122-
required=False,
123-
help='The project ID used to register device instances.')
124-
parser.add_argument(
125-
'-v',
126-
'--version',
127-
action='version',
128-
version='%(prog)s ' +
129-
Assistant.__version_str__())
93+
help='path to store and read OAuth2 credentials')
94+
parser.add_argument('-v', '--version', action='version',
95+
version='%(prog)s ' + Assistant.__version_str__())
13096

13197
args = parser.parse_args()
13298
with open(args.credentials, 'r') as f:
13399
credentials = google.oauth2.credentials.Credentials(token=None,
134100
**json.load(f))
135101

136-
with Assistant(credentials, args.device_model_id) as assistant:
137-
events = assistant.start()
102+
device_model_id = None
103+
last_device_id = None
104+
try:
105+
with open(args.device_config) as f:
106+
device_config = json.load(f)
107+
device_model_id = device_config['model_id']
108+
last_device_id = device_config.get('last_device_id', None)
109+
except FileNotFoundError:
110+
pass
138111

139-
print('device_model_id:', args.device_model_id + '\n' +
140-
'device_id:', assistant.device_id + '\n')
112+
if not args.device_model_id and not device_model_id:
113+
raise Exception('Missing --device-model-id option')
114+
115+
# Re-register if "device_model_id" is given by the user and it differs
116+
# from what we previously registered with.
117+
should_register = (
118+
args.device_model_id and args.device_model_id != device_model_id)
119+
120+
device_model_id = args.device_model_id or device_model_id
121+
122+
with Assistant(credentials, device_model_id) as assistant:
123+
events = assistant.start()
141124

142-
if args.project_id:
143-
register_device(args.project_id, credentials,
144-
args.device_model_id, assistant.device_id)
125+
device_id = assistant.device_id
126+
print('device_model_id:', device_model_id)
127+
print('device_id:', device_id + '\n')
128+
129+
# Re-register if "device_id" is different from the last "device_id":
130+
if should_register or (device_id != last_device_id):
131+
if args.project_id:
132+
register_device(args.project_id, credentials,
133+
device_model_id, device_id)
134+
pathlib.Path(os.path.dirname(args.device_config)).mkdir(
135+
exist_ok=True)
136+
with open(args.device_config, 'w') as f:
137+
json.dump({
138+
'last_device_id': device_id,
139+
'model_id': device_model_id,
140+
}, f)
141+
else:
142+
print(WARNING_NOT_REGISTERED)
145143

146144
for event in events:
147-
process_event(event, assistant.device_id)
145+
process_event(event)
148146

149147

150148
if __name__ == '__main__':

0 commit comments

Comments
 (0)