My script for managing intents locally

For those who are interested and if it can save time I offer you my skill to manage certain intents locally such as:
ask for the time, adjust the volume of the rhasspy server, start / stop a web radio etc all these tasks which can be handled very quickly directly on the rhasspy server

I put the skill.py script in /home/pi/.config/rhasspy/profiles/fr/scripts
we launch the skill at the same time as rhasspy

#!/usr/bin/env python3
import sys
import random
import datetime
from subprocess import call
import vlc
import time
import paho.mqtt.client as mqtt
instance = vlc.Instance()  # ('--verbose 9')
player = instance.media_player_new()
def on_connect(client, userdata, flags, rc):
    """Called when connected to MQTT broker."""
    client.subscribe("hermes/intent/#")
    client.subscribe("hermes/nlu/intentNotRecognized")
    print("Connected. Waiting for intents.")
def on_disconnect(client, userdata, flags, rc):
    """Called when disconnected from MQTT broker."""
    client.reconnect()
def on_message(client, userdata, msg):
    """Called each time a message is received on a subscribed topic."""
       if msg.topic == "hermes/nlu/intentNotRecognized":
        Say = "unrecognized command"
    else:
        Intent = json.loads(msg.payload)
        Say = Intent["input"]
        Intent_Name = Intent["intent"]["intentName"]
        print("Got intent:", Intent_Name )
    if Intent_Name == "RadioOn" :
        slots = Intent["slots"]
        radio = slots[0]["value"]["value"]
        if radio=="Nostalgie":
            Media = instance.media_new('https://icecast.radiofrance.fr/fbnord-midfi.mp3?ID=76zqey582k')
            Media.get_mrl()
            player.set_media(Media)
            player.play()
        elif Intent_Name == "VLC" :
        slots = Intent["slots"]
        Cmde  = slots[0]["value"]["value"]
        if Cmde == "stop" :
            player.stop()
        elif Cmde== "Play" :
            player.play()
    elif Intent_Name == "GetTime" :
        now = datetime.datetime.now()
        heur = now.strftime('%H')   
        minut = now.strftime('%M')  
        if heur[0:1] == "0" : heur = heur[1:2]
        if heur == "1" : heur = "une"
        Say = "It's" + heur + " heure " + minut + " minutes"
    elif Intent_Name == "setVolume"  :
        slots = Intent["slots"]
        if len(slots) == 1 :  
            arg1 = slots[0]["value"]["value"]
            volume = str(int(arg1)*0.63)  
            # -c=N° Card  liste des controles-> amixer
            call(["/usr/bin/amixer","-q","-c2", "set" ,'Speaker', volume ])
            call(["/usr/bin/amixer","-q","-c2", "set" ,'Headphone', volume ])
            call(["/usr/bin/amixer","-q","-c2", "set" ,'digital volume', volume ])
            Say = "volume reglé sur" + str(arg1)
        # Speak the text from the intent      
    if Say != "" :
        site_id = "Master" #nlu_payload["siteId"]
        client.publish( "hermes/tts/say", json.dumps({'text': Say ,'siteId': site_id  }) )
# Create MQTT client and connect to broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.connect("localhost", 1883)
client.loop_forever()

some intents in the sentences.ini

[GetTime]
what time is it
[setVolume]
volume (0…100) {volume}
[RadioOn]
listen (Nostalgie | NRJ) {radio}
[VLC]
(stop the music): stop {command}
(resume music): play {command}

Here you just have to modify according to your needs
cordially
Arpagor

2 Likes

Can you explain what I name the python file?

the name of the python script does not matter, we name it what we want
the important points are the lines:
call (["/ usr / bin / amixer", “- q”, “- c2”, “set”, ‘Speaker’, volume])
which depend on your sound card!
and you have to run the script in parallel with rhasspy (I created a service)

Could you please explain, how you created that service for those of us, who do not have experience with this?

Start a python script as a service

create a service file such as:
nano /etc/systemd/system/script_name.service

[Unit]
Description=Description of script
[Service]
Type=simple
ExecStart=/home/pi/autostart/name_of_script.py
[Install]
WantedBy=multi-user.target

Make the launch permanent:
sudo systemctl enable name_of_script.service
start the service:
sudo systemctl start name_of_script.service
For check if everything is OK:
sudo systemctl status name_of_script.service

2 Likes

Very nice description. Thank you very much! :+1: