Listens on one or several mics, transcribes spoken English commands with a speech-to-text server and runs them on Home Assistant through its REST API. Read this to install, configure, run or test it; to change the code, AGENTS.md. The longer README it was cut from, with the feature list and step-by-step walk-throughs: history/2026-12/2026-12-01-0815-readme-doc-as-it-stood-19-kb.md
- Linux, Python 3.8+; ALSA or PulseAudio for a local mic, or
ffmpegfor an RTSP camera's audio track - A speech-to-text server implementing the Transcription API, developed against NVIDIA Parakeet TDT 0.6B v2 (English)
- Home Assistant and a long-lived access token (bottom of http://homeassistant.local:8123/profile/security)
- Optional: a Piper TTS server and an OpenAI API key for the AI assistant, a speaker for the confirmation sounds
requirements.txt: numpy, requests and openai, which is imported at startup but called only by the AI assistant
git clone https://github.com/stepankandrushin/homeassistant-voice.git
cd homeassistant-voice
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp config.py.sample config.py # then set the server URLs, the HA token, the mics and the aliases
All settings are in config.py, one per host and not tracked; config.py.sample lists them with comments.
TRANSCRIPTION_API_URL = "http://localhost:8889/transcribe". The server must provide:
POST /transcribe: a multipart form with one WAV file in theaudiofield; returns JSON{"text": "..."}POST /transcribe_batch, window mode only: several WAV files, each in its ownaudiofield; returns{"texts": ["...", ...]}, one text per file in the order sent. Its URL isTRANSCRIPTION_API_URL + "_batch"unlessTRANSCRIPTION_BATCH_API_URLis set.
The clips are mono 16-bit WAV; a VAD clip is labelled 16 kHz whatever SAMPLE_RATE says, so keep the sources at
16000. Texts should come without punctuation, which aliases don't expect: the code only lowercases them.
A source is any command writing raw s16le at SAMPLE_RATE to stdout, restarted 2 s after its process exits or
killed and restarted after STALE_CHUNK_TIMEOUT_SEC (30) without audio. AUDIO_RECORD_CMD is one source, named
mic; AUDIO_RECORD_CMDS runs several, as a dict whose keys name the mics in the logs and per-mic settings, or as
a list of mic1, mic2, ...
AUDIO_RECORD_CMDS = {
"kitchen": ["arecord", "-D", "dsnoop:CARD=MS,DEV=0", "-r", "16000", "-c", "1", "-f", "S16_LE", "-t", "raw"],
"garden": ["ffmpeg", "-loglevel", "quiet", "-rtsp_transport", "tcp",
"-i", "rtsp://user:pass@garden-camera.local:554/Streaming/Channels/102",
"-vn", "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1", "-f", "s16le", "-"],
}
source_rooms = {"kitchen": "kitchen", "garden": "garden"} # room of a command that names none; else default_room
source_db_thresholds = {"garden": 62} # VAD mode: this mic's DB_THRESHOLD
DEDUPE_WINDOW_SEC = 2.0 # two mics hearing one phrase: the same entity + action runs once within this
HOMEASSISTANT_URL = "http://homeassistant.local:8123" # the IP where mDNS doesn't resolve the name
HOMEASSISTANT_TOKEN = "YOUR_LONG_LIVED_ACCESS_TOKEN"
DB_THRESHOLD = 50 # VAD mode: speech level in dB, a few dB above the mic's idle noise floor
SILENCE_THRESHOLD_MS = 500 # silence that ends an utterance
MIN_RECORDING_LENGTH_SEC = 1.0 # shorter utterances are dropped; window mode waits for this much audio
PREROLL_DURATION_SEC = 0.5 # audio kept from before speech was detected
SAVE_RECORDINGS_TO_DISK = False # True: also saved as RECORDINGS_DIR/YYYY/MM/DD/<mic>_YYYYMMDD_HHMMSS.wav
RECORDINGS_DIR = "recordings"
TRANSCRIPTS_DIR = "transcripts" # every transcript is appended to TRANSCRIPTS_DIR/<mic>.logHOMEASSISTANT_SOUND ("" for none) is played when a command runs and AI_SOUND when the AI assistant is called,
both by AUDIO_PLAY_CMD; TTS_API_URL is a Piper TTS HTTP server whose audio VOICE_PLAY_CMD plays (22050 Hz).
In VAD mode an utterance that is no Home Assistant command and starts with a wake word from ai_assistant_names
("smarty, what's the capital of France") goes to OpenAI GPT-4o (OPENAI_API_KEY), and the answer is spoken.
STT_MODE = "vad", the default, cuts an utterance out where the level crosses DB_THRESHOLD. Where a mic's noise
floor sits close to speech level (a fan, a far camera), quiet syllables fall under any threshold and phrases get
chopped (turn on | the light). STT_MODE = "window" drops the threshold: every WINDOW_HOP_SEC (0.5) the last
WINDOW_SEC (5.0, must fit the longest command) of every mic goes to /transcribe_batch in one batch, so a command
lands whole in several windows. utils/window.py runs each utterance once, by these rules (tests/test_window.py):
- One window that parses to a command is enough; one that names its room runs at once. A room-less one waits
WINDOW_HOLD_HOPSrounds (1; 0 runs it at once) for the next window to add "in the garden": a newer command replaces it, a window that parses to nothing never cancels it, text still growing ("... in the gar") waits a round. - A room-less reading ending in "in", "at" or "the" was cut before its room: no command, and it doesn't fire a held one. "on" doesn't count: "turn the light on" is complete.
- Among mics ready in one round, a reading that names its room beats one that fell back to its mic's room: the noisier of two mics may hear "in the gordon" for "in the garden".
- Once a command fires, every mic's buffered audio is discarded, so no mic acts on the same words again.
- The same entity + action is deduped across mics for
max(DEDUPE_WINDOW_SEC, WINDOW_SEC)(a lagging stream).
Window mode runs Home Assistant commands only, since the AI assistant needs whole utterances; a mic's window text is logged only when it changes.
A command is [action] [device] in [room] ("turn off the AC in the bedroom", "turn the TV on"). An alias is a
substring of the lowercase transcript or a compiled regex searched in it, for what a substring can't say: a particle
verb split around its object, or a short word that must not match inside another ("ac" in "back"). In each dict the
first matching entry wins: list a bare-room pseudo-device like "pool" after the real devices.
action_aliases = { # the words between turn/switch and on/off may not be on/off: "turn off the light on the terrace"
"turn_on": ["turn on", "switch on", re.compile(r"\b(?:turn|switch) (?:(?!on\b|off\b)\w+ ){1,5}on\b")],
"turn_off": ["turn off", "switch off", re.compile(r"\b(?:turn|switch) (?:(?!on\b|off\b)\w+ ){1,5}off\b")],
}
device_aliases = {"ac": [re.compile(r"\ba ?c\b"), "air conditioner"], "light": ["light", "lamp"]}
room_aliases = {"office": ["office", "study"], "garden": ["garden", "outside"]}
room_entities = {
"office": {"ac": "climate.office_ac", "light": "light.office_main"},
"garden": {"light": ["switch.garden_switch", "switch.garden_switch_2"]}, # two relays, one HA call
}A device maps to one entity ID; to a list of IDs sharing a domain, switched in one HA call; or to a dict
{action: entity(s)} when one action should hit another set (a light whose turn_off also stops a pump), with a
"default" key for the actions not listed. A command naming no room goes to its mic's room (source_rooms, else
default_room); a device in devices_without_room goes to the first room in room_entities that has it. An
action_aliases key is the Home Assistant service called, so a toggle entry works too.
"Turn on the light everywhere" needs no code: a virtual room in room_aliases and room_entities whose device
entry lists every entity to hit, all of one domain, kept in step with the real rooms. A button.* or
input_button.* entity is pressed whatever the action (press is a button's only service), so a phrase can press
a Home Assistant button whose script holds the list:
room_aliases["everywhere"] = ["everywhere", "all lights", "all the lights"]
room_entities["everywhere"] = {"light": {
"turn_on": ["light.office_main", "switch.garden_switch", "switch.garden_switch_2"],
"turn_off": "button.all_lights_off",
}}python main.py runs it in the foreground. As a service: homeassistant-voice.service assumes user pi and the
checkout in /home/pi/homeassistant-voice; edit it, then:
sudo cp homeassistant-voice.service /etc/systemd/system/
sudo systemctl enable --now homeassistant-voice.service
sudo journalctl -u homeassistant-voice.service -f
On SIGTERM (systemctl stop or restart) it stops the capture processes and any TTS playing, clears the TTS
queue and exits, leaving no audio process behind.
99-usb-jabra.rules restarts the service and reports over Telegram when a USB speakerphone (a Jabra Speak2 40)
that dropped off the bus comes back. Copy report.sh.sample to an executable report.sh with the bot token and
chat ID, and put the device's idVendor and idProduct (lsusb) and that path in the rules file. The restart
runs only after report.sh succeeds (&&): a missing script or a curl with no network skips it.
sudo cp 99-usb-jabra.rules /etc/udev/rules.d/ && sudo udevadm control --reload-rules && sudo udevadm trigger
python run_tests.py runs the command-matching and window-mode tests, which need no config.py, server or audio
device; tests/test_ai_integration.py is always skipped, as it imports send_to_openai, which utils/ai.py no
longer has. Against the real config.py:
python tests/test_shutdown.pystartsmain.py, sends it SIGTERM and checks that it exits cleanlytests/test_tts.py,test_tts_debug.pyandtest_tts_direct.pyspeak through the TTS server and the speakers (tests/TTS_TEST_README.md)python transcribe.py recordings/2025/02/27/mic_20250227_101030.wavsends one WAV to the transcription server
ha.py switches an entity through the REST API with the URL and token in config.py, e.g. to find which relay
is which; the domain is the ID's part before the dot.
./ha.py switch.garden_switch # toggle
./ha.py switch.garden_switch on # on|1|true, off|0|false
MIT, see LICENSE.