コード例 #1
0
def main():
    global ASSISTANT

    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))
    ASSISTANT = Assistant(credentials)
    GPIO.add_event_detect(PIN_BTN,
                          GPIO.FALLING,
                          callback=callback_start_conversation,
                          bouncetime=300)
    for event in ASSISTANT.start():
        process_event(event)

    while True:
        pass
コード例 #2
0
    def run(self, mainQueue, utils):
        p = multiprocessing.current_process()
        self.logger = utils._logger
        self.logger.info('Google Assistant PID: ' + str(p.pid))

        with open(
                os.path.join(os.path.expanduser('~/.config'),
                             'google-oauthlib-tool', 'credentials.json'),
                'r') as f:
            credentials = google.oauth2.credentials.Credentials(token=None,
                                                                **json.load(f))

        self.logger.info('Google Assistant: Starting')
        _assistant = Assistant(credentials, 'homepi-177214-shineon-1s9b88')
        self._assistant = _assistant

        self.register_device('homepi-177214', credentials,
                             'homepi-177214-shineon-1s9b88',
                             self._assistant.device_id)
        count = 0
        for event in _assistant.start():
            #print(event)
            _events = GoogleEvents(_assistant, utils)
            if (count == 0):
                self.logger.info('Google Assistant: Started')
            messages = _events.getEvent(event)
            self.sendMessages(mainQueue, messages)
            count += 1
コード例 #3
0
class HotwordAssistant(object):
    def __init__(self,
                 device_model_id,
                 creds_path=os.path.join(os.path.expanduser('~/.config'),
                                         'google-oauthlib-tool',
                                         'credentials.json')):
        with open(creds_path, 'r') as f:
            credentials = google.oauth2.credentials.Credentials(token=None,
                                                                **json.load(f))
            self.assistant = Assistant(credentials, device_model_id)

    def __enter__(self):
        return self

    def stop(self):
        self.assistant.__exit__(None, None, None)
        # self.assistant.stop_conversation()

    def assist(self):
        for event in self.assistant.start():

            if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
                print('Hotword detected')
                # Stopping in a separate thread to prevent blocking the main thread.
                threading.Thread(target=self.stop).start()
                return

            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_DEVICE_ACTION:
                for command, params in event.actions:
                    print('Do command', command, 'with params', str(params))

                if command == "com.example.commands.BlinkLight":
                    number = int(params['number'])
                    for i in range(int(number)):
                        print('Device is blinking.')
                        time.sleep(1)

                if command == "com.example.commands.ShowImages":
                    query = params['query']
                    print('Query is ', query)
コード例 #4
0
class FlipdotAssistant(object):
    def __init__(self, credentials, device_model_id, project_id=None):
        # Create a google assistant client
        self.assistant = Assistant(credentials, device_model_id)

        # Register device if necessary
        if project_id:
            self.register_device(
                project_id,
                credentials,
                device_model_id,
                self.assistant.device_id)

        # Create a flipapps client
        self.client = FlipAppClient()

    def __enter__(self):
        self.assistant.__enter__()
        return self

    def __exit__(self, type, value, traceback):
        self.assistant.__exit__(type, value, traceback)

    def run(self):
        events = self.assistant.start()
        for event in events:
            self.process_event(event, self.assistant.device_id)

    def show_weather(self, params):
        coordinates = None
        if params['location']:
            location_query = params['location']
            geolocator = Nominatim()
            location = geolocator.geocode(location_query)
            coordinates = (location.latitude, location.longitude)
        self.client.show_weather(coordinates=coordinates)

    def show_time(self, _):
        self.client.show_clock()

    def show_text(self, params):
        text = params['message']
        self.client.show_text(text)

    def process_event(self, event, device_id):
        """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.
            device_id(str): The device ID of the new instance.
        """
        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_DEVICE_ACTION:
            for command, params in FlipdotAssistant.process_device_actions(
                    event, device_id):
                print('Do command', command, 'with params', str(params))

                if command == "com.briggysmalls.commands.show_weather":
                    self.show_weather(params)
                elif command == "com.briggysmalls.commands.show_time":
                    self.show_time(params)
                elif command == "com.briggysmalls.commands.show_message":
                    self.show_text(params)

    @staticmethod
    def process_device_actions(event, device_id):
        if 'inputs' in event.args:
            for i in event.args['inputs']:
                if i['intent'] == 'action.devices.EXECUTE':
                    for c in i['payload']['commands']:
                        for device in c['devices']:
                            if device['id'] == device_id:
                                if 'execution' in c:
                                    for e in c['execution']:
                                        if 'params' in e:
                                            yield e['command'], e['params']
                                        else:
                                            yield e['command'], None

    @staticmethod
    def register_device(project_id, credentials, device_model_id, device_id):
        """Register the device if needed.
        Registers a new assistant device if an instance with the given id
        does not already exists for this model.
        Args:
           project_id(str): The project ID used to register device instance.
           credentials(google.oauth2.credentials.Credentials): The Google
                    OAuth2 credentials of the user to associate the device
                    instance with.
           device_model_id(str): The registered device model ID.
           device_id(str): The device ID of the new instance.
        """
        base_url = '/'.join([DEVICE_API_URL, 'projects', project_id, 'devices'])
        device_url = '/'.join([base_url, device_id])
        session = google.auth.transport.requests.AuthorizedSession(credentials)
        r = session.get(device_url)
        print(device_url, r.status_code)
        if r.status_code == 404:
            print('Registering....')
            r = session.post(base_url, data=json.dumps({
                'id': device_id,
                'model_id': device_model_id,
                'client_type': 'SDK_LIBRARY'
            }))
            if r.status_code != 200:
                raise Exception('failed to register device: ' + r.text)
            print('\rDevice registered.')
