コード例 #1
0
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')
    parser.add_argument('--device_model_id',
                        type=str,
                        metavar='DEVICE_MODEL_ID',
                        required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument('--project_id',
                        type=str,
                        metavar='PROJECT_ID',
                        required=False,
                        help='The project ID used to register device ' +
                        'instances.')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(
            ["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' + 'device_id:',
              assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials, args.device_model_id,
                            assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd = event.args
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'stream'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi/src/trackchange.py')
                    os.system(
                        'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    os.system(
                        'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())
                else:
                    os.system(
                        'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    os.system(
                        'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())

            if 'stop'.lower() in str(usrcmd).lower():
                stop()
            if 'radio'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                radio(str(usrcmd).lower())
            if 'wireless'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ESP(str(usrcmd).lower())
            if 'parcel'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                track()
            if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(
                    usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                feed(str(usrcmd).lower())
            if 'on kodi'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kodiactions(str(usrcmd).lower())
            if 'chromecast'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if 'play'.lower() in str(usrcmd).lower():
                    chromecast_play_video(str(usrcmd).lower())
                else:
                    chromecast_control(usrcmd)
            if 'pause music'.lower() in str(usrcmd).lower(
            ) or 'resume music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if ismpvplaying():
                    if 'pause music'.lower() in str(usrcmd).lower():
                        playstatus = os.system("echo '" + json.dumps(
                            {"command": ["set_property", "pause", True]}) +
                                               "' | socat - /tmp/mpvsocket")
                    elif 'resume music'.lower() in str(usrcmd).lower():
                        playstatus = os.system("echo '" + json.dumps(
                            {"command": ["set_property", "pause", False]}) +
                                               "' | socat - /tmp/mpvsocket")
                else:
                    say("Sorry nothing is playing right now")
            if 'music volume'.lower() in str(usrcmd).lower():
                if ismpvplaying():
                    if 'set'.lower() in str(usrcmd).lower() or 'change'.lower(
                    ) in str(usrcmd).lower():
                        if 'hundred'.lower() in str(usrcmd).lower(
                        ) or 'maximum' in str(usrcmd).lower():
                            settingvollevel = 100
                            with open('/home/pi/.mediavolume.json',
                                      'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol = os.system("echo '" + json.dumps({
                                "command": [
                                    "set_property", "volume",
                                    str(settingvollevel)
                                ]
                            }) + "' | socat - /tmp/mpvsocket")
                        elif 'zero'.lower() in str(usrcmd).lower(
                        ) or 'minimum' in str(usrcmd).lower():
                            settingvollevel = 0
                            with open('/home/pi/.mediavolume.json',
                                      'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol = os.system("echo '" + json.dumps({
                                "command": [
                                    "set_property", "volume",
                                    str(settingvollevel)
                                ]
                            }) + "' | socat - /tmp/mpvsocket")
                        else:
                            for settingvollevel in re.findall(
                                    r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                with open('/home/pi/.mediavolume.json',
                                          'w') as vol:
                                    json.dump(settingvollevel, vol)
                            mpvsetvol = os.system("echo '" + json.dumps({
                                "command": [
                                    "set_property", "volume",
                                    str(settingvollevel)
                                ]
                            }) + "' | socat - /tmp/mpvsocket")
                    elif 'increase'.lower() in str(usrcmd).lower(
                    ) or 'decrease'.lower() in str(usrcmd).lower(
                    ) or 'reduce'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.mediavolume.json"):
                            with open('/home/pi/.mediavolume.json',
                                      'r') as vol:
                                oldvollevel = json.load(vol)
                                for oldvollevel in re.findall(
                                        r'\b\d+\b', str(oldvollevel)):
                                    oldvollevel = int(oldvollevel)
                        else:
                            mpvgetvol = subprocess.Popen(
                                [("echo '" + json.dumps(
                                    {"command": ["get_property", "volume"]}) +
                                  "' | socat - /tmp/mpvsocket")],
                                shell=True,
                                stdout=subprocess.PIPE)
                            output = mpvgetvol.communicate()[0]
                            for oldvollevel in re.findall(
                                    r"[-+]?\d*\.\d+|\d+", str(output)):
                                oldvollevel = int(oldvollevel)

                        if 'increase'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(
                                        r'\b\d+\b', str(usrcmd)):
                                    changevollevel = int(changevollevel)
                            else:
                                changevollevel = 10
                            newvollevel = oldvollevel + changevollevel
                            print(newvollevel)
                            if newvollevel > 100:
                                settingvollevel == 100
                            elif newvollevel < 0:
                                settingvollevel == 0
                            else:
                                settingvollevel = newvollevel
                            with open('/home/pi/.mediavolume.json',
                                      'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol = os.system("echo '" + json.dumps({
                                "command": [
                                    "set_property", "volume",
                                    str(settingvollevel)
                                ]
                            }) + "' | socat - /tmp/mpvsocket")
                        if 'decrease'.lower() in str(usrcmd).lower(
                        ) or 'reduce'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(
                                        r'\b\d+\b', str(usrcmd)):
                                    changevollevel = int(changevollevel)
                            else:
                                changevollevel = 10
                            newvollevel = oldvollevel - changevollevel
                            print(newvollevel)
                            if newvollevel > 100:
                                settingvollevel == 100
                            elif newvollevel < 0:
                                settingvollevel == 0
                            else:
                                settingvollevel = newvollevel
                            with open('/home/pi/.mediavolume.json',
                                      'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol = os.system("echo '" + json.dumps({
                                "command": [
                                    "set_property", "volume",
                                    str(settingvollevel)
                                ]
                            }) + "' | socat - /tmp/mpvsocket")
                    else:
                        say("Sorry I could not help you")
                else:
                    say("Sorry nothing is playing right now")

            if 'refresh'.lower() in str(
                    usrcmd).lower() and 'music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                refreshlists()
            if 'google music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi/src/trackchange.py')
                    os.system(
                        'echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    if 'all the songs'.lower() in str(usrcmd).lower():
                        os.system(
                            'echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py'
                        )
                        say("Playing all your songs")
                        play_songs()

                    if 'playlist'.lower() in str(usrcmd).lower():
                        if 'first'.lower() in str(usrcmd).lower(
                        ) or 'one'.lower() in str(usrcmd).lower() or '1'.lower(
                        ) in str(usrcmd).lower():
                            os.system(
                                'echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            say("Playing songs from your playlist")
                            play_playlist(0)
                        else:
                            say("Sorry I am unable to help")

                    if 'album'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                            os.system("rm /home/pi/.gmusicalbumplayer.json")

                        req = str(usrcmd).lower()
                        idx = (req).find('album')
                        album = req[idx:]
                        album = album.replace("'}", "", 1)
                        album = album.replace('album', '', 1)
                        if 'from'.lower() in req:
                            album = album.replace('from', '', 1)
                            album = album.replace('google music', '', 1)
                        else:
                            album = album.replace('google music', '', 1)

                        album = album.strip()
                        print(album)
                        albumstr = ('"' + album + '"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_album(' + albumstr + ')')
                        f.close()
                        say("Looking for songs from the album")
                        play_album(album)

                    if 'artist'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                            os.system("rm /home/pi/.gmusicartistplayer.json")

                        req = str(usrcmd).lower()
                        idx = (req).find('artist')
                        artist = req[idx:]
                        artist = artist.replace("'}", "", 1)
                        artist = artist.replace('artist', '', 1)
                        if 'from'.lower() in req:
                            artist = artist.replace('from', '', 1)
                            artist = artist.replace('google music', '', 1)
                        else:
                            artist = artist.replace('google music', '', 1)

                        artist = artist.strip()
                        print(artist)
                        artiststr = ('"' + artist + '"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_artist(' + artiststr + ')')
                        f.close()
                        say("Looking for songs rendered by the artist")
                        play_artist(artist)
                else:
                    os.system(
                        'echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                    )
                    if 'all the songs'.lower() in str(usrcmd).lower():
                        os.system(
                            'echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py'
                        )
                        say("Playing all your songs")
                        play_songs()

                    if 'playlist'.lower() in str(usrcmd).lower():
                        if 'first'.lower() in str(usrcmd).lower(
                        ) or 'one'.lower() in str(usrcmd).lower() or '1'.lower(
                        ) in str(usrcmd).lower():
                            os.system(
                                'echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            say("Playing songs from your playlist")
                            play_playlist(0)
                        else:
                            say("Sorry I am unable to help")

                    if 'album'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                            os.system("rm /home/pi/.gmusicalbumplayer.json")

                        req = str(usrcmd).lower()
                        idx = (req).find('album')
                        album = req[idx:]
                        album = album.replace("'}", "", 1)
                        album = album.replace('album', '', 1)
                        if 'from'.lower() in req:
                            album = album.replace('from', '', 1)
                            album = album.replace('google music', '', 1)
                        else:
                            album = album.replace('google music', '', 1)

                        album = album.strip()
                        print(album)
                        albumstr = ('"' + album + '"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_album(' + albumstr + ')')
                        f.close()
                        say("Looking for songs from the album")
                        play_album(album)

                    if 'artist'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                            os.system("rm /home/pi/.gmusicartistplayer.json")

                        req = str(usrcmd).lower()
                        idx = (req).find('artist')
                        artist = req[idx:]
                        artist = artist.replace("'}", "", 1)
                        artist = artist.replace('artist', '', 1)
                        if 'from'.lower() in req:
                            artist = artist.replace('from', '', 1)
                            artist = artist.replace('google music', '', 1)
                        else:
                            artist = artist.replace('google music', '', 1)

                        artist = artist.strip()
                        print(artist)
                        artiststr = ('"' + artist + '"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_artist(' + artiststr + ')')
                        f.close()
                        say("Looking for songs rendered by the artist")
                        play_artist(artist)
コード例 #2
0
ファイル: pushbutton.py プロジェクト: sup3rgiu/GassistPi-IT
    def assist(self):
        """Send a voice request to the Assistant and playback the response.

        Returns: True if conversation should continue.
        """
        continue_conversation = False
        device_actions_futures = []
        subprocess.Popen(
            ["aplay", "/home/pi/GassistPi-IT/sample-audio-files/Fb.wav"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        self.conversation_stream.start_recording()
        #Uncomment the following after starting the Kodi
        #status=mutevolstatus()
        #vollevel=status[1]
        #with open('/home/pi/.volume.json', 'w') as f:
        #json.dump(vollevel, f)
        #kodi.Application.SetVolume({"volume": 0})
        GPIO.output(5, GPIO.HIGH)
        led.ChangeDutyCycle(100)
        if ismpvplaying():
            if os.path.isfile("/home/pi/.mediavolume.json"):
                mpvsetvol = os.system(
                    "echo '" +
                    json.dumps({"command": ["set_property", "volume", "10"]}) +
                    "' | socat - /tmp/mpvsocket")
            else:
                mpvgetvol = subprocess.Popen(
                    [("echo '" +
                      json.dumps({"command": ["get_property", "volume"]}) +
                      "' | socat - /tmp/mpvsocket")],
                    shell=True,
                    stdout=subprocess.PIPE)
                output = mpvgetvol.communicate()[0]
                for currntvol in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                        json.dump(currntvol, vol)
                mpvsetvol = os.system(
                    "echo '" +
                    json.dumps({"command": ["set_property", "volume", "10"]}) +
                    "' | socat - /tmp/mpvsocket")

        logging.info('Recording audio request.')

        def iter_assist_requests():
            for c in self.gen_assist_requests():
                assistant_helpers.log_assist_request_without_audio(c)
                yield c
            self.conversation_stream.start_playback()

        # This generator yields AssistResponse proto messages
        # received from the gRPC Google Assistant API.
        for resp in self.assistant.Assist(iter_assist_requests(),
                                          self.deadline):
            assistant_helpers.log_assist_response_without_audio(resp)
            if resp.event_type == END_OF_UTTERANCE:
                logging.info('End of audio request detected')
                GPIO.output(5, GPIO.LOW)
                led.ChangeDutyCycle(0)
                self.conversation_stream.stop_recording()

            if resp.speech_results:
                logging.info(
                    'Transcript of user request: "%s".',
                    ' '.join(r.transcript for r in resp.speech_results))

                for r in resp.speech_results:
                    usercommand = str(r)

                if "stability: 1.0" in usercommand.lower():
                    usrcmd = str(usercommand).lower()
                    idx = usrcmd.find('stability')
                    usrcmd = usrcmd[:idx]
                    usrcmd = usrcmd.replace("stability", "", 1)
                    usrcmd = usrcmd.strip()
                    usrcmd = usrcmd.replace('transcript: "', '', 1)
                    usrcmd = usrcmd.replace('"', '', 1)
                    usrcmd = usrcmd.strip()
                    print(str(usrcmd))
                    for num, name in enumerate(tasmota_devicelist):
                        if name.lower() in str(usrcmd).lower():
                            tasmota_control(
                                str(usrcmd).lower(), name.lower(),
                                tasmota_deviceip[num])
                            return continue_conversation
                            break
                    with open('/home/pi/GassistPi-IT/src/diyHue/config.json',
                              'r') as config:
                        hueconfig = json.load(config)
                    for i in range(1, len(hueconfig['lights']) + 1):
                        try:
                            if str(hueconfig['lights'][str(i)]
                                   ['name']).lower() in str(usrcmd).lower():
                                assistant.stop_conversation()
                                hue_control(
                                    str(usrcmd).lower(), str(i),
                                    str(hueconfig['lights_address'][str(i)]
                                        ['ip']))
                                break
                        except Keyerror:
                            say('Unable to help, please check your config file'
                                )

                    if 'magic mirror'.lower() in str(usrcmd).lower():
                        assistant.stop_conversation()
                        try:
                            mmmcommand = str(usrcmd).lower()
                            if 'weather'.lower() in mmmcommand:
                                if 'show'.lower() in mmmcommand:
                                    mmreq_one = requests.get(
                                        "http://" + mmmip +
                                        ":8080/remote?action=SHOW&module=module_2_currentweather"
                                    )
                                    mmreq_two = requests.get(
                                        "http://" + mmmip +
                                        ":8080/remote?action=SHOW&module=module_3_currentweather"
                                    )
                                if 'hide'.lower() in mmmcommand:
                                    mmreq_one = requests.get(
                                        "http://" + mmmip +
                                        ":8080/remote?action=HIDE&module=module_2_currentweather"
                                    )
                                    mmreq_two = requests.get(
                                        "http://" + mmmip +
                                        ":8080/remote?action=HIDE&module=module_3_currentweather"
                                    )
                            if 'power off'.lower() in mmmcommand:
                                mmreq = requests.get(
                                    "http://" + mmmip +
                                    ":8080/remote?action=SHUTDOWN")
                            if 'reboot'.lower() in mmmcommand:
                                mmreq = requests.get(
                                    "http://" + mmmip +
                                    ":8080/remote?action=REBOOT")
                            if 'restart'.lower() in mmmcommand:
                                mmreq = requests.get(
                                    "http://" + mmmip +
                                    ":8080/remote?action=RESTART")
                            if 'display on'.lower() in mmmcommand:
                                mmreq = requests.get(
                                    "http://" + mmmip +
                                    ":8080/remote?action=MONITORON")
                            if 'display off'.lower() in mmmcommand:
                                mmreq = requests.get(
                                    "http://" + mmmip +
                                    ":8080/remote?action=MONITOROFF")
                        except requests.exceptions.ConnectionError:
                            say("Magic mirror not online")
                    if 'ingredients'.lower() in str(usrcmd).lower():
                        assistant.stop_conversation()
                        ingrequest = str(usrcmd).lower()
                        ingredientsidx = ingrequest.find('for')
                        ingrequest = ingrequest[ingredientsidx:]
                        ingrequest = ingrequest.replace('for', "", 1)
                        ingrequest = ingrequest.replace("'}", "", 1)
                        ingrequest = ingrequest.strip()
                        ingrequest = ingrequest.replace(" ", "%20", 1)
                        getrecipe(ingrequest)
                    if 'kickstarter'.lower() in str(usrcmd).lower():
                        assistant.stop_conversation()
                        kickstarter_tracker(str(usrcmd).lower())
                    if 'trigger'.lower() in str(usrcmd).lower():
                        Action(str(usrcmd).lower())
                        return continue_conversation
                    if 'stream'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile(
                                "/home/pi/GassistPi-IT/src/trackchange.py"):
                            os.system(
                                'rm /home/pi/GassistPi-IT/src/trackchange.py')
                            os.system(
                                'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py'
                            )
                            os.system(
                                'echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py'
                            )
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        else:
                            os.system(
                                'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py'
                            )
                            os.system(
                                'echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py'
                            )
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        return continue_conversation
                    if 'stop'.lower() in str(usrcmd).lower():
                        stop()
                        return continue_conversation
                    if 'radio'.lower() in str(usrcmd).lower():
                        radio(str(usrcmd).lower())
                        return continue_conversation
                    if 'wireless'.lower() in str(usrcmd).lower():
                        ESP(str(usrcmd).lower())
                        return continue_conversation
                    if 'parcel'.lower() in str(usrcmd).lower():
                        track()
                        return continue_conversation
                    if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower(
                    ) in str(usrcmd).lower() or 'quote'.lower() in str(
                            usrcmd).lower():
                        feed(str(usrcmd).lower())
                        return continue_conversation
                    if 'on kodi'.lower() in str(usrcmd).lower():
                        kodiactions(str(usrcmd).lower())
                        return continue_conversation
                    if 'chromecast'.lower() in str(usrcmd).lower():
                        if 'play'.lower() in str(usrcmd).lower():
                            chromecast_play_video(str(usrcmd).lower())
                        else:
                            chromecast_control(usrcmd)
                        return continue_conversation
                    if 'pause music'.lower() in str(usrcmd).lower(
                    ) or 'resume music'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'pause music'.lower() in str(usrcmd).lower():
                                playstatus = os.system("echo '" + json.dumps({
                                    "command": ["set_property", "pause", True]
                                }) + "' | socat - /tmp/mpvsocket")
                            elif 'resume music'.lower() in str(usrcmd).lower():
                                playstatus = os.system("echo '" + json.dumps({
                                    "command":
                                    ["set_property", "pause", False]
                                }) + "' | socat - /tmp/mpvsocket")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation
                    if 'music volume'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'set'.lower() in str(usrcmd).lower(
                            ) or 'change'.lower() in str(usrcmd).lower():
                                if 'hundred'.lower() in str(usrcmd).lower(
                                ) or 'maximum' in str(usrcmd).lower():
                                    settingvollevel = 100
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                elif 'zero'.lower() in str(usrcmd).lower(
                                ) or 'minimum' in str(usrcmd).lower():
                                    settingvollevel = 0
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                else:
                                    for settingvollevel in re.findall(
                                            r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                        with open('/home/pi/.mediavolume.json',
                                                  'w') as vol:
                                            json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                            elif 'increase'.lower() in str(usrcmd).lower(
                            ) or 'decrease'.lower() in str(usrcmd).lower(
                            ) or 'reduce'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.mediavolume.json"):
                                    with open('/home/pi/.mediavolume.json',
                                              'r') as vol:
                                        oldvollevel = json.load(vol)
                                        for oldvollevel in re.findall(
                                                r'\b\d+\b', str(oldvollevel)):
                                            oldvollevel = int(oldvollevel)
                                else:
                                    mpvgetvol = subprocess.Popen(
                                        [("echo '" + json.dumps({
                                            "command":
                                            ["get_property", "volume"]
                                        }) + "' | socat - /tmp/mpvsocket")],
                                        shell=True,
                                        stdout=subprocess.PIPE)
                                    output = mpvgetvol.communicate()[0]
                                    for oldvollevel in re.findall(
                                            r"[-+]?\d*\.\d+|\d+", str(output)):
                                        oldvollevel = int(oldvollevel)

                                if 'increase'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit()
                                           for char in str(usrcmd)):
                                        for changevollevel in re.findall(
                                                r'\b\d+\b', str(usrcmd)):
                                            changevollevel = int(
                                                changevollevel)
                                    else:
                                        changevollevel = 10
                                    newvollevel = oldvollevel + changevollevel
                                    print(newvollevel)
                                    if newvollevel > 100:
                                        settingvollevel == 100
                                    elif newvollevel < 0:
                                        settingvollevel == 0
                                    else:
                                        settingvollevel = newvollevel
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                if 'decrease'.lower() in str(usrcmd).lower(
                                ) or 'reduce'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit()
                                           for char in str(usrcmd)):
                                        for changevollevel in re.findall(
                                                r'\b\d+\b', str(usrcmd)):
                                            changevollevel = int(
                                                changevollevel)
                                    else:
                                        changevollevel = 10
                                    newvollevel = oldvollevel - changevollevel
                                    print(newvollevel)
                                    if newvollevel > 100:
                                        settingvollevel == 100
                                    elif newvollevel < 0:
                                        settingvollevel == 0
                                    else:
                                        settingvollevel = newvollevel
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                            else:
                                say("Sorry I could not help you")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation

                    if 'refresh'.lower() in str(usrcmd).lower(
                    ) and 'music'.lower() in str(usrcmd).lower():
                        refreshlists()
                        return continue_conversation
                    if 'google music'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile(
                                "/home/pi/GassistPi-IT/src/trackchange.py"):
                            os.system(
                                'rm /home/pi/GassistPi-IT/src/trackchange.py')
                            gmusicselect(str(usrcmd).lower())
                        else:
                            gmusicselect(str(usrcmd).lower())
                        return continue_conversation

                    else:
                        continue
                GPIO.output(5, GPIO.LOW)
                GPIO.output(6, GPIO.HIGH)
                led.ChangeDutyCycle(50)
                logging.info('Playing assistant response.')
            if len(resp.audio_out.audio_data) > 0:
                self.conversation_stream.write(resp.audio_out.audio_data)
            if resp.dialog_state_out.conversation_state:
                conversation_state = resp.dialog_state_out.conversation_state
                logging.debug('Updating conversation state.')
                self.conversation_state = conversation_state
            if resp.dialog_state_out.volume_percentage != 0:
                volume_percentage = resp.dialog_state_out.volume_percentage
                logging.info('Setting volume to %s%%', volume_percentage)
                self.conversation_stream.volume_percentage = volume_percentage
            if resp.dialog_state_out.microphone_mode == DIALOG_FOLLOW_ON:
                continue_conversation = True
                GPIO.output(6, GPIO.LOW)
                GPIO.output(5, GPIO.HIGH)
                led.ChangeDutyCycle(100)
                logging.info('Expecting follow-on query from user.')
            elif resp.dialog_state_out.microphone_mode == CLOSE_MICROPHONE:
                GPIO.output(6, GPIO.LOW)
                GPIO.output(5, GPIO.LOW)
                led.ChangeDutyCycle(0)
                if ismpvplaying():
                    if os.path.isfile("/home/pi/.mediavolume.json"):
                        with open('/home/pi/.mediavolume.json', 'r') as vol:
                            oldvollevel = json.load(vol)
                            print(oldvollevel)
                        mpvsetvol = os.system("echo '" + json.dumps({
                            "command":
                            ["set_property", "volume",
                             str(oldvollevel)]
                        }) + "' | socat - /tmp/mpvsocket")

                #Uncomment the following, after starting Kodi
                #with open('/home/pi/.volume.json', 'r') as f:
                #vollevel = json.load(f)
                #kodi.Application.SetVolume({"volume": vollevel})
                continue_conversation = False
            if resp.device_action.device_request_json:
                device_request = json.loads(
                    resp.device_action.device_request_json)
                fs = self.device_handler(device_request)
                if fs:
                    device_actions_futures.extend(fs)

        if len(device_actions_futures):
            logging.info('Waiting for device executions to complete.')
            concurrent.futures.wait(device_actions_futures)

        logging.info('Finished playing assistant response.')
        self.conversation_stream.stop_playback()
        return continue_conversation
コード例 #3
0
ファイル: main.py プロジェクト: sup3rgiu/GassistPi-IT
def main():
    init_pubnub()
    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')
    parser.add_argument('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument(
        '--project_id',
        type=str,
        metavar='PROJECT_ID',
        required=False,
        help='The project ID used to register device instances.')
    parser.add_argument(
        '-v',
        '--version',
        action='version',
        version='%(prog)s ' +
        Assistant.__version_str__())

    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi-IT/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd=event.args
            with open('/home/pi/GassistPi-IT/src/diyHue/config.json', 'r') as config:
                 hueconfig = json.load(config)
            for i in range(1,len(hueconfig['lights'])+1):
                try:
                    if str(hueconfig['lights'][str(i)]['name']).lower() in str(usrcmd).lower():
                        assistant.stop_conversation()
                        hue_control(str(usrcmd).lower(),str(i),str(hueconfig['lights_address'][str(i)]['ip']))
                        break
                except Keyerror:
                    say('Unable to help, please check your config file')

            for num, name in enumerate(tasmota_devicelist):
                if name.lower() in str(usrcmd).lower():
                    assistant.stop_conversation()
                    tasmota_control(str(usrcmd).lower(), name.lower(),tasmota_deviceip[num])
                    break
            if 'lampadina'.lower() in str(usrcmd).lower():		
                assistant.stop_conversation()
                if 'accendi'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Accesa")
                elif 'spegni'.lower() in str(usrcmd).lower():
                    url = ''
                    r = requests.post(url, data="")
                    say("Lampadina Spenta")        
            if 'magic mirror'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                try:
                    mmmcommand=str(usrcmd).lower()
                    if 'weather'.lower() in mmmcommand:
                        if 'show'.lower() in mmmcommand:
                            mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_2_currentweather")
                            mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=SHOW&module=module_3_currentweather")
                        if 'hide'.lower() in mmmcommand:
                            mmreq_one=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_2_currentweather")
                            mmreq_two=requests.get("http://"+mmmip+":8080/remote?action=HIDE&module=module_3_currentweather")
                    if 'power off'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=SHUTDOWN")
                    if 'reboot'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=REBOOT")
                    if 'restart'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=RESTART")
                    if 'display on'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITORON")
                    if 'display off'.lower() in mmmcommand:
                        mmreq=requests.get("http://"+mmmip+":8080/remote?action=MONITOROFF")
                except requests.exceptions.ConnectionError:
                    say("Magic mirror not online")
            if 'ingredients'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ingrequest=str(usrcmd).lower()
                ingredientsidx=ingrequest.find('for')
                ingrequest=ingrequest[ingredientsidx:]
                ingrequest=ingrequest.replace('for',"",1)
                ingrequest=ingrequest.replace("'}","",1)
                ingrequest=ingrequest.strip()
                ingrequest=ingrequest.replace(" ","%20",1)
                getrecipe(ingrequest)
            if 'kickstarter'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kickstarter_tracker(str(usrcmd).lower())
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'avvia'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())
                else:
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi-IT/src/trackchange.py')
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())

            if 'ferma'.lower() in str(usrcmd).lower():
                stop()
            if 'radio'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                radio(str(usrcmd).lower())
            if 'wireless'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ESP(str(usrcmd).lower())
            if 'parcel'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                track()
            if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                feed(str(usrcmd).lower())
            if 'on kodi'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kodiactions(str(usrcmd).lower())
            if 'chromecast'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if 'play'.lower() in str(usrcmd).lower():
                    chromecast_play_video(str(usrcmd).lower())
                else:
                    chromecast_control(usrcmd)
            if 'pause music'.lower() in str(usrcmd).lower() or 'resume music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if ismpvplaying():
                    if 'pause music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", True]})+"' | socat - /tmp/mpvsocket")
                    elif 'resume music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", False]})+"' | socat - /tmp/mpvsocket")
                else:
                    say("Sorry nothing is playing right now")
            if 'music volume'.lower() in str(usrcmd).lower():
                if ismpvplaying():
                    if 'set'.lower() in str(usrcmd).lower() or 'change'.lower() in str(usrcmd).lower():
                        if 'hundred'.lower() in str(usrcmd).lower() or 'maximum' in str(usrcmd).lower():
                            settingvollevel=100
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        elif 'zero'.lower() in str(usrcmd).lower() or 'minimum' in str(usrcmd).lower():
                            settingvollevel=0
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        else:
                            for settingvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                with open('/home/pi/.mediavolume.json', 'w') as vol:
                                    json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    elif 'increase'.lower() in str(usrcmd).lower() or 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.mediavolume.json"):
                            with open('/home/pi/.mediavolume.json', 'r') as vol:
                                oldvollevel = json.load(vol)
                                for oldvollevel in re.findall(r'\b\d+\b', str(oldvollevel)):
                                    oldvollevel=int(oldvollevel)
                        else:
                            mpvgetvol=subprocess.Popen([("echo '"+json.dumps({ "command": ["get_property", "volume"]})+"' | socat - /tmp/mpvsocket")],shell=True, stdout=subprocess.PIPE)
                            output=mpvgetvol.communicate()[0]
                            for oldvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                                oldvollevel=int(oldvollevel)

                        if 'increase'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel+ changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        if 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel - changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    else:
                        say("Sorry I could not help you")
                else:
                    say("Sorry nothing is playing right now")

            if 'refresh'.lower() in str(usrcmd).lower() and 'music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                refreshlists()
            if 'google music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi-IT/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi-IT/src/trackchange.py')
                    gmusicselect(str(usrcmd).lower())
                else:
                    gmusicselect(str(usrcmd).lower())
コード例 #4
0
    def assist(self):
        """Send a voice request to the Assistant and playback the response.

        Returns: True if conversation should continue.
        """
        continue_conversation = False
        device_actions_futures = []
        subprocess.Popen(
            ["aplay", "/home/pi/GassistPi/sample-audio-files/Fb.wav"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        self.conversation_stream.start_recording()
        #Uncomment the following after starting the Kodi
        #status=mutevolstatus()
        #vollevel=status[1]
        #with open('/home/pi/.volume.json', 'w') as f:
        #json.dump(vollevel, f)
        #kodi.Application.SetVolume({"volume": 0})
        GPIO.output(5, GPIO.HIGH)
        led.ChangeDutyCycle(100)
        if ismpvplaying():
            if os.path.isfile("/home/pi/.mediavolume.json"):
                mpvsetvol = os.system(
                    "echo '" +
                    json.dumps({"command": ["set_property", "volume", "10"]}) +
                    "' | socat - /tmp/mpvsocket")
            else:
                mpvgetvol = subprocess.Popen(
                    [("echo '" +
                      json.dumps({"command": ["get_property", "volume"]}) +
                      "' | socat - /tmp/mpvsocket")],
                    shell=True,
                    stdout=subprocess.PIPE)
                output = mpvgetvol.communicate()[0]
                for currntvol in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                        json.dump(currntvol, vol)
                mpvsetvol = os.system(
                    "echo '" +
                    json.dumps({"command": ["set_property", "volume", "10"]}) +
                    "' | socat - /tmp/mpvsocket")

        logging.info('Recording audio request.')

        def iter_assist_requests():
            for c in self.gen_assist_requests():
                assistant_helpers.log_assist_request_without_audio(c)
                yield c
            self.conversation_stream.start_playback()

        # This generator yields AssistResponse proto messages
        # received from the gRPC Google Assistant API.
        for resp in self.assistant.Assist(iter_assist_requests(),
                                          self.deadline):
            assistant_helpers.log_assist_response_without_audio(resp)
            if resp.event_type == END_OF_UTTERANCE:
                logging.info('End of audio request detected')
                GPIO.output(5, GPIO.LOW)
                led.ChangeDutyCycle(0)
                self.conversation_stream.stop_recording()

            if resp.speech_results:
                logging.info(
                    'Transcript of user request: "%s".',
                    ' '.join(r.transcript for r in resp.speech_results))

                for r in resp.speech_results:
                    usercommand = str(r)

                if "stability: 1.0" in usercommand.lower():
                    usrcmd = str(usercommand).lower()
                    idx = usrcmd.find('stability')
                    usrcmd = usrcmd[:idx]
                    usrcmd = usrcmd.replace("stability", "", 1)
                    usrcmd = usrcmd.strip()
                    usrcmd = usrcmd.replace('transcript: "', '', 1)
                    usrcmd = usrcmd.replace('"', '', 1)
                    usrcmd = usrcmd.strip()
                    print(str(usrcmd))
                    if 'trigger'.lower() in str(usrcmd).lower():
                        Action(str(usrcmd).lower())
                        return continue_conversation
                    if 'stream'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile(
                                "/home/pi/GassistPi/src/trackchange.py"):
                            os.system(
                                'rm /home/pi/GassistPi/src/trackchange.py')
                            os.system(
                                'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            os.system(
                                'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        else:
                            os.system(
                                'echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            os.system(
                                'echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        return continue_conversation
                    if 'stop'.lower() in str(usrcmd).lower():
                        stop()
                        return continue_conversation
                    if 'radio'.lower() in str(usrcmd).lower():
                        radio(str(usrcmd).lower())
                        return continue_conversation
                    if 'wireless'.lower() in str(usrcmd).lower():
                        ESP(str(usrcmd).lower())
                        return continue_conversation
                    if 'parcel'.lower() in str(usrcmd).lower():
                        track()
                        return continue_conversation
                    if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower(
                    ) in str(usrcmd).lower() or 'quote'.lower() in str(
                            usrcmd).lower():
                        feed(str(usrcmd).lower())
                        return continue_conversation
                    if 'on kodi'.lower() in str(usrcmd).lower():
                        kodiactions(str(usrcmd).lower())
                        return continue_conversation
                    if 'chromecast'.lower() in str(usrcmd).lower():
                        if 'play'.lower() in str(usrcmd).lower():
                            chromecast_play_video(str(usrcmd).lower())
                        else:
                            chromecast_control(usrcmd)
                        return continue_conversation
                    if 'pause music'.lower() in str(usrcmd).lower(
                    ) or 'resume music'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'pause music'.lower() in str(usrcmd).lower():
                                playstatus = os.system("echo '" + json.dumps({
                                    "command": ["set_property", "pause", True]
                                }) + "' | socat - /tmp/mpvsocket")
                            elif 'resume music'.lower() in str(usrcmd).lower():
                                playstatus = os.system("echo '" + json.dumps({
                                    "command":
                                    ["set_property", "pause", False]
                                }) + "' | socat - /tmp/mpvsocket")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation
                    if 'music volume'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'set'.lower() in str(usrcmd).lower(
                            ) or 'change'.lower() in str(usrcmd).lower():
                                if 'hundred'.lower() in str(usrcmd).lower(
                                ) or 'maximum' in str(usrcmd).lower():
                                    settingvollevel = 100
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                elif 'zero'.lower() in str(usrcmd).lower(
                                ) or 'minimum' in str(usrcmd).lower():
                                    settingvollevel = 0
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                else:
                                    for settingvollevel in re.findall(
                                            r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                        with open('/home/pi/.mediavolume.json',
                                                  'w') as vol:
                                            json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                            elif 'increase'.lower() in str(usrcmd).lower(
                            ) or 'decrease'.lower() in str(usrcmd).lower(
                            ) or 'reduce'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.mediavolume.json"):
                                    with open('/home/pi/.mediavolume.json',
                                              'r') as vol:
                                        oldvollevel = json.load(vol)
                                        for oldvollevel in re.findall(
                                                r'\b\d+\b', str(oldvollevel)):
                                            oldvollevel = int(oldvollevel)
                                else:
                                    mpvgetvol = subprocess.Popen(
                                        [("echo '" + json.dumps({
                                            "command":
                                            ["get_property", "volume"]
                                        }) + "' | socat - /tmp/mpvsocket")],
                                        shell=True,
                                        stdout=subprocess.PIPE)
                                    output = mpvgetvol.communicate()[0]
                                    for oldvollevel in re.findall(
                                            r"[-+]?\d*\.\d+|\d+", str(output)):
                                        oldvollevel = int(oldvollevel)

                                if 'increase'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit()
                                           for char in str(usrcmd)):
                                        for changevollevel in re.findall(
                                                r'\b\d+\b', str(usrcmd)):
                                            changevollevel = int(
                                                changevollevel)
                                    else:
                                        changevollevel = 10
                                    newvollevel = oldvollevel + changevollevel
                                    print(newvollevel)
                                    if newvollevel > 100:
                                        settingvollevel == 100
                                    elif newvollevel < 0:
                                        settingvollevel == 0
                                    else:
                                        settingvollevel = newvollevel
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                                if 'decrease'.lower() in str(usrcmd).lower(
                                ) or 'reduce'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit()
                                           for char in str(usrcmd)):
                                        for changevollevel in re.findall(
                                                r'\b\d+\b', str(usrcmd)):
                                            changevollevel = int(
                                                changevollevel)
                                    else:
                                        changevollevel = 10
                                    newvollevel = oldvollevel - changevollevel
                                    print(newvollevel)
                                    if newvollevel > 100:
                                        settingvollevel == 100
                                    elif newvollevel < 0:
                                        settingvollevel == 0
                                    else:
                                        settingvollevel = newvollevel
                                    with open('/home/pi/.mediavolume.json',
                                              'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol = os.system(
                                        "echo '" + json.dumps({
                                            "command": [
                                                "set_property", "volume",
                                                str(settingvollevel)
                                            ]
                                        }) + "' | socat - /tmp/mpvsocket")
                            else:
                                say("Sorry I could not help you")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation

                    if 'refresh'.lower() in str(usrcmd).lower(
                    ) and 'music'.lower() in str(usrcmd).lower():
                        refreshlists()
                        return continue_conversation
                    if 'google music'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile(
                                "/home/pi/GassistPi/src/trackchange.py"):
                            os.system(
                                'rm /home/pi/GassistPi/src/trackchange.py')
                            os.system(
                                'echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            if 'all the songs'.lower() in str(usrcmd).lower():
                                os.system(
                                    'echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py'
                                )
                                say("Playing all your songs")
                                play_songs()

                            if 'playlist'.lower() in str(usrcmd).lower():
                                if 'first'.lower() in str(usrcmd).lower(
                                ) or 'one'.lower() in str(usrcmd).lower(
                                ) or '1'.lower() in str(usrcmd).lower():
                                    os.system(
                                        'echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py'
                                    )
                                    say("Playing songs from your playlist")
                                    play_playlist(0)
                                else:
                                    say("Sorry I am unable to help")

                            if 'album'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.gmusicalbumplayer.json"):
                                    os.system(
                                        "rm /home/pi/.gmusicalbumplayer.json")

                                req = str(usrcmd).lower()
                                idx = (req).find('album')
                                album = req[idx:]
                                album = album.replace("'}", "", 1)
                                album = album.replace('album', '', 1)
                                if 'from'.lower() in req:
                                    album = album.replace('from', '', 1)
                                    album = album.replace(
                                        'google music', '', 1)
                                else:
                                    album = album.replace(
                                        'google music', '', 1)

                                album = album.strip()
                                print(album)
                                albumstr = ('"' + album + '"')
                                f = open(
                                    '/home/pi/GassistPi/src/trackchange.py',
                                    'a+')
                                f.write('play_album(' + albumstr + ')')
                                f.close()
                                say("Looking for songs from the album")
                                play_album(album)

                            if 'artist'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.gmusicartistplayer.json"):
                                    os.system(
                                        "rm /home/pi/.gmusicartistplayer.json")

                                req = str(usrcmd).lower()
                                idx = (req).find('artist')
                                artist = req[idx:]
                                artist = artist.replace("'}", "", 1)
                                artist = artist.replace('artist', '', 1)
                                if 'from'.lower() in req:
                                    artist = artist.replace('from', '', 1)
                                    artist = artist.replace(
                                        'google music', '', 1)
                                else:
                                    artist = artist.replace(
                                        'google music', '', 1)

                                artist = artist.strip()
                                print(artist)
                                artiststr = ('"' + artist + '"')
                                f = open(
                                    '/home/pi/GassistPi/src/trackchange.py',
                                    'a+')
                                f.write('play_artist(' + artiststr + ')')
                                f.close()
                                say("Looking for songs rendered by the artist")
                                play_artist(artist)
                        else:
                            os.system(
                                'echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py'
                            )
                            if 'all the songs'.lower() in str(usrcmd).lower():
                                os.system(
                                    'echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py'
                                )
                                say("Playing all your songs")
                                play_songs()

                            if 'playlist'.lower() in str(usrcmd).lower():
                                if 'first'.lower() in str(usrcmd).lower(
                                ) or 'one'.lower() in str(usrcmd).lower(
                                ) or '1'.lower() in str(usrcmd).lower():
                                    os.system(
                                        'echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py'
                                    )
                                    say("Playing songs from your playlist")
                                    play_playlist(0)
                                else:
                                    say("Sorry I am unable to help")

                            if 'album'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.gmusicalbumplayer.json"):
                                    os.system(
                                        "rm /home/pi/.gmusicalbumplayer.json")

                                req = str(usrcmd).lower()
                                idx = (req).find('album')
                                album = req[idx:]
                                album = album.replace("'}", "", 1)
                                album = album.replace('album', '', 1)
                                if 'from'.lower() in req:
                                    album = album.replace('from', '', 1)
                                    album = album.replace(
                                        'google music', '', 1)
                                else:
                                    album = album.replace(
                                        'google music', '', 1)

                                album = album.strip()
                                print(album)
                                albumstr = ('"' + album + '"')
                                f = open(
                                    '/home/pi/GassistPi/src/trackchange.py',
                                    'a+')
                                f.write('play_album(' + albumstr + ')')
                                f.close()
                                say("Looking for songs from the album")
                                play_album(album)

                            if 'artist'.lower() in str(usrcmd).lower():
                                if os.path.isfile(
                                        "/home/pi/.gmusicartistplayer.json"):
                                    os.system(
                                        "rm /home/pi/.gmusicartistplayer.json")

                                req = str(usrcmd).lower()
                                idx = (req).find('artist')
                                artist = req[idx:]
                                artist = artist.replace("'}", "", 1)
                                artist = artist.replace('artist', '', 1)
                                if 'from'.lower() in req:
                                    artist = artist.replace('from', '', 1)
                                    artist = artist.replace(
                                        'google music', '', 1)
                                else:
                                    artist = artist.replace(
                                        'google music', '', 1)

                                artist = artist.strip()
                                print(artist)
                                artiststr = ('"' + artist + '"')
                                f = open(
                                    '/home/pi/GassistPi/src/trackchange.py',
                                    'a+')
                                f.write('play_artist(' + artiststr + ')')
                                f.close()
                                say("Looking for songs rendered by the artist")
                                play_artist(artist)
                        return continue_conversation

                else:
                    continue
                GPIO.output(5, GPIO.LOW)
                GPIO.output(6, GPIO.HIGH)
                led.ChangeDutyCycle(50)
                logging.info('Playing assistant response.')
            if len(resp.audio_out.audio_data) > 0:
                self.conversation_stream.write(resp.audio_out.audio_data)
            if resp.dialog_state_out.conversation_state:
                conversation_state = resp.dialog_state_out.conversation_state
                logging.debug('Updating conversation state.')
                self.conversation_state = conversation_state
            if resp.dialog_state_out.volume_percentage != 0:
                volume_percentage = resp.dialog_state_out.volume_percentage
                logging.info('Setting volume to %s%%', volume_percentage)
                self.conversation_stream.volume_percentage = volume_percentage
            if resp.dialog_state_out.microphone_mode == DIALOG_FOLLOW_ON:
                continue_conversation = True
                GPIO.output(6, GPIO.LOW)
                GPIO.output(5, GPIO.HIGH)
                led.ChangeDutyCycle(100)
                logging.info('Expecting follow-on query from user.')
            elif resp.dialog_state_out.microphone_mode == CLOSE_MICROPHONE:
                continue_conversation = False
            if resp.device_action.device_request_json:
                device_request = json.loads(
                    resp.device_action.device_request_json)
                fs = self.device_handler(device_request)
                if fs:
                    device_actions_futures.extend(fs)

        if len(device_actions_futures):
            logging.info('Waiting for device executions to complete.')
            concurrent.futures.wait(device_actions_futures)

        logging.info('Finished playing assistant response.')
        GPIO.output(6, GPIO.LOW)
        GPIO.output(5, GPIO.LOW)
        led.ChangeDutyCycle(0)
        #Uncomment the following, after starting Kodi
        #with open('/home/pi/.volume.json', 'r') as f:
        #vollevel = json.load(f)
        #kodi.Application.SetVolume({"volume": vollevel})
        if ismpvplaying():
            if os.path.isfile("/home/pi/.mediavolume.json"):
                with open('/home/pi/.mediavolume.json', 'r') as vol:
                    oldvollevel = json.load(vol)
                print(oldvollevel)
                mpvsetvol = os.system("echo '" + json.dumps(
                    {"command": ["set_property", "volume",
                                 str(oldvollevel)]}) +
                                      "' | socat - /tmp/mpvsocket")
        self.conversation_stream.stop_playback()
        return continue_conversation
コード例 #5
0
ファイル: main.py プロジェクト: ascillato/GassistPi
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')
    parser.add_argument('--device_model_id', type=str,
                        metavar='DEVICE_MODEL_ID', required=True,
                        help='The device model ID registered with Google.')
    parser.add_argument('--project_id', type=str,
                        metavar='PROJECT_ID', required=False,
                        help='The project ID used to register device '
                        + 'instances.')
    args = parser.parse_args()
    with open(args.credentials, 'r') as f:
        credentials = google.oauth2.credentials.Credentials(token=None,
                                                            **json.load(f))
    with Assistant(credentials, args.device_model_id) as assistant:
        subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        events = assistant.start()
        print('device_model_id:', args.device_model_id + '\n' +
              'device_id:', assistant.device_id + '\n')
        if args.project_id:
            register_device(args.project_id, credentials,
                            args.device_model_id, assistant.device_id)
        for event in events:
            process_event(event, assistant.device_id)
            usrcmd=event.args
            if 'trigger'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                Action(str(usrcmd).lower())
            if 'stream'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi/src/trackchange.py')
                    os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                    os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py')
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())
                else:
                    os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                    os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py')
                    if 'autoplay'.lower() in str(usrcmd).lower():
                        YouTube_Autoplay(str(usrcmd).lower())
                    else:
                        YouTube_No_Autoplay(str(usrcmd).lower())
                
            if 'stop'.lower() in str(usrcmd).lower():
                stop()
            if 'radio'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                radio(str(usrcmd).lower())
            if 'wireless'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                ESP(str(usrcmd).lower())
            if 'parcel'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                track()
            if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                feed(str(usrcmd).lower())
            if 'on kodi'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                kodiactions(str(usrcmd).lower())
            if 'chromecast'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if 'play'.lower() in str(usrcmd).lower():
                    chromecast_play_video(str(usrcmd).lower())
                else:
                    chromecast_control(usrcmd)
            if 'pause music'.lower() in str(usrcmd).lower() or 'resume music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                if ismpvplaying():
                    if 'pause music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", True]})+"' | socat - /tmp/mpvsocket")
                    elif 'resume music'.lower() in str(usrcmd).lower():
                        playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", False]})+"' | socat - /tmp/mpvsocket")
                else:
                    say("Sorry nothing is playing right now")
            if 'music volume'.lower() in str(usrcmd).lower():
                if ismpvplaying():
                    if 'set'.lower() in str(usrcmd).lower() or 'change'.lower() in str(usrcmd).lower():
                        if 'hundred'.lower() in str(usrcmd).lower() or 'maximum' in str(usrcmd).lower():
                            settingvollevel=100
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        elif 'zero'.lower() in str(usrcmd).lower() or 'minimum' in str(usrcmd).lower():
                            settingvollevel=0
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        else:
                            for settingvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                with open('/home/pi/.mediavolume.json', 'w') as vol:
                                    json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    elif 'increase'.lower() in str(usrcmd).lower() or 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.mediavolume.json"):
                            with open('/home/pi/.mediavolume.json', 'r') as vol:
                                oldvollevel = json.load(vol)
                                for oldvollevel in re.findall(r'\b\d+\b', str(oldvollevel)):
                                    oldvollevel=int(oldvollevel)
                        else:
                            mpvgetvol=subprocess.Popen([("echo '"+json.dumps({ "command": ["get_property", "volume"]})+"' | socat - /tmp/mpvsocket")],shell=True, stdout=subprocess.PIPE)
                            output=mpvgetvol.communicate()[0]
                            for oldvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                                oldvollevel=int(oldvollevel)

                        if 'increase'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel+ changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                        if 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                            if any(char.isdigit() for char in str(usrcmd)):
                                for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                    changevollevel=int(changevollevel)
                            else:
                                changevollevel=10
                            newvollevel= oldvollevel - changevollevel
                            print(newvollevel)
                            if newvollevel>100:
                                settingvollevel==100
                            elif newvollevel<0:
                                settingvollevel==0
                            else:
                                settingvollevel=newvollevel
                            with open('/home/pi/.mediavolume.json', 'w') as vol:
                                json.dump(settingvollevel, vol)
                            mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                    else:
                        say("Sorry I could not help you")
                else:
                    say("Sorry nothing is playing right now")

            if 'refresh'.lower() in str(usrcmd).lower() and 'music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                refreshlists()
            if 'google music'.lower() in str(usrcmd).lower():
                assistant.stop_conversation()
                os.system('pkill mpv')
                if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                    os.system('rm /home/pi/GassistPi/src/trackchange.py')
                    os.system('echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                    if 'all the songs'.lower() in str(usrcmd).lower():
                        os.system('echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py')
                        say("Playing all your songs")
                        play_songs()

                    if 'playlist'.lower() in str(usrcmd).lower():
                        if 'first'.lower() in str(usrcmd).lower() or 'one'.lower() in str(usrcmd).lower()  or '1'.lower() in str(usrcmd).lower():
                            os.system('echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py')
                            say("Playing songs from your playlist")
                            play_playlist(0)
                        else:
                            say("Sorry I am unable to help")

                    if 'album'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                            os.system("rm /home/pi/.gmusicalbumplayer.json")

                        req=str(usrcmd).lower()
                        idx=(req).find('album')
                        album=req[idx:]
                        album=album.replace("'}", "",1)
                        album = album.replace('album','',1)
                        if 'from'.lower() in req:
                            album = album.replace('from','',1)
                            album = album.replace('google music','',1)
                        else:
                            album = album.replace('google music','',1)

                        album=album.strip()
                        print(album)
                        albumstr=('"'+album+'"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_album('+albumstr+')')
                        f.close()
                        say("Looking for songs from the album")
                        play_album(album)

                    if 'artist'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                            os.system("rm /home/pi/.gmusicartistplayer.json")

                        req=str(usrcmd).lower()
                        idx=(req).find('artist')
                        artist=req[idx:]
                        artist=artist.replace("'}", "",1)
                        artist = artist.replace('artist','',1)
                        if 'from'.lower() in req:
                            artist = artist.replace('from','',1)
                            artist = artist.replace('google music','',1)
                        else:
                            artist = artist.replace('google music','',1)

                        artist=artist.strip()
                        print(artist)
                        artiststr=('"'+artist+'"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_artist('+artiststr+')')
                        f.close()
                        say("Looking for songs rendered by the artist")
                        play_artist(artist)
                else:
                    os.system('echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                    if 'all the songs'.lower() in str(usrcmd).lower():
                        os.system('echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py')
                        say("Playing all your songs")
                        play_songs()

                    if 'playlist'.lower() in str(usrcmd).lower():
                        if 'first'.lower() in str(usrcmd).lower() or 'one'.lower() in str(usrcmd).lower()  or '1'.lower() in str(usrcmd).lower():
                            os.system('echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py')
                            say("Playing songs from your playlist")
                            play_playlist(0)
                        else:
                            say("Sorry I am unable to help")

                    if 'album'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                            os.system("rm /home/pi/.gmusicalbumplayer.json")

                        req=str(usrcmd).lower()
                        idx=(req).find('album')
                        album=req[idx:]
                        album=album.replace("'}", "",1)
                        album = album.replace('album','',1)
                        if 'from'.lower() in req:
                            album = album.replace('from','',1)
                            album = album.replace('google music','',1)
                        else:
                            album = album.replace('google music','',1)

                        album=album.strip()
                        print(album)
                        albumstr=('"'+album+'"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_album('+albumstr+')')
                        f.close()
                        say("Looking for songs from the album")
                        play_album(album)

                    if 'artist'.lower() in str(usrcmd).lower():
                        if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                            os.system("rm /home/pi/.gmusicartistplayer.json")

                        req=str(usrcmd).lower()
                        idx=(req).find('artist')
                        artist=req[idx:]
                        artist=artist.replace("'}", "",1)
                        artist = artist.replace('artist','',1)
                        if 'from'.lower() in req:
                            artist = artist.replace('from','',1)
                            artist = artist.replace('google music','',1)
                        else:
                            artist = artist.replace('google music','',1)

                        artist=artist.strip()
                        print(artist)
                        artiststr=('"'+artist+'"')
                        f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                        f.write('play_artist('+artiststr+')')
                        f.close()
                        say("Looking for songs rendered by the artist")
                        play_artist(artist)
コード例 #6
0
ファイル: pushbutton.py プロジェクト: ascillato/GassistPi
    def assist(self):
        """Send a voice request to the Assistant and playback the response.

        Returns: True if conversation should continue.
        """
        continue_conversation = False
        device_actions_futures = []
        subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Fb.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.conversation_stream.start_recording()
        #Uncomment the following after starting the Kodi
        #status=mutevolstatus()
        #vollevel=status[1]
        #with open('/home/pi/.volume.json', 'w') as f:
               #json.dump(vollevel, f)
        #kodi.Application.SetVolume({"volume": 0})
        GPIO.output(5,GPIO.HIGH)
        led.ChangeDutyCycle(100)
        if ismpvplaying():
            if os.path.isfile("/home/pi/.mediavolume.json"):
                mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume","10"]})+"' | socat - /tmp/mpvsocket")
            else:
                mpvgetvol=subprocess.Popen([("echo '"+json.dumps({ "command": ["get_property", "volume"]})+"' | socat - /tmp/mpvsocket")],shell=True, stdout=subprocess.PIPE)
                output=mpvgetvol.communicate()[0]
                for currntvol in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                        json.dump(currntvol, vol)
                mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume","10"]})+"' | socat - /tmp/mpvsocket")

        logging.info('Recording audio request.')

        def iter_assist_requests():
            for c in self.gen_assist_requests():
                assistant_helpers.log_assist_request_without_audio(c)
                yield c
            self.conversation_stream.start_playback()

        # This generator yields AssistResponse proto messages
        # received from the gRPC Google Assistant API.
        for resp in self.assistant.Assist(iter_assist_requests(),
                                          self.deadline):
            assistant_helpers.log_assist_response_without_audio(resp)
            if resp.event_type == END_OF_UTTERANCE:
                logging.info('End of audio request detected')
                GPIO.output(5,GPIO.LOW)
                led.ChangeDutyCycle(0)
                self.conversation_stream.stop_recording()

            if resp.speech_results:
                logging.info('Transcript of user request: "%s".',
                             ' '.join(r.transcript
                                      for r in resp.speech_results))

                for r in resp.speech_results:
                    usercommand=str(r)

                if "stability: 1.0" in usercommand.lower():
                    usrcmd=str(usercommand).lower()
                    idx=usrcmd.find('stability')
                    usrcmd=usrcmd[:idx]
                    usrcmd=usrcmd.replace("stability","",1)
                    usrcmd=usrcmd.strip()
                    usrcmd=usrcmd.replace('transcript: "','',1)
                    usrcmd=usrcmd.replace('"','',1)
                    usrcmd=usrcmd.strip()
                    print(str(usrcmd))
                    if 'trigger'.lower() in str(usrcmd).lower():
                        Action(str(usrcmd).lower())
                        return continue_conversation
                    if 'stream'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                            os.system('rm /home/pi/GassistPi/src/trackchange.py')
                            os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                            os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py')
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        else:
                            os.system('echo "from actions import youtubeplayer\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                            os.system('echo "youtubeplayer()\n" >> /home/pi/GassistPi/src/trackchange.py')
                            if 'autoplay'.lower() in str(usrcmd).lower():
                                YouTube_Autoplay(str(usrcmd).lower())
                            else:
                                YouTube_No_Autoplay(str(usrcmd).lower())
                        return continue_conversation
                    if 'stop'.lower() in str(usrcmd).lower():
                        stop()
                        return continue_conversation
                    if 'radio'.lower() in str(usrcmd).lower():
                        radio(str(usrcmd).lower())
                        return continue_conversation
                    if 'wireless'.lower() in str(usrcmd).lower():
                        ESP(str(usrcmd).lower())
                        return continue_conversation
                    if 'parcel'.lower() in str(usrcmd).lower():
                        track()
                        return continue_conversation
                    if 'news'.lower() in str(usrcmd).lower() or 'feed'.lower() in str(usrcmd).lower() or 'quote'.lower() in str(usrcmd).lower():
                        feed(str(usrcmd).lower())
                        return continue_conversation
                    if 'on kodi'.lower() in str(usrcmd).lower():
                        kodiactions(str(usrcmd).lower())
                        return continue_conversation
                    if 'chromecast'.lower() in str(usrcmd).lower():
                        if 'play'.lower() in str(usrcmd).lower():
                            chromecast_play_video(str(usrcmd).lower())
                        else:
                            chromecast_control(usrcmd)
                        return continue_conversation
                    if 'pause music'.lower() in str(usrcmd).lower() or 'resume music'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'pause music'.lower() in str(usrcmd).lower():
                                playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", True]})+"' | socat - /tmp/mpvsocket")
                            elif 'resume music'.lower() in str(usrcmd).lower():
                                playstatus=os.system("echo '"+json.dumps({ "command": ["set_property", "pause", False]})+"' | socat - /tmp/mpvsocket")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation
                    if 'music volume'.lower() in str(usrcmd).lower():
                        if ismpvplaying():
                            if 'set'.lower() in str(usrcmd).lower() or 'change'.lower() in str(usrcmd).lower():
                                if 'hundred'.lower() in str(usrcmd).lower() or 'maximum' in str(usrcmd).lower():
                                    settingvollevel=100
                                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                                elif 'zero'.lower() in str(usrcmd).lower() or 'minimum' in str(usrcmd).lower():
                                    settingvollevel=0
                                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                                else:
                                    for settingvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(usrcmd)):
                                        with open('/home/pi/.mediavolume.json', 'w') as vol:
                                            json.dump(settingvollevel, vol)
                                    mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                            elif 'increase'.lower() in str(usrcmd).lower() or 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                                if os.path.isfile("/home/pi/.mediavolume.json"):
                                    with open('/home/pi/.mediavolume.json', 'r') as vol:
                                        oldvollevel = json.load(vol)
                                        for oldvollevel in re.findall(r'\b\d+\b', str(oldvollevel)):
                                            oldvollevel=int(oldvollevel)
                                else:
                                    mpvgetvol=subprocess.Popen([("echo '"+json.dumps({ "command": ["get_property", "volume"]})+"' | socat - /tmp/mpvsocket")],shell=True, stdout=subprocess.PIPE)
                                    output=mpvgetvol.communicate()[0]
                                    for oldvollevel in re.findall(r"[-+]?\d*\.\d+|\d+", str(output)):
                                        oldvollevel=int(oldvollevel)

                                if 'increase'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit() for char in str(usrcmd)):
                                        for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                            changevollevel=int(changevollevel)
                                    else:
                                        changevollevel=10
                                    newvollevel= oldvollevel+ changevollevel
                                    print(newvollevel)
                                    if newvollevel>100:
                                        settingvollevel==100
                                    elif newvollevel<0:
                                        settingvollevel==0
                                    else:
                                        settingvollevel=newvollevel
                                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                                if 'decrease'.lower() in str(usrcmd).lower() or 'reduce'.lower() in str(usrcmd).lower():
                                    if any(char.isdigit() for char in str(usrcmd)):
                                        for changevollevel in re.findall(r'\b\d+\b', str(usrcmd)):
                                            changevollevel=int(changevollevel)
                                    else:
                                        changevollevel=10
                                    newvollevel= oldvollevel - changevollevel
                                    print(newvollevel)
                                    if newvollevel>100:
                                        settingvollevel==100
                                    elif newvollevel<0:
                                        settingvollevel==0
                                    else:
                                        settingvollevel=newvollevel
                                    with open('/home/pi/.mediavolume.json', 'w') as vol:
                                        json.dump(settingvollevel, vol)
                                    mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(settingvollevel)]})+"' | socat - /tmp/mpvsocket")
                            else:
                                say("Sorry I could not help you")
                        else:
                            say("Sorry nothing is playing right now")
                        return continue_conversation

                    if 'refresh'.lower() in str(usrcmd).lower() and 'music'.lower() in str(usrcmd).lower():
                        refreshlists()
                        return continue_conversation
                    if 'google music'.lower() in str(usrcmd).lower():
                        os.system('pkill mpv')
                        if os.path.isfile("/home/pi/GassistPi/src/trackchange.py"):
                            os.system('rm /home/pi/GassistPi/src/trackchange.py')
                            os.system('echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                            if 'all the songs'.lower() in str(usrcmd).lower():
                                os.system('echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py')
                                say("Playing all your songs")
                                play_songs()

                            if 'playlist'.lower() in str(usrcmd).lower():
                                if 'first'.lower() in str(usrcmd).lower() or 'one'.lower() in str(usrcmd).lower()  or '1'.lower() in str(usrcmd).lower():
                                    os.system('echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py')
                                    say("Playing songs from your playlist")
                                    play_playlist(0)
                                else:
                                    say("Sorry I am unable to help")

                            if 'album'.lower() in str(usrcmd).lower():
                                if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                                    os.system("rm /home/pi/.gmusicalbumplayer.json")

                                req=str(usrcmd).lower()
                                idx=(req).find('album')
                                album=req[idx:]
                                album=album.replace("'}", "",1)
                                album = album.replace('album','',1)
                                if 'from'.lower() in req:
                                    album = album.replace('from','',1)
                                    album = album.replace('google music','',1)
                                else:
                                    album = album.replace('google music','',1)

                                album=album.strip()
                                print(album)
                                albumstr=('"'+album+'"')
                                f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                                f.write('play_album('+albumstr+')')
                                f.close()
                                say("Looking for songs from the album")
                                play_album(album)

                            if 'artist'.lower() in str(usrcmd).lower():
                                if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                                    os.system("rm /home/pi/.gmusicartistplayer.json")

                                req=str(usrcmd).lower()
                                idx=(req).find('artist')
                                artist=req[idx:]
                                artist=artist.replace("'}", "",1)
                                artist = artist.replace('artist','',1)
                                if 'from'.lower() in req:
                                    artist = artist.replace('from','',1)
                                    artist = artist.replace('google music','',1)
                                else:
                                    artist = artist.replace('google music','',1)

                                artist=artist.strip()
                                print(artist)
                                artiststr=('"'+artist+'"')
                                f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                                f.write('play_artist('+artiststr+')')
                                f.close()
                                say("Looking for songs rendered by the artist")
                                play_artist(artist)
                        else:
                            os.system('echo "from actions import play_playlist\nfrom actions import play_songs\nfrom actions import play_album\nfrom actions import play_artist\n\n" >> /home/pi/GassistPi/src/trackchange.py')
                            if 'all the songs'.lower() in str(usrcmd).lower():
                                os.system('echo "play_songs()\n" >> /home/pi/GassistPi/src/trackchange.py')
                                say("Playing all your songs")
                                play_songs()

                            if 'playlist'.lower() in str(usrcmd).lower():
                                if 'first'.lower() in str(usrcmd).lower() or 'one'.lower() in str(usrcmd).lower()  or '1'.lower() in str(usrcmd).lower():
                                    os.system('echo "play_playlist(0)\n" >> /home/pi/GassistPi/src/trackchange.py')
                                    say("Playing songs from your playlist")
                                    play_playlist(0)
                                else:
                                    say("Sorry I am unable to help")

                            if 'album'.lower() in str(usrcmd).lower():
                                if os.path.isfile("/home/pi/.gmusicalbumplayer.json"):
                                    os.system("rm /home/pi/.gmusicalbumplayer.json")

                                req=str(usrcmd).lower()
                                idx=(req).find('album')
                                album=req[idx:]
                                album=album.replace("'}", "",1)
                                album = album.replace('album','',1)
                                if 'from'.lower() in req:
                                    album = album.replace('from','',1)
                                    album = album.replace('google music','',1)
                                else:
                                    album = album.replace('google music','',1)

                                album=album.strip()
                                print(album)
                                albumstr=('"'+album+'"')
                                f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                                f.write('play_album('+albumstr+')')
                                f.close()
                                say("Looking for songs from the album")
                                play_album(album)

                            if 'artist'.lower() in str(usrcmd).lower():
                                if os.path.isfile("/home/pi/.gmusicartistplayer.json"):
                                    os.system("rm /home/pi/.gmusicartistplayer.json")

                                req=str(usrcmd).lower()
                                idx=(req).find('artist')
                                artist=req[idx:]
                                artist=artist.replace("'}", "",1)
                                artist = artist.replace('artist','',1)
                                if 'from'.lower() in req:
                                    artist = artist.replace('from','',1)
                                    artist = artist.replace('google music','',1)
                                else:
                                    artist = artist.replace('google music','',1)

                                artist=artist.strip()
                                print(artist)
                                artiststr=('"'+artist+'"')
                                f = open('/home/pi/GassistPi/src/trackchange.py', 'a+')
                                f.write('play_artist('+artiststr+')')
                                f.close()
                                say("Looking for songs rendered by the artist")
                                play_artist(artist)
                        return continue_conversation

                else:
                    continue
                GPIO.output(5,GPIO.LOW)
                GPIO.output(6,GPIO.HIGH)
                led.ChangeDutyCycle(50)
                logging.info('Playing assistant response.')
            if len(resp.audio_out.audio_data) > 0:
                self.conversation_stream.write(resp.audio_out.audio_data)
            if resp.dialog_state_out.conversation_state:
                conversation_state = resp.dialog_state_out.conversation_state
                logging.debug('Updating conversation state.')
                self.conversation_state = conversation_state
            if resp.dialog_state_out.volume_percentage != 0:
                volume_percentage = resp.dialog_state_out.volume_percentage
                logging.info('Setting volume to %s%%', volume_percentage)
                self.conversation_stream.volume_percentage = volume_percentage
            if resp.dialog_state_out.microphone_mode == DIALOG_FOLLOW_ON:
                continue_conversation = True
                GPIO.output(6,GPIO.LOW)
                GPIO.output(5,GPIO.HIGH)
                led.ChangeDutyCycle(100)
                logging.info('Expecting follow-on query from user.')
            elif resp.dialog_state_out.microphone_mode == CLOSE_MICROPHONE:
                continue_conversation = False
            if resp.device_action.device_request_json:
                device_request = json.loads(
                    resp.device_action.device_request_json
                )
                fs = self.device_handler(device_request)
                if fs:
                    device_actions_futures.extend(fs)

        if len(device_actions_futures):
            logging.info('Waiting for device executions to complete.')
            concurrent.futures.wait(device_actions_futures)

        logging.info('Finished playing assistant response.')
        GPIO.output(6,GPIO.LOW)
        GPIO.output(5,GPIO.LOW)
        led.ChangeDutyCycle(0)
        #Uncomment the following, after starting Kodi
        #with open('/home/pi/.volume.json', 'r') as f:
               #vollevel = json.load(f)
               #kodi.Application.SetVolume({"volume": vollevel})
        if ismpvplaying():
            if os.path.isfile("/home/pi/.mediavolume.json"):
                with open('/home/pi/.mediavolume.json', 'r') as vol:
                    oldvollevel = json.load(vol)
                print(oldvollevel)
                mpvsetvol=os.system("echo '"+json.dumps({ "command": ["set_property", "volume",str(oldvollevel)]})+"' | socat - /tmp/mpvsocket")
        self.conversation_stream.stop_playback()
        return continue_conversation