diff --git a/CONTEXT.md b/CONTEXT.md index 73a59b8..1228892 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -11,7 +11,8 @@ Assistant vocal **100 % local** : ESP32 (micro INMP441) → MQTT → serveur Python (VAD, faster-whisper, diarisation, Piper) → MQTT → ESP32 (ampli MAX98357A). -Prompt de référence : `prompt-assistant-vocal-esp32.md` (rôle, style, feuille de route, conventions). +Prompt de référence : `prompt-assistant-vocal-esp32.md` (rôle, style, feuille de route, conventions) ; **supprimé du dépôt par +l'utilisateur le 2026-10-19**, il reste dans l'historique : `git show d20976f:prompt-assistant-vocal-esp32.md`. --- @@ -51,7 +52,8 @@ capteur R503 + bouton conservé) — mêmes règles de validation : | F4 | Serveur : droits par doigt, confirmation par le même doigt, pipeline sans VAD / diarisation / voix | **fait** | **oui (2026-10-18)** | | F4b | Suppression du code devenu inutile (VAD, diarisation, voix, mot de réveil, mains libres, firmware d'écoute continue, outils, extras) | **fait** | **oui (2026-10-18)** | | F5 | ESP32-S3 Mini (deuxième environnement PlatformIO) | **fait** (`dd268d2`) | **oui (2026-10-19)** | -| F6 | Configuration en plusieurs fichiers : `include` (motifs admis), `server/conf/` | **fait** | **oui (2026-10-19)** | +| F6 | Configuration en plusieurs fichiers : `include` (motifs admis), `server/conf/` | **fait** (`0d00b50`) | **oui (2026-10-19)** | +| F7 | Le serveur démarre avec la machine : service systemd (`make server-install`) | **fait** | **oui (2026-10-19)** | **Exigence ajoutée par l'utilisateur (2026-09-30)** : l'assistant doit aussi pouvoir **commander des machines Linux du réseau**. Absente de la feuille de route du prompt. Proposition en discussion : @@ -203,6 +205,8 @@ tools/wav_to_mqtt.py WAV ou son pur -> carte, avec bilan server/voice_server/settings.py config.yaml (+ include, F6) + .env [étape 4, F6] server/conf/home.yaml, machines.yaml, access.yaml sections home / machines / access + fingerprint [F6] server/tests/conftest.py, test_config_include.py copie de la config, 28 tests de l'inclusion [F6] +server/voice-server.service modèle d'unité systemd (@USER@, @SERVER_DIR@) [F7] +server/tests/test_service_unit.py rendu de l'unité, systemd-analyze, garde de « make run » [F7] server/voice_server/mqtt_link.py paho-mqtt 2.x, abonnement voice/+/... [étape 4] server/voice_server/audio_buffer.py PCM borné, niveaux, écriture WAV [étape 4] server/voice_server/session_manager.py sessions, pertes, délais, WAV [étape 4] @@ -265,7 +269,7 @@ TLS (option de l'étape 15, non activée). ### État au 2026-10-19 (branche `fingerprint`) -- Branche `fingerprint` : **F1 à F4b, F5 et F6 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), +- Branche `fingerprint` : **F1 à F4b, F5, F6 et F7 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), `254fc09` (F4b), `dd268d2` (F5). F5 validée par l'utilisateur le 2026-10-19 après essai sur la carte, y compris « autre doigt = 3 éclairs rouges ». - F6 (configuration en plusieurs fichiers) **validée par l'utilisateur le 2026-10-19** ; `make test` : 300 tests, pyright 0 erreur ; @@ -1129,3 +1133,22 @@ profils vocaux, enregistrements (wav/mp3), modèles, journaux et environnements avec la phrase dite ; mesuré sur 100 synthèses : jamais sous 0,65 ; texte vide 0, sous-titre inventé ≤ 0,27, autre phrase 0,44 : refusés. 12 lancements de suite sans échec. `test_round_trip` (« appelles ») est stable : 40 sur 40. Pas de changement de code de production. +- **2026-10-19** — **F7 écrite** (demande : « démarrer le serveur avec systemd »). `server/voice-server.service` (modèle) ; + `Makefile` : `server-install` (sudo, refuse si un serveur tourne), `server-uninstall`, `server-status`, `server-log` (sudo : le + compte n'est pas dans `adm`/`systemd-journal`), `server-unit` (affiche l'unité), `server-guard` (refuse `make run`/`run-echo` + si le service est actif : deux serveurs de même `client_id` se chassent du broker). `__main__.py` : `EXIT_SETUP = 78` pour les + erreurs de configuration, de dépendances ou de modèles ; l'unité a `Restart=on-failure` et `RestartPreventExitStatus=78` (un + plantage est relancé après 5 s, une configuration à corriger ne boucle pas). Le serveur démarre sans broker (paho + `connect_async` + reconnexion) et gère SIGTERM. Vérifié sans sudo : `systemd-analyze verify` (aucun avertissement), l'environnement + du service sous `systemd-run --user` avec les mêmes protections (cwd, `.env` lu, imports, `recordings/` et `logs/` inscriptibles, + modèles présents), la garde (`make server-install` refuse tant que `make run` tourne). 6 tests (`test_service_unit.py`). + **Non installé** : `sudo` demande un mot de passe, l'installation est à faire par l'utilisateur. +- **2026-10-19** — Constat pendant F7 : à 12:45 `server/config.yaml` est revenu à la version du dépôt (`mqtt.host: 10.42.0.1`) alors qu'il + portait `192.168.1.4` (modification locale de l'utilisateur) ; pas de trace dans git (ni stash, ni reflog), probablement un + « annuler les modifications » de l'IDE. Le serveur lancé à la main (PID 113256, 11:12) a encore 192.168.1.4 en mémoire ; la carte vise + 192.168.1.4 (NVS). Rien n'a été remis sans l'accord de l'utilisateur. +- **2026-10-19** — **F7 validée** par l'utilisateur (« Je valide F7. on laisse mqtt.host »). Le service est **installé par l'utilisateur** : + `voice-server` actif et activé au boot, démarré à 15:14:42, 0 redémarrage (relevé par `systemctl show`). `mqtt.host` : la copie de + travail de `server/config.yaml` porte de nouveau `192.168.1.4` (modification locale, non commitée) ; le dépôt garde `10.42.0.1`. + `prompt-assistant-vocal-esp32.md` (fichier suivi par git) a été **supprimé volontairement par l'utilisateur** ; sa suppression + n'est pas dans le commit de F7 (reste dans l'historique : `git show d20976f:prompt-assistant-vocal-esp32.md`). diff --git a/Makefile b/Makefile index 48b59cd..6f41db3 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,11 @@ PIP := $(VENV)/bin/pip PIO_VENV := .pio-venv PIO := $(PIO_VENV)/bin/pio FW_DIR := firmware +# Service systemd du serveur (étape F7) : compte qui le fait tourner, dossier server/ de ce dépôt. +SERVICE := voice-server +SERVICE_USER ?= $(shell id -un) +SERVER_DIR = $(realpath server) +RENDER_UNIT = sed -e 's|@USER@|$(SERVICE_USER)|' -e 's|@SERVER_DIR@|$(SERVER_DIR)|' server/voice-server.service # Carte du firmware : esp32dev (ESP32 WROOM, défaut) ou esp32s3mini (ESP32-S3 Mini, port /dev/ttyACM0). FW_ENV ?= esp32dev SERIAL_PORT ?= /dev/ttyUSB0 @@ -42,7 +47,7 @@ MQTT_AS = @echo "(compte MQTT : $(if $(MQTT_USERNAME),$(MQTT_USERNAME) de s .DEFAULT_GOAL := help .PHONY: help install-system mosquitto-config mosquitto-docker mqtt-user agent-run agent-install agent-log mqtt-agents mqtt-watch mqtt-transcript mqtt-home mqtt-control venv install install-dev install-speech models \ - say latency finger-list finger-enroll finger-delete speech-check transcribe run test lint record play inspect play-esp tone-esp play-mqtt tone-mqtt run-echo pio-venv fw-build fw-check fw-upload \ + say latency finger-list finger-enroll finger-delete speech-check transcribe run server-guard server-unit server-install server-uninstall server-status server-log test lint record play inspect play-esp tone-esp play-mqtt tone-mqtt run-echo pio-venv fw-build fw-check fw-upload \ fw-monitor clean ## ------------------------------------------------------------------ aide @@ -177,12 +182,40 @@ transcribe: ## Transcription et réponse du WAV OUT, sans ESP32 (étape 6) ## ----------------------------------------------------------------- serveur -run: ## Lance l'assistant vocal : répond à chaque session (étape 6, Ctrl-C pour arrêter) +# Deux serveurs de même identifiant MQTT se chassent du broker en boucle : on refuse de lancer le second. +server-guard: + @if systemctl is-active --quiet $(SERVICE) 2>/dev/null; then \ + echo "Le service $(SERVICE) tourne deja : sudo systemctl stop $(SERVICE) avant de lancer le serveur a la main."; exit 1; fi + +run: server-guard ## Lance l'assistant vocal : répond à chaque session (étape 6, Ctrl-C pour arrêter) cd server && .venv/bin/python -m voice_server --config config.yaml -run-echo: ## Serveur en mode echo : chaque session est rejouee par l'ESP32 (etape 5) +run-echo: server-guard ## Serveur en mode echo : chaque session est rejouee par l'ESP32 (etape 5) cd server && .venv/bin/python -m voice_server --config config.yaml --echo +server-unit: ## Affiche l'unité systemd du serveur telle qu'elle sera installée (rien n'est installé) + @$(RENDER_UNIT) + +server-install: ## Installe le serveur comme service (sudo) : démarre au boot, relancé après un plantage (étape F7) + @if pgrep -f '[v]oice_server --config' >/dev/null; then \ + echo "Un serveur tourne deja (make run ?) : arretez-le (Ctrl-C) avant, sinon les deux se chassent du broker."; exit 1; fi + @test -x $(SERVER_DIR)/.venv/bin/python || { echo "server/.venv absent : make install"; exit 1; } + $(RENDER_UNIT) | sudo tee /etc/systemd/system/$(SERVICE).service >/dev/null + sudo systemctl daemon-reload + sudo systemctl enable --now $(SERVICE) + @sleep 2; sudo systemctl --no-pager status $(SERVICE) | head -n 8 + +server-uninstall: ## Retire le service (le dépôt, la configuration et les enregistrements restent) + -sudo systemctl disable --now $(SERVICE) + sudo rm -f /etc/systemd/system/$(SERVICE).service + sudo systemctl daemon-reload + +server-status: ## État du service du serveur + @systemctl --no-pager status $(SERVICE) | head -n 12 + +server-log: ## Journal du service du serveur (Ctrl-C pour quitter) + sudo journalctl -u $(SERVICE) -f + test: ## Exécute les tests Python $(VENV)/bin/pytest server/tests -v diff --git a/README-EN.md b/README-EN.md index bb8ce44..1e1908c 100644 --- a/README-EN.md +++ b/README-EN.md @@ -305,7 +305,41 @@ make lint # pyright type check The exact state of the project, step by step, lives in **[CONTEXT.md](CONTEXT.md)**. Current step: **done — steps 1 to 16 are validated** (`main` branch). -`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini) and F6 (configuration in several files) validated. +`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini), F6 (configuration in several files) and F7 (server under systemd) validated. + +### `fingerprint` branch — step F7: the server starts with the machine (systemd) + +The server becomes a service: it starts at boot (no login needed), is restarted if it crashes, and its log goes to +`journalctl`. Same pattern as the agent (`make agent-install`): a template unit in the repository, installed with `sudo`. + +```bash +make server-install # installs and starts the service (sudo); refuses while a "make run" is still running +make server-status # service state +make server-log # live log (Ctrl-C to quit) +sudo systemctl restart voice-server # after changing config.yaml, conf/*.yaml, .env or the code +make server-unit # prints the unit that would be installed, installs nothing +make server-uninstall # removes the service (the repository and the recordings stay) +``` + +| Point | Detail | +|---|---| +| account and folder | the account of whoever runs `make server-install`, in this repository's `server/`: `config.yaml`, `conf/`, `.env`, `models/`, `recordings/` and `logs/` are the same as with `make run`; moving the repository means running `make server-install` again | +| start | at boot, once the network is online; if the broker is absent the server starts and reconnects on its own (1 to 10 s between tries); loading Whisper and Piper takes a few seconds | +| crash | restarted after 5 s | +| configuration or models to fix | **not restarted** (exit code 78): the state is `failed` and `make server-log` says what to fix | +| stop | `sudo systemctl stop voice-server`: clean disconnection from the broker | +| `make run` | refused while the service runs: two servers with the same MQTT identifier kick each other out of the broker in a loop | +| secrets | `.env` stays in `server/`, read by the server; nothing is copied into the unit or the log | + +The service reads `server/config.yaml` **as it is at start-up**: check `mqtt.host` before installing (the repository's value is +`10.42.0.1`, the Raspberry Pi). + +1. Stop the server started by hand (Ctrl-C in the `make run` terminal), then `make server-install`: `active (running)`. +2. `make server-log`: `doigts : Denis (empreinte 1)`, then the broker connection; a session by finger gets its answer. +3. Simulated crash: `sudo systemctl kill -s SIGKILL voice-server`; the log shows the restart after 5 s. +4. Reboot the machine without logging in: `make server-status` says `active (running)` and the board gets its answer. +5. Configuration error: `sudo systemctl stop voice-server`, write `include: conf/absent.yaml` in `config.yaml`, + `sudo systemctl start voice-server`: state `failed` (code 78), no restart loop; put the configuration back and restart. ### `fingerprint` branch — step F6: the configuration in several files diff --git a/README.md b/README.md index 0a76e98..e2e26b5 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,41 @@ make lint # typage pyright L'état exact du projet, étape par étape, est dans **[CONTEXT.md](CONTEXT.md)**. Étape courante : **terminée — les étapes 1 à 16 sont validées** (branche `main`). -Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini) et F6 (configuration en plusieurs fichiers) validées. +Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini), F6 (configuration en plusieurs fichiers) et F7 (serveur sous systemd) validées. + +### Branche `fingerprint` — étape F7 : le serveur démarre avec la machine (systemd) + +Le serveur devient un service : il démarre au boot (sans ouvrir de session), est relancé s'il plante, et son journal va dans +`journalctl`. Même schéma que l'agent (`make agent-install`) : une unité modèle dans le dépôt, installée avec `sudo`. + +```bash +make server-install # installe et démarre le service (sudo) ; refuse si un « make run » tourne encore +make server-status # état du service +make server-log # journal en direct (Ctrl-C pour quitter) +sudo systemctl restart voice-server # après un changement de config.yaml, conf/*.yaml, .env ou du code +make server-unit # affiche l'unité qui serait installée, sans rien installer +make server-uninstall # retire le service (le dépôt et les enregistrements restent) +``` + +| Point | Détail | +|---|---| +| compte et dossier | le compte de celui qui lance `make server-install`, dans `server/` de ce dépôt : `config.yaml`, `conf/`, `.env`, `models/`, `recordings/` et `logs/` sont ceux de `make run` ; déplacer le dépôt demande de refaire `make server-install` | +| démarrage | au boot, une fois le réseau en ligne ; si le broker est absent, le serveur démarre et se reconnecte seul (1 à 10 s entre deux essais) ; le chargement de Whisper et de Piper prend quelques secondes | +| plantage | relancé après 5 s | +| configuration ou modèles à corriger | **pas relancé** (code de sortie 78) : l'état est `failed` et `make server-log` dit quoi corriger | +| arrêt | `sudo systemctl stop voice-server` : déconnexion propre du broker | +| `make run` | refusé tant que le service tourne : deux serveurs de même identifiant MQTT se chassent du broker en boucle | +| secrets | `.env` reste dans `server/`, lu par le serveur ; rien n'est copié dans l'unité ni dans le journal | + +Le service lit `server/config.yaml` **tel qu'il est au démarrage** : vérifiez `mqtt.host` avant d'installer (celui du dépôt est +`10.42.0.1`, le Raspberry Pi). + +1. Arrêtez le serveur lancé à la main (Ctrl-C dans le terminal de `make run`), puis `make server-install` : `active (running)`. +2. `make server-log` : `doigts : Denis (empreinte 1)`, puis la connexion au broker ; une session au doigt reçoit sa réponse. +3. Plantage simulé : `sudo systemctl kill -s SIGKILL voice-server` ; le journal montre le redémarrage après 5 s. +4. Redémarrez la machine, sans ouvrir de session : `make server-status` dit `active (running)` et la carte reçoit sa réponse. +5. Erreur de configuration : `sudo systemctl stop voice-server`, écrivez `include: conf/absent.yaml` dans `config.yaml`, + `sudo systemctl start voice-server` : état `failed` (code 78), sans boucle de relance ; remettez la configuration et redémarrez. ### Branche `fingerprint` — étape F6 : la configuration en plusieurs fichiers diff --git a/server/tests/test_config_include.py b/server/tests/test_config_include.py index dea7132..f032586 100644 --- a/server/tests/test_config_include.py +++ b/server/tests/test_config_include.py @@ -8,7 +8,7 @@ from pathlib import Path import pytest -from voice_server.__main__ import main +from voice_server.__main__ import EXIT_SETUP, main from voice_server.settings import read_config SERVER_DIR = Path(__file__).resolve().parents[1] @@ -213,7 +213,7 @@ def test_mqtt_host_stays_readable_by_the_makefile() -> None: def test_server_refuses_to_start_on_a_conflict_and_says_why(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None: """Deux fichiers définissent access.default : pas de trace d'appels, le message nomme les deux fichiers.""" config_copy.write_text(config_copy.read_text(encoding="utf-8") + "\naccess:\n default: standard\n", encoding="utf-8") - assert main(["--config", str(config_copy)]) == 1 + assert main(["--config", str(config_copy)]) == EXIT_SETUP error = capsys.readouterr().err assert "configuration invalide" in error assert "« access.default » est défini à la fois dans" in error @@ -222,5 +222,5 @@ def test_server_refuses_to_start_on_a_conflict_and_says_why(config_copy: Path, c def test_server_refuses_to_start_on_a_missing_included_file(config_copy: Path, capsys: pytest.CaptureFixture[str]) -> None: (config_copy.parent / "conf" / "home.yaml").unlink() - assert main(["--config", str(config_copy)]) == 1 + assert main(["--config", str(config_copy)]) == EXIT_SETUP assert "fichier introuvable" in capsys.readouterr().err diff --git a/server/tests/test_service_unit.py b/server/tests/test_service_unit.py new file mode 100644 index 0000000..e363a78 --- /dev/null +++ b/server/tests/test_service_unit.py @@ -0,0 +1,89 @@ +"""Étape F7 : l'unité systemd du serveur (server/voice-server.service) et les cibles du Makefile qui l'installent.""" + +from __future__ import annotations + +import getpass +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from voice_server.__main__ import EXIT_SETUP + +REPO = Path(__file__).resolve().parents[2] + +pytestmark = pytest.mark.skipif(shutil.which("make") is None, reason="make absent") + + +def make(*args: str, path: str | None = None) -> subprocess.CompletedProcess[str]: + """Lance make à la racine du dépôt, avec un PATH choisi au besoin.""" + env = {**os.environ, "PATH": path} if path else None + return subprocess.run(["make", "-s", *args], cwd=REPO, capture_output=True, text=True, env=env, check=False) + + +def render(folder: Path, user: str = "alice") -> str: + result = make("server-unit", f"SERVICE_USER={user}", f"SERVER_DIR={folder}") + assert result.returncode == 0, result.stderr + return result.stdout + + +def test_unit_is_rendered_for_the_given_user_and_folder(tmp_path: Path) -> None: + text = render(tmp_path) + + assert "@USER@" not in text and "@SERVER_DIR@" not in text + assert "User=alice" in text + assert f"WorkingDirectory={tmp_path}" in text + assert f"ExecStart={tmp_path}/.venv/bin/python -m voice_server --config config.yaml" in text + + +def test_unit_does_not_restart_when_the_setup_is_wrong(tmp_path: Path) -> None: + """Configuration ou modèles à corriger : le code de sortie du serveur est celui que systemd ne relance pas.""" + lines = render(tmp_path).splitlines() + + assert f"RestartPreventExitStatus={EXIT_SETUP}" in lines + assert "Restart=on-failure" in lines + + +@pytest.mark.skipif(shutil.which("systemd-analyze") is None, reason="systemd-analyze absent") +def test_unit_passes_systemd_analyze(tmp_path: Path) -> None: + """systemd lit l'unité sans erreur ni avertissement (programme, dossier et compte existent).""" + python = tmp_path / ".venv" / "bin" / "python" + python.parent.mkdir(parents=True) + python.symlink_to(Path(sys.executable).resolve()) + unit = tmp_path / "voice-server.service" + unit.write_text(render(tmp_path, user=getpass.getuser()), encoding="utf-8") + + result = subprocess.run(["systemd-analyze", "verify", str(unit)], capture_output=True, text=True, check=False) + + assert result.returncode == 0, result.stderr + assert result.stderr.strip() == "" + + +def fake_systemctl(folder: Path, exit_code: int) -> str: + """PATH où « systemctl » répond toujours exit_code (0 = le service est actif, 3 = inactif).""" + script = folder / "systemctl" + script.write_text(f"#!/bin/sh\nexit {exit_code}\n", encoding="utf-8") + script.chmod(0o755) + return f"{folder}{os.pathsep}{os.environ['PATH']}" + + +def test_manual_run_is_refused_while_the_service_runs(tmp_path: Path) -> None: + """Deux serveurs de même identifiant MQTT se chassent du broker : la garde de « make run » refuse.""" + result = make("server-guard", path=fake_systemctl(tmp_path, 0)) + + assert result.returncode != 0 + assert "tourne deja" in result.stdout + result.stderr + + +def test_manual_run_is_allowed_when_the_service_is_stopped(tmp_path: Path) -> None: + assert make("server-guard", path=fake_systemctl(tmp_path, 3)).returncode == 0 + + +def test_run_depends_on_the_guard() -> None: + """« make run » et « make run-echo » passent par la garde (make -n n'exécute rien).""" + for target in ("run", "run-echo"): + result = subprocess.run(["make", "-n", target], cwd=REPO, capture_output=True, text=True, check=False) + assert "systemctl is-active --quiet voice-server" in result.stdout, target diff --git a/server/voice-server.service b/server/voice-server.service new file mode 100644 index 0000000..bca1087 --- /dev/null +++ b/server/voice-server.service @@ -0,0 +1,36 @@ +# Service systemd du serveur vocal (étape F7). Modèle : « make server-install » remplace @USER@ et @SERVER_DIR@ +# (l'utilisateur et le dossier server/ de ce dépôt), puis l'installe dans /etc/systemd/system. +[Unit] +Description=Serveur de l'assistant vocal (Whisper, Piper, MQTT) +After=network-online.target +Wants=network-online.target + +[Service] +# Le serveur tourne sous le compte de l'utilisateur, dans server/ : config.yaml, conf/, .env, models/, +# recordings/ et logs/ sont lus et écrits là, exactement comme avec « make run ». +User=@USER@ +WorkingDirectory=@SERVER_DIR@ +ExecStart=@SERVER_DIR@/.venv/bin/python -m voice_server --config config.yaml +Environment=PYTHONUNBUFFERED=1 +SyslogIdentifier=voice-server + +# Relancé après un plantage. Si le broker est absent au démarrage, le serveur n'en a pas besoin pour démarrer : il +# se reconnecte seul (1 à 10 s entre deux essais). Pas relancé quand la configuration ou les modèles sont à corriger +# (code 78 de voice_server/__main__.py) : un redémarrage n'y changerait rien, le journal dit quoi corriger. +Restart=on-failure +RestartSec=5 +RestartPreventExitStatus=78 + +# SIGTERM : le serveur se déconnecte proprement du broker et journalise « arret du serveur ». +TimeoutStopSec=20 + +# Durcissement léger : rien n'a besoin d'élévation de droits, ni d'écrire hors du dépôt et de /tmp. +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=full +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true + +[Install] +WantedBy=multi-user.target diff --git a/server/voice_server/__main__.py b/server/voice_server/__main__.py index 5cd2b16..74ec869 100644 --- a/server/voice_server/__main__.py +++ b/server/voice_server/__main__.py @@ -40,6 +40,10 @@ from voice_server.settings import Settings, load_settings logger = logging.getLogger("voice_server") +# Code de sortie quand la configuration ou les modèles sont à corriger (EX_CONFIG de sysexits.h). Le service +# systemd (server/voice-server.service, RestartPreventExitStatus) ne relance pas le serveur dans ce cas. +EXIT_SETUP = 78 + SWEEP_PERIOD_S = 0.2 # fréquence de vérification des sessions terminées ou muettes LOG_FILE_BYTES = 1_000_000 # journal fichier : 1 Mo par fichier... LOG_FILE_COUNT = 3 # ... et 3 anciens gardés : 4 Mo au plus @@ -143,7 +147,7 @@ def worker(jobs: "queue.Queue[SessionResult | None]", handle: Callable[[SessionR def main(argv: list[str]) -> int: - """Lance le serveur jusqu'à Ctrl-C.""" + """Lance le serveur jusqu'à Ctrl-C ou SIGTERM. Rend EXIT_SETUP si la configuration ou les modèles sont à corriger.""" parser = argparse.ArgumentParser(description="serveur de l'assistant vocal") parser.add_argument("--config", type=Path, default=Path(__file__).resolve().parents[1] / "config.yaml") parser.add_argument("--echo", action="store_true", @@ -155,7 +159,7 @@ def main(argv: list[str]) -> int: except (ValueError, OSError, yaml.YAMLError) as error: # Le journal n'est pas encore réglé (il dépend de la configuration) : message direct, sans trace d'appels. print(f"configuration invalide : {error}", file=sys.stderr) - return 1 + return EXIT_SETUP setup_logging(settings) logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon logger.info("enregistrements dans %s", settings.recordings_dir) @@ -175,10 +179,10 @@ def main(argv: list[str]) -> int: handle = make_assistant(settings, resampler, sender, link) except ImportError as error: logger.error("%s", error) - return 1 + return EXIT_SETUP except FileNotFoundError as error: logger.error("%s : lancez 'make models'", error) - return 1 + return EXIT_SETUP logger.info("mode assistant : posez un doigt enregistre (ou appuyez sur le bouton) et parlez") jobs: "queue.Queue[SessionResult | None]" = queue.Queue()