コード例 #5
0
class Google_Assistant(object):
    def __init__(self):
        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:
            self.credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f))

        self.google_assistant = threading.Thread(target=self.main)

    def INFO(self, info):
        print("Google_Assistant: %s"%info)
    def start(self):
        self.google_assistant.start()

    def process_event(self, event):
        status = None

        #self.assistant.set_mic_mute(False)

        self.INFO(event)
        if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
            status_handler.display_status = status_handler.GREETINGS

        if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
            status = self.process_status(event.args['text'])

        if event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
            if status_handler.display_status == status_handler.GREETINGS:
                status_handler.display_status = status_handler.CLEANUP

        if status != None:
            self.assistant.set_mic_mute(True)
            status_handler.display_status = status
            self.assistant.set_mic_mute(False)

    def process_status(self, text):
        text = text.lower()
        status = None
        if 'show me' in text:
            if 'date' in text or 'time' in text:
                status = 'DATETIME'
            elif 'weather' in text:
                status = 'WEATHER'
            elif 'detail' in text:
                if 'first' in text:
                    status = 'NEWS_DETAIL_1'
                elif 'second' in text:
                    status = 'NEWS_DETAIL_2'
                elif 'third' in text:
                    status = 'NEWS_DETAIL_3'
                elif 'fourth' in text:
                    status = 'NEWS_DETAIL_4'
                elif 'fifth' in text:
                    status = 'NEWS_DETAIL_5'
            elif 'news' in text:
                status = 'NEWS'
        return status

    def main(self):
        self.assistant = Assistant(self.credentials)
        for ga_event in self.assistant.start():
            status = self.process_event(ga_event)
コード例 #6
0
class Google_Assistant(object):
    def __init__(self):
        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:
            self.credentials = google.oauth2.credentials.Credentials(
                token=None, **json.load(f))

        self.google_assistant = threading.Thread(target=self.main)

    def INFO(self, info):
        print("Google_Assistant: %s" % info)

    def start(self):
        self.google_assistant.start()

    def process_event(self, event):
        status = None

        self.INFO(event)
        if event.type == EventType.ON_CONVERSATION_TURN_STARTED:
            if status_handler.display_status != 'NEWS':
                status_handler.display_status = 'GREETINGS'

        elif event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED:
            status = self.process_status(event.args['text'])

        elif event.type == EventType.ON_CONVERSATION_TURN_TIMEOUT:
            status_handler.display_status = 'CLEANUP'

        elif event.type == EventType.ON_CONVERSATION_TURN_FINISHED:
            if status_handler.display_status == 'GREETINGS':
                status_handler.display_status = 'CLEANUP'

        if status != None:
            self.assistant.set_mic_mute(True)
            status_handler.display_status = status
            self.assistant.set_mic_mute(False)

    def process_status(self, text):
        text = text.lower()
        status = None
        if text == 'hey google' or text == 'ok google':
            status = 'GREETINGS'
        if 'show me' in text:
            if 'date' in text or 'time' in text:
                status = 'DATETIME'
            elif 'weather' in text:
                status = 'WEATHER'
            elif 'news' in text:
                status = 'NEWS'
        elif 'set screensaver to' in text:
            if 'mirror' in text:
                status = 'SCREENSAVER MIRROR'
            if 'random' in text:
                status = 'SCREENSAVER RANDOM'
        return status

    def process_news(self, text):
        text = text.lower()
        status = None
        if text in CANCLE_PHRASE:
            status = 'SCREENSAVER'
        else:
            for key in numbers_en:
                if key in text:
                    status = 'NEWS_DETAIL %d' % numbers_en[key]
                    print('Detail detect!: %s' % status)
                    return status
            for i in range(0, 11):
                if str(i) in text:
                    status = 'NEWS_DETAIL %d' % i
                    print('Detail detect!: %s' % status)
                    return status
        return status

    def main(self):
        self.assistant = Assistant(self.credentials)
        for ga_event in self.assistant.start():
            status = self.process_event(ga_event)