JSON string object Python

Pagina: 1
Acties:

Acties:
  • 0 Henk 'm!

  • Lennyz
  • Registratie: Januari 2010
  • Laatst online: 25-09 09:49
Om te beginnen: Ik heb nog geen verstand van programmeren. Ik ben pas sinds een half jaar bezig met C/C++. Met Python heb ik nog geen enkele ervaring. Excuses alvast als ik verkeerde terminologie gebruik.

Ik ben de Google Assistant SDK aan het uitproberen.

Volgens de handleiding is het mogelijk om de door Google herkende tekst uit een JSON string object te halen.

https://developers.google.../sdk/prototype/next-steps

De handleiding geeft aan:
For the Google Assistant library, the transcript is located in a JSON string object in the ON_RECOGNIZING_SPEECH_FINISHED event.
De output ziet er als volgt uit als Google het woordje 'hello' herkent.
ON_RECOGNIZING_SPEECH_FINISHED:
{'text': 'hello'}
Na enig onderzoek moet ik dus de informatie uit het JSON string object halen. Dat probeer ik als volgt te doen middels json.load en json.loads. Ik krijg echter de volgende output. Ik weet niet meer zo goed wat ik nu kan proberen.
if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
data = json.loads(event.type)

TypeError: the JSON object must be str, not 'EventType'

if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
data = json.load(event.type)

AttributeError: 'EventType' object has no attribute 'read'
Mijn vraag is dus:

Hoe kan ik zorgen dat mijn code het gesproken woord haalt uit de JSON string (bijvoorbeeld 'hello') zodat ik daar vervolgens een actie aan kan koppelen (bijvoorbeeld het versturen van een MQTT message)

Mijn totale code:

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python

# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from __future__ import print_function

import argparse
import os.path
import json

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


def process_event(event):
    """Pretty prints events.

    Prints all events that occur with two spaces between each new
    conversation and a single space between turns of a conversation.

    Args:
        event(event.Event): The current event to process.
    """
    if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
        print()

    print(event)

    if (event.type == EventType.ON_CONVERSATION_TURN_FINISHED and
            event.args and not event.args['with_follow_on_turn']):
        print()

    if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
        data = json.loads(event.type)

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--credentials', type=existing_file,
                        metavar='OAUTH2_CREDENTIALS_FILE',
                        default=os.path.join(
                            os.path.expanduser('~/.config'),
                            'google-oauthlib-tool',
                            'credentials.json'
                        ),
                        help='Path to store and read OAuth2 credentials')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))

    with Assistant(credentials) as assistant:
        for event in assistant.start():
            process_event(event)


if __name__ == '__main__':
    main()

Acties:
  • +2 Henk 'm!

  • Raynman
  • Registratie: Augustus 2004
  • Laatst online: 17:21
Lennyz schreef op vrijdag 9 juni 2017 @ 20:41:
De handleiding geeft aan:

[...]
Dat is niet heel duidelijk, maar als je de link volgt naar de documentatie voor Event, staat daar dat het attribuut 'args' een dict is (en dus geen string). Klik je dan op [source], dan zie je ook dat in de constructor (__init__) al json.loads gebruikt wordt. Die Python-wrapper doet dat dus al voor je en jij kunt gewoon event.args['text'] gebruiken om 'hello' te vinden.

Verderop in jouw code zie je ook al event.args['with_follow_on_turn']. Daar bevat de args-dict dus andere keys voor een ander EventType. In de documentatie zie je de verschillende types met bijbehorende args.

Acties:
  • 0 Henk 'm!

  • Lennyz
  • Registratie: Januari 2010
  • Laatst online: 25-09 09:49
Raynman schreef op vrijdag 9 juni 2017 @ 21:32:
[...]
Dat is niet heel duidelijk, maar als je de link volgt naar de documentatie voor Event, staat daar dat het attribuut 'args' een dict is (en dus geen string). Klik je dan op [source], dan zie je ook dat in de constructor (__init__) al json.loads gebruikt wordt. Die Python-wrapper doet dat dus al voor je en jij kunt gewoon event.args['text'] gebruiken om 'hello' te vinden.

Verderop in jouw code zie je ook al event.args['with_follow_on_turn']. Daar bevat de args-dict dus andere keys voor een ander EventType. In de documentatie zie je de verschillende types met bijbehorende args.
Aha! Dank je! Het werkt nu! Helemaal super!

Ik heb even onderstaande code gebruikt en het werkt zoals het zou moeten werken. Nu ga ik weer even uitzoeken hoe ik dan kan bepalen welke response Google terugzegt.

code:
1
2
3
4
5
6
        test = event.args['text']
        test2 = "hello"
        if test == test2:
            print('yes')
        else:
            print('no')

[ Voor 8% gewijzigd door Lennyz op 10-06-2017 10:29 ]