F8 : modèle de configuration versionné (config.example.yaml), server/config.yaml local et ignoré

server/config.example.yaml est le modèle (mqtt.host 10.42.0.1, en-tête qui explique le mécanisme) ;
server/config.yaml n'est plus suivi par git (git rm --cached : le fichier de l'utilisateur reste sur son
disque) et entre dans .gitignore. Plus de risque de commiter une adresse de broker locale.

Makefile : make config crée server/config.yaml depuis le modèle sans jamais l'écraser, make install le
lance (comme pour server/.env), make config-diff montre l'écart avec le modèle ; MQTT_HOST se lit dans
config.yaml ou, à défaut, dans le modèle ; server-install exige config.yaml. __main__.py : un config.yaml
absent dit « make config le crée depuis config.example.yaml » (code 78).

Les tests lisent le modèle (7 fichiers et conftest.py) : ils ne dépendent plus de la copie locale et
passent sur un clone neuf (312 tests, vérifiés sur l'arbre indexé, sans config.yaml). 7 tests nouveaux :
modèle, .gitignore, make config (création, jamais d'écrasement), config-diff, message d'un fichier absent.
server/conf/*.yaml restent versionnés. Sur une autre machine qui avait déjà ce dépôt, le premier git pull
retire le config.yaml suivi jusque-là : le sauvegarder avant (voir README).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Denis Defolie
2026-10-19 15:29:28 +02:00
parent 5362014c6b
commit 5dff1b3aba
17 changed files with 216 additions and 34 deletions
+3
View File
@@ -15,6 +15,9 @@ mosquitto/passwd
agent/agent.yaml agent/agent.yaml
mosquitto/*.pwd mosquitto/*.pwd
# --- Configuration locale du serveur (modèle versionné : server/config.example.yaml, « make config ») ---
server/config.yaml
# --- Données personnelles (voix = donnée biométrique) --- # --- Données personnelles (voix = donnée biométrique) ---
docs/test-suivi-perso.txt docs/test-suivi-perso.txt
recordings/ recordings/
+20 -5
View File
@@ -53,7 +53,8 @@ capteur R503 + bouton conservé) — mêmes règles de validation :
| 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)** | | 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)** | | 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** (`0d00b50`) | **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)** | | F7 | Le serveur démarre avec la machine : service systemd (`make server-install`) | **fait** (`311fde1`) | **oui (2026-10-19)** |
| F8 | `server/config.example.yaml` versionné, `server/config.yaml` ignoré par git, créé par `make install` / `make config` | **fait** | **oui (2026-10-19)** |
**Exigence ajoutée par l'utilisateur (2026-09-30)** : l'assistant doit aussi pouvoir **commander des **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 : machines Linux du réseau**. Absente de la feuille de route du prompt. Proposition en discussion :
@@ -206,6 +207,8 @@ server/voice_server/settings.py config.yaml (+ include, F6) + .env
server/conf/home.yaml, machines.yaml, access.yaml sections home / machines / access + fingerprint [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/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/voice-server.service modèle d'unité systemd (@USER@, @SERVER_DIR@) [F7]
server/config.example.yaml modèle de configuration versionné ; config.yaml = copie locale ignorée [F8]
server/tests/test_config_example.py modèle, .gitignore, make config / config-diff, message d'un config.yaml absent [F8]
server/tests/test_service_unit.py rendu de l'unité, systemd-analyze, garde de « make run » [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/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/audio_buffer.py PCM borné, niveaux, écriture WAV [étape 4]
@@ -269,7 +272,7 @@ TLS (option de l'étape 15, non activée).
### État au 2026-10-19 (branche `fingerprint`) ### État au 2026-10-19 (branche `fingerprint`)
- Branche `fingerprint` : **F1 à F4b, F5, F6 et F7 validées**. Commits : `67bd4a4` (F1), `19c935c` (F2), `0c7fae1` (F3), `6e432be` (F4), - Branche `fingerprint` : **F1 à F4b, F5, F6, F7 et F8 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, `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 ». 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 ; - F6 (configuration en plusieurs fichiers) **validée par l'utilisateur le 2026-10-19** ; `make test` : 300 tests, pyright 0 erreur ;
@@ -277,9 +280,9 @@ TLS (option de l'étape 15, non activée).
similarité). similarité).
- Avant F6 : 272 tests, pyright 0 erreur, `make fw-check` SUCCESS pour `esp32dev` (RAM 36,9 % / Flash 33,2 %) et `esp32s3mini` - Avant F6 : 272 tests, pyright 0 erreur, `make fw-check` SUCCESS pour `esp32dev` (RAM 36,9 % / Flash 33,2 %) et `esp32s3mini`
(36,8 % / 32,8 %). (36,8 % / 32,8 %).
- Le `server/config.yaml` de travail de l'utilisateur garde `mqtt.host: 192.168.1.4` (non commité, le dépôt garde `10.42.0.1`) ; - Depuis F8, `server/config.yaml` n'est plus suivi par git : c'est la copie locale de l'utilisateur (`mqtt.host: 192.168.1.4`),
`wake.enabled: false` sur la branche (le doigt remplace le mot de réveil). Pour commiter `config.yaml`, ne jamais embarquer cette créée depuis `server/config.example.yaml` (modèle, `mqtt.host: 10.42.0.1`) par `make install` / `make config`. Plus besoin de
adresse (index forcé par `git hash-object -w` + `git update-index --cacheinfo`). l'index forcé (`git hash-object` + `update-index`) : le modèle se commite normalement. `wake.enabled: false` sur la branche.
- Après `git merge main` : le firmware de `main` n'a pas le capteur ; relire `main.cpp` en cas de conflit. - Après `git merge main` : le firmware de `main` n'a pas le capteur ; relire `main.cpp` en cas de conflit.
- Décisions de l'utilisateur (2026-10-19) : le schéma WROOM (`wiring.svg`) **reste tel quel** (sans R503 ni LED de démonstration) ; - Décisions de l'utilisateur (2026-10-19) : le schéma WROOM (`wiring.svg`) **reste tel quel** (sans R503 ni LED de démonstration) ;
**pas de liste de réseaux** dans le portail (le nom se recopie à l'identique). **pas de liste de réseaux** dans le portail (le nom se recopie à l'identique).
@@ -1152,3 +1155,15 @@ profils vocaux, enregistrements (wav/mp3), modèles, journaux et environnements
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`. 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 `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`). n'est pas dans le commit de F7 (reste dans l'historique : `git show d20976f:prompt-assistant-vocal-esp32.md`).
- **2026-10-19** — **F8 écrite** (demande : « faire un config.example.yaml et mettre config.yaml dans .gitignore. Faire un cp
config.example vers config à l'install »). `server/config.example.yaml` = version du dépôt (`mqtt.host: 10.42.0.1`) + en-tête qui
explique le mécanisme ; `.gitignore` : `server/config.yaml` ; `Makefile` : `config` (copie sans jamais écraser), `config-diff`,
`install: venv config`, `MQTT_HOST` lu dans `config.yaml` ou, à défaut, dans le modèle, `server-install` exige `config.yaml` ;
`__main__.py` : un `config.yaml` absent dit « make config le crée depuis config.example.yaml ». **Les tests lisent le modèle**
(7 fichiers de tests + `conftest.py`) : ils ne dépendent plus de la copie locale et passent sur un clone neuf. Le fichier local de
l'utilisateur n'est pas touché (`git rm --cached` : il reste sur le disque, ignoré). `server/conf/*.yaml` restent versionnés.
**Autres machines** : au premier `git pull` de cette étape, git y supprime le `config.yaml` suivi jusque-là (à sauvegarder avant).
- **2026-10-19** — **F8 validée** par l'utilisateur (« uniquement commiter F8 et pousser ») : le commit retire `server/config.yaml` de
l'index (`git rm --cached`, le fichier local reste sur le disque), ajoute `config.example.yaml`, `.gitignore`, le Makefile, les
tests et la documentation. **Décision** : `server/conf/*.yaml` restent versionnés (pas de modèle `*.example.yaml` pour eux) ; à
reprendre si l'utilisateur enregistre d'autres personnes (`conf/access.yaml` porte les noms).
+15 -4
View File
@@ -11,6 +11,9 @@ PIO_VENV := .pio-venv
PIO := $(PIO_VENV)/bin/pio PIO := $(PIO_VENV)/bin/pio
FW_DIR := firmware FW_DIR := firmware
# Service systemd du serveur (étape F7) : compte qui le fait tourner, dossier server/ de ce dépôt. # Service systemd du serveur (étape F7) : compte qui le fait tourner, dossier server/ de ce dépôt.
# Configuration du serveur : le modèle est versionné, la copie locale (ignorée par git) est celle que le serveur lit.
CONFIG_FILE ?= server/config.yaml
CONFIG_EXAMPLE ?= server/config.example.yaml
SERVICE := voice-server SERVICE := voice-server
SERVICE_USER ?= $(shell id -un) SERVICE_USER ?= $(shell id -un)
SERVER_DIR = $(realpath server) SERVER_DIR = $(realpath server)
@@ -28,9 +31,9 @@ JITTER ?= 0
VOICE ?= fr_FR-tom-medium VOICE ?= fr_FR-tom-medium
SPEAKER ?= SPEAKER ?=
SAY_OUT ?= recordings/voix-test/phrase.wav SAY_OUT ?= recordings/voix-test/phrase.wav
# Adresse du broker : UN seul réglage, mqtt.host de server/config.yaml, relu ici pour les # Adresse du broker : UN seul réglage, mqtt.host de server/config.yaml (à défaut, du modèle), relu ici pour les
# cibles mqtt-* (surcharge ponctuelle : make mqtt-watch MQTT_HOST=...). # cibles mqtt-* (surcharge ponctuelle : make mqtt-watch MQTT_HOST=...).
MQTT_HOST ?= $(shell awk '/^mqtt:/{m=1;next} m && $$1=="host:"{print $$2; exit}' server/config.yaml) MQTT_HOST ?= $(shell awk '/^mqtt:/{m=1;next} m && $$1=="host:"{print $$2; exit}' $(if $(wildcard $(CONFIG_FILE)),$(CONFIG_FILE),$(CONFIG_EXAMPLE)))
MSG ?= {"cmd":"ping"} MSG ?= {"cmd":"ping"}
MOSQ_DIR ?= $(HOME)/srv/mosquitto MOSQ_DIR ?= $(HOME)/srv/mosquitto
MOSQ_COMPOSE ?= $(HOME)/srv/docker-compose.mosquitto.yml MOSQ_COMPOSE ?= $(HOME)/srv/docker-compose.mosquitto.yml
@@ -47,7 +50,7 @@ MQTT_AS = @echo "(compte MQTT : $(if $(MQTT_USERNAME),$(MQTT_USERNAME) de s
.DEFAULT_GOAL := help .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 \ .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 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 \ say latency finger-list finger-enroll finger-delete speech-check transcribe run config config-diff 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 fw-monitor clean
## ------------------------------------------------------------------ aide ## ------------------------------------------------------------------ aide
@@ -143,7 +146,7 @@ venv: ## Crée l'environnement virtuel Python
python3 -m venv $(VENV) python3 -m venv $(VENV)
$(PIP) install --upgrade pip setuptools wheel $(PIP) install --upgrade pip setuptools wheel
install: venv ## Installe le serveur Python (dépendances de base) install: venv config ## Installe le serveur Python (dépendances de base) et crée server/config.yaml s'il manque
$(PIP) install -e server $(PIP) install -e server
@test -f server/.env || { cp server/.env.example server/.env; echo "server/.env créé depuis .env.example — renseigner MQTT_USERNAME/PASSWORD."; } @test -f server/.env || { cp server/.env.example server/.env; echo "server/.env créé depuis .env.example — renseigner MQTT_USERNAME/PASSWORD."; }
@@ -153,6 +156,13 @@ install-dev: install pio-venv ## Installe en plus les outils de développement
install-speech: install ## Installe faster-whisper et Piper (étape 6) install-speech: install ## Installe faster-whisper et Piper (étape 6)
$(PIP) install -e "server[speech]" $(PIP) install -e "server[speech]"
config: ## Crée server/config.yaml depuis config.example.yaml, sans jamais écraser un fichier existant
@if [ -f $(CONFIG_FILE) ]; then echo "$(CONFIG_FILE) existe deja : rien a faire (make config-diff le compare au modele)."; \
else cp $(CONFIG_EXAMPLE) $(CONFIG_FILE) && echo "$(CONFIG_FILE) cree depuis $(notdir $(CONFIG_EXAMPLE)) : verifiez mqtt.host."; fi
config-diff: ## Montre ce qui diffère entre le modèle config.example.yaml et votre server/config.yaml
@diff -u $(CONFIG_EXAMPLE) $(CONFIG_FILE) || true
models: ## Télécharge Whisper et la voix Piper de config.yaml dans server/models models: ## Télécharge Whisper et la voix Piper de config.yaml dans server/models
$(PY) tools/download_models.py $(PY) tools/download_models.py
@@ -200,6 +210,7 @@ server-install: ## Installe le serveur comme service (sudo) : démarre au boot,
@if pgrep -f '[v]oice_server --config' >/dev/null; then \ @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 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; } @test -x $(SERVER_DIR)/.venv/bin/python || { echo "server/.venv absent : make install"; exit 1; }
@test -f $(CONFIG_FILE) || { echo "$(CONFIG_FILE) absent : make config, puis verifiez mqtt.host"; exit 1; }
$(RENDER_UNIT) | sudo tee /etc/systemd/system/$(SERVICE).service >/dev/null $(RENDER_UNIT) | sudo tee /etc/systemd/system/$(SERVICE).service >/dev/null
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable --now $(SERVICE) sudo systemctl enable --now $(SERVICE)
+32 -3
View File
@@ -205,7 +205,7 @@ make run
| File | Contents | | File | Contents |
|---|---| |---|---|
| `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` |
| `server/config.yaml` | general settings (audio, MQTT, voices, log) and the list of included files | | `server/config.yaml` | **your local copy** (ignored by git, created by `make install` from `config.example.yaml`): general settings (audio, MQTT, voices, log) and the list of included files |
| `server/conf/home.yaml` | rooms and the room of each board | | `server/conf/home.yaml` | rooms and the room of each board |
| `server/conf/machines.yaml` | Linux machines on the network and their actions | | `server/conf/machines.yaml` | Linux machines on the network and their actions |
| `server/conf/access.yaml` | rights per person (`access`) and the owner of each finger (`fingerprint`) | | `server/conf/access.yaml` | rights per person (`access`) and the owner of each finger (`fingerprint`) |
@@ -305,7 +305,36 @@ make lint # pyright type check
The exact state of the project, step by step, lives in **[CONTEXT.md](CONTEXT.md)**. 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). Current step: **done — steps 1 to 16 are validated** (`main` branch).
`fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini), F6 (configuration in several files) and F7 (server under systemd) validated. `fingerprint` branch: F1 to F4b, F5 (ESP32-S3 Mini), F6 (configuration in several files), F7 (server under systemd) and F8 (versioned configuration template, ignored local copy) validated
### `fingerprint` branch — step F8: a versioned configuration template, an ignored local copy
`server/config.example.yaml` is the **template** (versioned); `server/config.yaml` is **your copy** (ignored by git): the
server, the tools and the service read that one. No more risk of committing your broker address, or of losing it to a
"discard changes".
```bash
make install # creates server/config.yaml from the template if missing (like server/.env), never overwriting it
make config # the same, alone
make config-diff # what differs between the template and your copy (re-read it when the template changes)
```
| Point | Detail |
|---|---|
| fresh clone | `make install` creates `server/config.yaml`; **check `mqtt.host`** (the template points at `10.42.0.1`, the Raspberry Pi) |
| the template changes | your copy is not touched: `make config-diff`, then carry the new keys over by hand |
| `server/conf/*.yaml` | stay versioned (starting values); only `config.yaml` is local |
| `make run`, service | a missing `config.yaml` gives `configuration invalide` and "`make config` creates it from config.example.yaml" |
| tests | they read the template: their results do not depend on your copy |
**Another machine that already has this repository** (the Raspberry Pi, a second PC): on the first `git pull` that brings this
step, git removes the `server/config.yaml` it used to track. Copy it before (`cp server/config.yaml ~/config.yaml.backup`)
and put it back afterwards; without local changes, `make config` recreates a file from the template.
1. `git pull` has nothing to do on your machine: your `server/config.yaml` stays (same content, `192.168.1.4`), and `git status`
no longer shows it.
2. `make config`: "existe deja: rien a faire"; `make config-diff`: shows only your differences (broker address…).
3. Fresh clone (temporary folder): `make config` creates `server/config.yaml` from the template.
### `fingerprint` branch — step F7: the server starts with the machine (systemd) ### `fingerprint` branch — step F7: the server starts with the machine (systemd)
@@ -331,7 +360,7 @@ make server-uninstall # removes the service (the repository and the recordings
| `make run` | refused while the service runs: two servers with the same MQTT identifier kick each other out of the broker in a loop | | `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 | | 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 The service reads `server/config.yaml` **as it is at start-up**: check `mqtt.host` before installing (the template's value is
`10.42.0.1`, the Raspberry Pi). `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)`. 1. Stop the server started by hand (Ctrl-C in the `make run` terminal), then `make server-install`: `active (running)`.
+32 -3
View File
@@ -207,7 +207,7 @@ make run
| Fichier | Contenu | | Fichier | Contenu |
|---|---| |---|---|
| `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` | | `server/.env` | `MQTT_USERNAME`, `MQTT_PASSWORD` |
| `server/config.yaml` | réglages généraux (audio, MQTT, voix, journal) et liste des fichiers inclus | | `server/config.yaml` | **votre copie locale** (ignorée par git, créée par `make install` depuis `config.example.yaml`) : réglages généraux (audio, MQTT, voix, journal) et liste des fichiers inclus |
| `server/conf/home.yaml` | pièces et pièce de chaque carte | | `server/conf/home.yaml` | pièces et pièce de chaque carte |
| `server/conf/machines.yaml` | machines Linux du réseau et leurs actions | | `server/conf/machines.yaml` | machines Linux du réseau et leurs actions |
| `server/conf/access.yaml` | droits par personne (`access`) et propriétaire de chaque doigt (`fingerprint`) | | `server/conf/access.yaml` | droits par personne (`access`) et propriétaire de chaque doigt (`fingerprint`) |
@@ -307,7 +307,36 @@ make lint # typage pyright
L'état exact du projet, étape par étape, est dans **[CONTEXT.md](CONTEXT.md)**. 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`). Étape courante : **terminée — les étapes 1 à 16 sont validées** (branche `main`).
Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini), F6 (configuration en plusieurs fichiers) et F7 (serveur sous systemd) validées. Branche `fingerprint` : F1 à F4b, F5 (ESP32-S3 Mini), F6 (configuration en plusieurs fichiers), F7 (serveur sous systemd) et F8 (modèle de configuration versionné, copie locale ignorée) validées
### Branche `fingerprint` — étape F8 : un modèle de configuration versionné, une copie locale ignorée
`server/config.example.yaml` est le **modèle** (versionné) ; `server/config.yaml` est **votre copie** (ignorée par git) : le serveur,
les outils et le service lisent celle-là. Plus de risque de commiter votre adresse de broker, ni de la perdre à un
« annuler les modifications ».
```bash
make install # crée server/config.yaml depuis le modèle s'il manque (comme server/.env), sans jamais l'écraser
make config # la même chose, seule
make config-diff # ce qui diffère entre le modèle et votre copie (à relire quand le modèle change)
```
| Point | Détail |
|---|---|
| clone neuf | `make install` crée `server/config.yaml` ; **vérifiez `mqtt.host`** (le modèle vise `10.42.0.1`, le Raspberry Pi) |
| le modèle change | votre copie n'est pas touchée : `make config-diff`, puis reportez à la main les nouvelles clés |
| `server/conf/*.yaml` | restent versionnés (valeurs de départ) ; seul `config.yaml` est local |
| `make run`, service | un `config.yaml` absent donne `configuration invalide` et « `make config` le crée depuis config.example.yaml » |
| tests | ils lisent le modèle : leurs résultats ne dépendent pas de votre copie |
**Autre machine qui a déjà ce dépôt** (le Raspberry Pi, un second PC) : au premier `git pull` qui apporte cette étape, git retire
le `server/config.yaml` suivi jusque-là. Copiez-le avant (`cp server/config.yaml ~/config.yaml.sauvegarde`) puis remettez-le
après ; sans modification locale, `make config` recrée un fichier depuis le modèle.
1. `git pull` n'a rien à faire chez vous : votre `server/config.yaml` reste (même contenu, `192.168.1.4`), et `git status` ne le
montre plus.
2. `make config` : « existe deja : rien a faire » ; `make config-diff` : montre seulement vos différences (adresse du broker…).
3. Clone neuf (dossier temporaire) : `make config` crée `server/config.yaml` depuis le modèle.
### Branche `fingerprint` — étape F7 : le serveur démarre avec la machine (systemd) ### Branche `fingerprint` — étape F7 : le serveur démarre avec la machine (systemd)
@@ -333,7 +362,7 @@ make server-uninstall # retire le service (le dépôt et les enregistrements re
| `make run` | refusé tant que le service tourne : deux serveurs de même identifiant MQTT se chassent du broker en boucle | | `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 | | 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 Le service lit `server/config.yaml` **tel qu'il est au démarrage** : vérifiez `mqtt.host` avant d'installer (celui du modèle est
`10.42.0.1`, le Raspberry Pi). `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)`. 1. Arrêtez le serveur lancé à la main (Ctrl-C dans le terminal de `make run`), puis `make server-install` : `active (running)`.
@@ -1,4 +1,7 @@
# Configuration du serveur vocal. # Configuration du serveur vocal : MODÈLE versionné (config.example.yaml).
# « make config » (lancé aussi par « make install ») en fait server/config.yaml, ignoré par git : c'est ce fichier
# que le serveur lit et que vous adaptez (mqtt.host, doigts, droits…). Il n'est jamais écrasé ; « make config-diff »
# montre ce qui diffère de ce modèle quand celui-ci change.
# Les valeurs sensibles (mots de passe, jetons) vont dans .env, jamais ici. # Les valeurs sensibles (mots de passe, jetons) vont dans .env, jamais ici.
# Les sections marquées « étape N » ne sont lues qu'à partir de cette étape. # Les sections marquées « étape N » ne sont lues qu'à partir de cette étape.
# Branche fingerprint : pas de VAD, de diarisation, de voix ni de mot de réveil (étapes F3 à F4b). # Branche fingerprint : pas de VAD, de diarisation, de voix ni de mot de réveil (étapes F3 à F4b).
+3 -2
View File
@@ -12,12 +12,13 @@ SERVER_DIR = Path(__file__).resolve().parents[1]
@pytest.fixture @pytest.fixture
def config_copy(tmp_path: Path) -> Path: def config_copy(tmp_path: Path) -> Path:
"""Copie de config.yaml et des fichiers qu'il inclut (server/conf) : modifiable sans toucher aux vrais. """Copie du modèle config.example.yaml (sous le nom config.yaml) et des fichiers qu'il inclut (server/conf) :
modifiable sans toucher aux vrais, et indépendante de la copie locale de l'utilisateur.
Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin. Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin.
""" """
destination = tmp_path / "server" destination = tmp_path / "server"
destination.mkdir() destination.mkdir()
shutil.copy2(SERVER_DIR / "config.yaml", destination / "config.yaml") shutil.copy2(SERVER_DIR / "config.example.yaml", destination / "config.yaml")
shutil.copytree(SERVER_DIR / "conf", destination / "conf") shutil.copytree(SERVER_DIR / "conf", destination / "conf")
return destination / "config.yaml" return destination / "config.yaml"
+2 -2
View File
@@ -159,8 +159,8 @@ def test_other_request_drops_the_pending_one(policy: AccessPolicy) -> None:
def test_project_config_is_valid() -> None: def test_project_config_is_valid() -> None:
"""Le config.yaml du dépôt se charge, et ses règles s'appliquent vraiment (profil standard).""" """Le modèle config.example.yaml se charge, et ses règles s'appliquent vraiment (profil standard)."""
settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml")
policy = AccessPolicy(settings.access, settings.home, settings.machines) policy = AccessPolicy(settings.access, settings.home, settings.machines)
for action in ("on", "off"): # on/off nus en YAML = booléens : Pierre refusé à l'essai réel for action in ("on", "off"): # on/off nus en YAML = booléens : Pierre refusé à l'essai réel
assert policy.check(DeviceCommand(action, "light", "salon"), "Pierre").allowed assert policy.check(DeviceCommand(action, "light", "salon"), "Pierre").allowed
+88
View File
@@ -0,0 +1,88 @@
"""Étape F8 : config.example.yaml est le modèle versionné ; server/config.yaml est la copie locale, ignorée par git."""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
import pytest
from voice_server.__main__ import EXIT_SETUP, main
from voice_server.settings import load_settings
SERVER_DIR = Path(__file__).resolve().parents[1]
REPO = SERVER_DIR.parent
EXAMPLE = SERVER_DIR / "config.example.yaml"
def make(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(["make", "-s", *args], cwd=REPO, capture_output=True, text=True, check=False)
def test_example_loads_and_keeps_the_repository_broker() -> None:
"""Le modèle se charge seul (un clone neuf n'a pas de config.yaml) et vise le broker du dépôt."""
settings = load_settings(EXAMPLE)
assert settings.mqtt.host == "10.42.0.1"
assert settings.home.rooms and settings.access.users
@pytest.mark.skipif(shutil.which("git") is None or not (REPO / ".git").exists(), reason="pas un dépôt git")
def test_local_config_is_ignored_by_git_and_the_example_is_not() -> None:
def ignored(path: str) -> bool:
return subprocess.run(["git", "check-ignore", "--no-index", "-q", path], cwd=REPO, check=False).returncode == 0
assert ignored("server/config.yaml")
assert not ignored("server/config.example.yaml")
@pytest.mark.skipif(shutil.which("make") is None, reason="make absent")
def test_make_config_creates_the_local_file_from_the_example(tmp_path: Path) -> None:
target = tmp_path / "config.yaml"
result = make("config", f"CONFIG_FILE={target}", f"CONFIG_EXAMPLE={EXAMPLE}")
assert result.returncode == 0, result.stderr
assert target.read_text(encoding="utf-8") == EXAMPLE.read_text(encoding="utf-8")
assert "verifiez mqtt.host" in result.stdout
@pytest.mark.skipif(shutil.which("make") is None, reason="make absent")
def test_make_config_never_overwrites_an_existing_file(tmp_path: Path) -> None:
target = tmp_path / "config.yaml"
target.write_text("mqtt:\n host: 192.168.1.4\n", encoding="utf-8")
result = make("config", f"CONFIG_FILE={target}", f"CONFIG_EXAMPLE={EXAMPLE}")
assert result.returncode == 0
assert target.read_text(encoding="utf-8") == "mqtt:\n host: 192.168.1.4\n"
assert "existe deja" in result.stdout
@pytest.mark.skipif(shutil.which("make") is None, reason="make absent")
def test_make_install_creates_the_config() -> None:
"""« make install » passe par la cible config (make -n n'exécute rien)."""
result = subprocess.run(["make", "-n", "install"], cwd=REPO, capture_output=True, text=True, check=False)
assert "cp server/config.example.yaml server/config.yaml" in result.stdout
@pytest.mark.skipif(shutil.which("make") is None, reason="make absent")
def test_config_diff_shows_what_changed_from_the_example(tmp_path: Path) -> None:
local = tmp_path / "config.yaml"
local.write_text(EXAMPLE.read_text(encoding="utf-8").replace("10.42.0.1", "192.168.1.4"), encoding="utf-8")
result = make("config-diff", f"CONFIG_FILE={local}", f"CONFIG_EXAMPLE={EXAMPLE}")
assert "- host: 10.42.0.1" in result.stdout and "+ host: 192.168.1.4" in result.stdout
def test_server_says_how_to_create_a_missing_config(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""Un clone neuf lance le serveur sans config.yaml : le message dit quoi faire."""
shutil.copy2(EXAMPLE, tmp_path / "config.example.yaml")
shutil.copytree(SERVER_DIR / "conf", tmp_path / "conf")
assert main(["--config", str(tmp_path / "config.yaml")]) == EXIT_SETUP
assert "make config" in capsys.readouterr().err
+5 -5
View File
@@ -181,24 +181,24 @@ def test_included_file_must_be_a_mapping(tmp_path: Path) -> None:
read_config(config) read_config(config)
# --------------------------------------------------------------------------- le config.yaml du dépôt # --------------------------------------------------------------------------- le modèle du dépôt
def test_project_config_takes_its_sections_from_conf() -> None: def test_project_config_takes_its_sections_from_conf() -> None:
"""Les sections découpées arrivent bien de server/conf, et « include » ne reste pas dans le résultat.""" """Les sections découpées arrivent bien de server/conf, et « include » ne reste pas dans le résultat."""
config = read_config(SERVER_DIR / "config.yaml") config = read_config(SERVER_DIR / "config.example.yaml")
assert "include" not in config assert "include" not in config
for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"): for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"):
assert section in config, section assert section in config, section
raw = (SERVER_DIR / "config.yaml").read_text(encoding="utf-8") raw = (SERVER_DIR / "config.example.yaml").read_text(encoding="utf-8")
for moved in ("home", "machines", "access", "fingerprint"): for moved in ("home", "machines", "access", "fingerprint"):
assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/" assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/"
def test_mqtt_host_stays_readable_by_the_makefile() -> None: def test_mqtt_host_stays_readable_by_the_makefile() -> None:
"""Le Makefile lit mqtt.host dans config.yaml avec awk : la section mqtt doit y rester.""" """Le Makefile lit mqtt.host dans config.yaml (à défaut, dans le modèle) avec awk : la section mqtt doit y rester."""
inside = False inside = False
host = "" host = ""
for line in (SERVER_DIR / "config.yaml").read_text(encoding="utf-8").splitlines(): for line in (SERVER_DIR / "config.example.yaml").read_text(encoding="utf-8").splitlines():
if line.startswith("mqtt:"): if line.startswith("mqtt:"):
inside = True inside = True
continue continue
+2 -2
View File
@@ -18,7 +18,7 @@ if str(TOOLS_DIR) not in sys.path:
from finger import command_delete, command_enroll, command_list, enrollment_message # noqa: E402 from finger import command_delete, command_enroll, command_list, enrollment_message # noqa: E402
CONFIG = Path(__file__).resolve().parents[1] / "config.yaml" CONFIG = Path(__file__).resolve().parents[1] / "config.example.yaml"
BOOK = FingerprintBook(FingerprintSettings(users={1: "Denis", 2: "Denis", 5: "Jessica"})) BOOK = FingerprintBook(FingerprintSettings(users={1: "Denis", 2: "Denis", 5: "Jessica"}))
@@ -64,7 +64,7 @@ def test_free_id_skips_taken_and_named_slots_and_keeps_zero_free() -> None:
def test_project_config_loads() -> None: def test_project_config_loads() -> None:
"""Le config.yaml du dépôt se charge ; son contenu appartient à l'utilisateur (ses doigts).""" """Le modèle config.example.yaml se charge (la copie locale server/config.yaml, elle, appartient à l'utilisateur)."""
users = load_settings(CONFIG).fingerprint.users users = load_settings(CONFIG).fingerprint.users
assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items()) assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items())
+2 -2
View File
@@ -103,6 +103,6 @@ def test_assistant_prefers_home_commands_then_chat() -> None:
def test_project_config_rooms_and_boards() -> None: def test_project_config_rooms_and_boards() -> None:
"""Le config.yaml du dépôt déclare la pièce de la carte parmi les pièces connues.""" """Le modèle config.example.yaml déclare la pièce de la carte parmi les pièces connues."""
home = load_settings(Path(__file__).resolve().parents[1] / "config.yaml").home home = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml").home
assert home.boards["esp32-01"] in home.rooms assert home.boards["esp32-01"] in home.rooms
+1 -1
View File
@@ -26,7 +26,7 @@ from voice_server.machine_control import (
from voice_server.mqtt_link import MqttLink from voice_server.mqtt_link import MqttLink
from voice_server.settings import MachinesSettings, load_settings from voice_server.settings import MachinesSettings, load_settings
SETTINGS = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") SETTINGS = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml")
MACHINES = SETTINGS.machines MACHINES = SETTINGS.machines
ONLINE = AgentStatus(online=True, actions=("lock", "reboot", "shutdown")) ONLINE = AgentStatus(online=True, actions=("lock", "reboot", "shutdown"))
ONLINE_PAYLOAD = json.dumps({"status": "online", "actions": ["lock", "reboot", "shutdown"]}).encode() ONLINE_PAYLOAD = json.dumps({"status": "online", "actions": ["lock", "reboot", "shutdown"]}).encode()
+1 -1
View File
@@ -15,7 +15,7 @@ from voice_server.__main__ import setup_logging
from voice_server.mqtt_link import presence_topic, refusal_hint, split_topic from voice_server.mqtt_link import presence_topic, refusal_hint, split_topic
from voice_server.settings import load_settings from voice_server.settings import load_settings
CONFIG = Path(__file__).resolve().parents[1] / "config.yaml" CONFIG = Path(__file__).resolve().parents[1] / "config.example.yaml"
def test_presence_topic_is_not_taken_for_a_board() -> None: def test_presence_topic_is_not_taken_for_a_board() -> None:
+2 -2
View File
@@ -170,8 +170,8 @@ def test_split_topic(topic: str, expected: tuple[str, str] | None) -> None:
def test_project_config_loads() -> None: def test_project_config_loads() -> None:
"""Le config.yaml du dépôt se charge et reste cohérent avec le firmware.""" """Le modèle config.example.yaml se charge et reste cohérent avec le firmware."""
settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml")
assert settings.audio.bytes_per_second == 32000 assert settings.audio.bytes_per_second == 32000
assert settings.mqtt.topic_prefix == "voice" assert settings.mqtt.topic_prefix == "voice"
+1 -1
View File
@@ -19,7 +19,7 @@ from voice_server.speech_to_text import SpeechToText
from voice_server.text_normalize import normalize from voice_server.text_normalize import normalize
from voice_server.text_to_speech import TextToSpeech from voice_server.text_to_speech import TextToSpeech
SETTINGS: Settings = load_settings(Path(__file__).resolve().parents[1] / "config.yaml") SETTINGS: Settings = load_settings(Path(__file__).resolve().parents[1] / "config.example.yaml")
pytestmark = pytest.mark.skipif( pytestmark = pytest.mark.skipif(
not (SETTINGS.stt.model_dir / "model.bin").exists() or not SETTINGS.tts.model_path.exists(), not (SETTINGS.stt.model_dir / "model.bin").exists() or not SETTINGS.tts.model_path.exists(),
+3
View File
@@ -159,6 +159,9 @@ def main(argv: list[str]) -> int:
except (ValueError, OSError, yaml.YAMLError) as error: 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. # 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) print(f"configuration invalide : {error}", file=sys.stderr)
example = args.config.with_name(f"{args.config.stem}.example{args.config.suffix}")
if isinstance(error, FileNotFoundError) and not args.config.exists() and example.exists():
print(f"{args.config} n'existe pas : « make config » le crée depuis {example.name}", file=sys.stderr)
return EXIT_SETUP return EXIT_SETUP
setup_logging(settings) setup_logging(settings)
logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon