mirror of
https://github.com/deunix-educ/voice-assistant.git
synced 2026-11-26 20:19:43 +01:00
F6 : la configuration en plusieurs fichiers (include, motifs), sections dans server/conf/
config.yaml peut inclure d'autres fichiers par la clé include : chemins relatifs au fichier qui inclut, motifs (*, ?, **) triés par nom, un fichier inclus peut en inclure d'autres (8 niveaux, boucle refusée). Les mappings s'additionnent (home.rooms peut venir de plusieurs fichiers) ; une même valeur définie dans deux fichiers est une erreur qui nomme les deux, les listes ne se concatènent pas. mqtt reste dans config.yaml : le Makefile y lit mqtt.host. Un config.yaml sans include fonctionne comme avant. server/conf/home.yaml, machines.yaml et access.yaml (access + fingerprint) reprennent les sections et leurs commentaires ; la configuration lue est identique à celle d'avant, comparée valeur par valeur. Le serveur s'arrête sur une configuration invalide avec un message, sans trace d'appels. tools/finger.py indique server/conf/access.yaml. Tests : 28 pour l'inclusion (simple, liste, motifs, fusion, conflits, boucle, profondeur, types invalides, démarrage du serveur) ; conftest.py copie la configuration pour les tests qui la réécrivaient (droits, journal, empreintes). Documentation : README FR/EN, CONTEXT.md. server/config.yaml garde mqtt.host 10.42.0.1 : l'adresse locale de l'utilisateur n'est pas commitée. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
# Inclus par config.yaml (clé include). Sections : access, fingerprint.
|
||||
|
||||
# étape 14 : droits par personne. Depuis F4, la personne est celle dont le DOIGT a ouvert la session
|
||||
# (section fingerprint, plus bas) ; la voix n'identifie plus personne. Niveaux : complet > standard > limite.
|
||||
# Les noms se comparent sans tenir compte de la casse ni des accents (« denis » = « Denis »).
|
||||
access:
|
||||
unknown: limite # bouton PTT, ou doigt sans nom dans fingerprint.users : conversation seulement
|
||||
default: standard # personne nommée par un doigt, absente de users
|
||||
users: # nom de la personne → niveau ; le nom est celui de fingerprint.users
|
||||
Denis: complet
|
||||
rules: # niveau minimal par appareil et action ; absent = complet
|
||||
light: {"on": standard, "off": standard} # guillemets : on/off nus = booléens en YAML
|
||||
shutter: {open: standard, close: standard}
|
||||
door: {open: complet, close: standard}
|
||||
machine: {wake: standard, lock: standard, shutdown: complet, reboot: complet} # étape 15b
|
||||
# « Confirmez-vous ? » puis « oui », dit avec le MÊME DOIGT que la demande : un autre doigt de la
|
||||
# même personne, le doigt d'une autre personne ou le bouton PTT annulent la demande.
|
||||
confirm: [door.open, machine.shutdown, machine.reboot]
|
||||
confirm_timeout_s: 15
|
||||
|
||||
# branche fingerprint, étape F2 : capteur d'empreinte R503. Chaque doigt enregistré dans le capteur
|
||||
# a un numéro (emplacement) ; ici, à qui il appartient. Une même personne peut avoir plusieurs doigts.
|
||||
# Les droits de chaque personne restent dans access.users, par nom.
|
||||
# Enregistrer un doigt : make finger-enroll NAME=Denis ; il affiche la ligne à ajouter ci-dessous.
|
||||
fingerprint:
|
||||
users: { 1: Denis } # ex. : {1: Denis, 2: Denis, 3: Jessica}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Inclus par config.yaml (clé include). Section : home.
|
||||
|
||||
# étape 11 : domotique. Commandes publiées sur <topic_prefix>/<pièce>/<appareil>/set ;
|
||||
# la carte exécute en plus celles de sa propre pièce (LED de démonstration).
|
||||
home:
|
||||
topic_prefix: home
|
||||
rooms: # nom tel qu'on le dit → complément dans les réponses
|
||||
salon: du salon
|
||||
cuisine: de la cuisine
|
||||
chambre: de la chambre
|
||||
salle de bain: de la salle de bain
|
||||
bureau: du bureau
|
||||
garage: du garage
|
||||
entrée: de l'entrée
|
||||
boards: # pièce de chaque carte : « allume la lumière » sans pièce = ici
|
||||
esp32-01: salon
|
||||
@@ -0,0 +1,23 @@
|
||||
# Inclus par config.yaml (clé include). Section : machines.
|
||||
|
||||
# étape 15b : machines Linux du réseau. Chacune fait tourner un agent (agent/voice_agent.py)
|
||||
# qui n'exécute QUE les actions de SA liste (/etc/voice-assistant/agent.yaml) ; ici, on dit
|
||||
# seulement comment on les appelle. « allume » = Wake-on-LAN, envoyé par le serveur
|
||||
# (la machine éteinte n'a pas d'agent). Nouvelle action : l'ajouter à l'agent, ici
|
||||
# (mots et phrases), puis dans access.rules.machine (sinon : niveau complet exigé).
|
||||
machines:
|
||||
topic_prefix: agent # agent/<machine>/state (retenu), command, result
|
||||
broadcast: 255.255.255.255 # Wake-on-LAN : diffusion sur le réseau local
|
||||
actions: # mots sans accents ; « does » et « verb » : phrases dites
|
||||
# Un mot par entrée, tel que Whisper l'écrit : « lock » devient souvent « Locke »,
|
||||
# « shutdown » devient « Shut down » (d'où « shut »).
|
||||
wake: {words: [allume, allumer, allumez, demarre, demarrer, reveille, reveiller], does: "J'allume", verb: allumer}
|
||||
shutdown: {words: [eteins, eteint, eteindre, eteignez, arrete, arreter, arretez, shutdown, shut], does: "J'éteins", verb: éteindre}
|
||||
reboot: {words: [redemarre, redemarrer, redemarrez, relance, relancer, reboot, reboote, rebooter], does: "Je redémarre", verb: redémarrer}
|
||||
lock: {words: [verrouille, verrouiller, verrouillez, lock, locke, locker, loque], does: "Je verrouille", verb: verrouiller}
|
||||
list: # identifiant de l'agent → comment on l'appelle
|
||||
pc-bureau:
|
||||
# Plusieurs mots : « bureau » seul est une pièce. « p c » : Whisper écrit parfois « P.C. ».
|
||||
names: [pc du bureau, p c du bureau, ordinateur du bureau]
|
||||
name: le PC du bureau
|
||||
mac: "" # ex. "aa:bb:cc:dd:ee:ff" (ip link) pour « allume le PC du bureau »
|
||||
+9
-61
@@ -3,6 +3,15 @@
|
||||
# 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).
|
||||
|
||||
# Étape F6 : les sections longues ou personnelles vivent dans server/conf/ et sont incluses ici.
|
||||
# Chemins relatifs à ce fichier ; motifs admis (« conf/machines/*.yaml » : un fichier par machine, triés par nom).
|
||||
# Les mappings s'additionnent (home.rooms peut venir de plusieurs fichiers) ; toute autre valeur définie
|
||||
# deux fois est une erreur qui nomme les deux fichiers. mqtt reste ici : le Makefile y lit mqtt.host.
|
||||
include:
|
||||
- conf/home.yaml # home : pièces et cartes (domotique)
|
||||
- conf/machines.yaml # machines : machines Linux du réseau et leurs actions
|
||||
- conf/access.yaml # access : droits par personne ; fingerprint : à qui appartient chaque doigt
|
||||
|
||||
audio:
|
||||
sample_rate: 16000 # Hz, identique dans tout le système
|
||||
bits: 16
|
||||
@@ -57,64 +66,3 @@ tts:
|
||||
voice: fr_FR-siwis-medium
|
||||
length_scale: 1.0 # > 1 : débit plus lent
|
||||
|
||||
# étape 11 : domotique. Commandes publiées sur <topic_prefix>/<pièce>/<appareil>/set ;
|
||||
# la carte exécute en plus celles de sa propre pièce (LED de démonstration).
|
||||
home:
|
||||
topic_prefix: home
|
||||
rooms: # nom tel qu'on le dit → complément dans les réponses
|
||||
salon: du salon
|
||||
cuisine: de la cuisine
|
||||
chambre: de la chambre
|
||||
salle de bain: de la salle de bain
|
||||
bureau: du bureau
|
||||
garage: du garage
|
||||
entrée: de l'entrée
|
||||
boards: # pièce de chaque carte : « allume la lumière » sans pièce = ici
|
||||
esp32-01: salon
|
||||
|
||||
# étape 14 : droits par personne. Depuis F4, la personne est celle dont le DOIGT a ouvert la session
|
||||
# (section fingerprint, plus bas) ; la voix n'identifie plus personne. Niveaux : complet > standard > limite.
|
||||
# Les noms se comparent sans tenir compte de la casse ni des accents (« denis » = « Denis »).
|
||||
access:
|
||||
unknown: limite # bouton PTT, ou doigt sans nom dans fingerprint.users : conversation seulement
|
||||
default: standard # personne nommée par un doigt, absente de users
|
||||
users: # nom de la personne → niveau ; le nom est celui de fingerprint.users
|
||||
Denis: complet
|
||||
rules: # niveau minimal par appareil et action ; absent = complet
|
||||
light: {"on": standard, "off": standard} # guillemets : on/off nus = booléens en YAML
|
||||
shutter: {open: standard, close: standard}
|
||||
door: {open: complet, close: standard}
|
||||
machine: {wake: standard, lock: standard, shutdown: complet, reboot: complet} # étape 15b
|
||||
# « Confirmez-vous ? » puis « oui », dit avec le MÊME DOIGT que la demande : un autre doigt de la
|
||||
# même personne, le doigt d'une autre personne ou le bouton PTT annulent la demande.
|
||||
confirm: [door.open, machine.shutdown, machine.reboot]
|
||||
confirm_timeout_s: 15
|
||||
|
||||
# étape 15b : machines Linux du réseau. Chacune fait tourner un agent (agent/voice_agent.py)
|
||||
# qui n'exécute QUE les actions de SA liste (/etc/voice-assistant/agent.yaml) ; ici, on dit
|
||||
# seulement comment on les appelle. « allume » = Wake-on-LAN, envoyé par le serveur
|
||||
# (la machine éteinte n'a pas d'agent). Nouvelle action : l'ajouter à l'agent, ici
|
||||
# (mots et phrases), puis dans access.rules.machine (sinon : niveau complet exigé).
|
||||
machines:
|
||||
topic_prefix: agent # agent/<machine>/state (retenu), command, result
|
||||
broadcast: 255.255.255.255 # Wake-on-LAN : diffusion sur le réseau local
|
||||
actions: # mots sans accents ; « does » et « verb » : phrases dites
|
||||
# Un mot par entrée, tel que Whisper l'écrit : « lock » devient souvent « Locke »,
|
||||
# « shutdown » devient « Shut down » (d'où « shut »).
|
||||
wake: {words: [allume, allumer, allumez, demarre, demarrer, reveille, reveiller], does: "J'allume", verb: allumer}
|
||||
shutdown: {words: [eteins, eteint, eteindre, eteignez, arrete, arreter, arretez, shutdown, shut], does: "J'éteins", verb: éteindre}
|
||||
reboot: {words: [redemarre, redemarrer, redemarrez, relance, relancer, reboot, reboote, rebooter], does: "Je redémarre", verb: redémarrer}
|
||||
lock: {words: [verrouille, verrouiller, verrouillez, lock, locke, locker, loque], does: "Je verrouille", verb: verrouiller}
|
||||
list: # identifiant de l'agent → comment on l'appelle
|
||||
pc-bureau:
|
||||
# Plusieurs mots : « bureau » seul est une pièce. « p c » : Whisper écrit parfois « P.C. ».
|
||||
names: [pc du bureau, p c du bureau, ordinateur du bureau]
|
||||
name: le PC du bureau
|
||||
mac: "" # ex. "aa:bb:cc:dd:ee:ff" (ip link) pour « allume le PC du bureau »
|
||||
|
||||
# branche fingerprint, étape F2 : capteur d'empreinte R503. Chaque doigt enregistré dans le capteur
|
||||
# a un numéro (emplacement) ; ici, à qui il appartient. Une même personne peut avoir plusieurs doigts.
|
||||
# Les droits de chaque personne restent dans access.users, par nom.
|
||||
# Enregistrer un doigt : make finger-enroll NAME=Denis ; il affiche la ligne à ajouter ci-dessous.
|
||||
fingerprint:
|
||||
users: { 1: Denis } # ex. : {1: Denis, 2: Denis, 3: Jessica}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Fixtures communes aux tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SERVER_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_copy(tmp_path: Path) -> Path:
|
||||
"""Copie de config.yaml et des fichiers qu'il inclut (server/conf) : modifiable sans toucher aux vrais.
|
||||
|
||||
Rend le chemin du config.yaml copié ; les fichiers inclus sont dans le dossier conf voisin.
|
||||
"""
|
||||
destination = tmp_path / "server"
|
||||
destination.mkdir()
|
||||
shutil.copy2(SERVER_DIR / "config.yaml", destination / "config.yaml")
|
||||
shutil.copytree(SERVER_DIR / "conf", destination / "conf")
|
||||
return destination / "config.yaml"
|
||||
@@ -168,13 +168,14 @@ def test_project_config_is_valid() -> None:
|
||||
assert not policy.check(DOOR_OPEN, "Pierre").allowed
|
||||
|
||||
|
||||
def test_yaml_boolean_keys_are_read_as_on_off(tmp_path: Path) -> None:
|
||||
def test_yaml_boolean_keys_are_read_as_on_off(config_copy: Path) -> None:
|
||||
"""« light: {on: standard} » sans guillemets : YAML lit True, le chargeur rend « on »."""
|
||||
text = (Path(__file__).resolve().parents[1] / "config.yaml").read_text(encoding="utf-8")
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"),
|
||||
access = config_copy.parent / "conf" / "access.yaml"
|
||||
text = access.read_text(encoding="utf-8")
|
||||
assert '{"on": standard, "off": standard}' in text
|
||||
access.write_text(text.replace('{"on": standard, "off": standard}', "{on: standard, off: standard}"),
|
||||
encoding="utf-8")
|
||||
assert load_settings(config).access.rules["light"] == {"on": "standard", "off": "standard"}
|
||||
assert load_settings(config_copy).access.rules["light"] == {"on": "standard", "off": "standard"}
|
||||
|
||||
|
||||
def test_unknown_rule_action_is_rejected() -> None:
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Étape F6 : config.yaml peut inclure d'autres fichiers (clé « include », motifs admis)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from voice_server.__main__ import main
|
||||
from voice_server.settings import read_config
|
||||
|
||||
SERVER_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def write(path: Path, text: str) -> Path:
|
||||
"""Écrit un fichier YAML de test (dossiers créés au besoin)."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(textwrap.dedent(text), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- cas simples
|
||||
|
||||
def test_without_include_the_file_is_read_as_is(tmp_path: Path) -> None:
|
||||
config = write(tmp_path / "config.yaml", "audio:\n sample_rate: 16000\n")
|
||||
assert read_config(config) == {"audio": {"sample_rate": 16000}}
|
||||
|
||||
|
||||
def test_empty_file_gives_nothing(tmp_path: Path) -> None:
|
||||
assert read_config(write(tmp_path / "config.yaml", "")) == {}
|
||||
|
||||
|
||||
def test_include_one_path_or_a_list(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home:\n topic_prefix: home\n")
|
||||
write(tmp_path / "b.yaml", "machines:\n topic_prefix: agent\n")
|
||||
one = write(tmp_path / "one.yaml", "include: a.yaml\naudio: {bits: 16}\n")
|
||||
many = write(tmp_path / "many.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
assert read_config(one) == {"audio": {"bits": 16}, "home": {"topic_prefix": "home"}}
|
||||
assert read_config(many) == {"home": {"topic_prefix": "home"}, "machines": {"topic_prefix": "agent"}}
|
||||
|
||||
|
||||
def test_paths_are_relative_to_the_including_file(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "home.yaml", "include: pieces/salon.yaml\nhome: {topic_prefix: home}\n")
|
||||
write(tmp_path / "conf" / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/home.yaml\n")
|
||||
assert read_config(config) == {"home": {"topic_prefix": "home", "rooms": {"salon": "du salon"}}}
|
||||
|
||||
|
||||
def test_absolute_path_is_accepted(tmp_path: Path) -> None:
|
||||
other = write(tmp_path / "ailleurs" / "x.yaml", "a: 1\n")
|
||||
config = write(tmp_path / "config.yaml", f"include: {other}\n")
|
||||
assert read_config(config) == {"a": 1}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- fusion
|
||||
|
||||
def test_mappings_add_up_across_files(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
write(tmp_path / "b.yaml", "home:\n rooms: {cuisine: de la cuisine}\n boards: {esp32-01: salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\nhome: {topic_prefix: home}\n")
|
||||
assert read_config(config) == {"home": {
|
||||
"topic_prefix": "home",
|
||||
"rooms": {"salon": "du salon", "cuisine": "de la cuisine"},
|
||||
"boards": {"esp32-01": "salon"},
|
||||
}}
|
||||
|
||||
|
||||
def test_numeric_keys_add_up_too(tmp_path: Path) -> None:
|
||||
"""fingerprint.users a des clés entières : deux fichiers peuvent nommer des doigts différents."""
|
||||
write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n")
|
||||
write(tmp_path / "b.yaml", "fingerprint:\n users: {2: Jessica}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
assert read_config(config)["fingerprint"]["users"] == {1: "Denis", 2: "Jessica"}
|
||||
|
||||
|
||||
def test_same_value_in_two_files_is_an_error_naming_both(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "a.yaml", "home:\n topic_prefix: home\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/a.yaml\nhome:\n topic_prefix: maison\n")
|
||||
with pytest.raises(ValueError, match=r"« home\.topic_prefix » est défini à la fois dans config\.yaml "
|
||||
r"et dans conf[/\\]a\.yaml"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_same_finger_in_two_files_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "fingerprint:\n users: {1: Denis}\n")
|
||||
write(tmp_path / "b.yaml", "fingerprint:\n users: {1: Jessica}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: [a.yaml, b.yaml]\n")
|
||||
with pytest.raises(ValueError, match=r"fingerprint\.users\.1 »"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_a_mapping_and_a_value_under_the_same_key_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "home: {rooms: {salon: du salon}}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\nhome:\n rooms: tous\n")
|
||||
with pytest.raises(ValueError, match=r"« home\.rooms » est défini à la fois"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_lists_are_never_concatenated(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "access:\n confirm: [door.open]\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\naccess:\n confirm: [machine.reboot]\n")
|
||||
with pytest.raises(ValueError, match=r"« access\.confirm » est défini à la fois"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- motifs
|
||||
|
||||
def test_pattern_loads_matching_files_sorted_by_name(tmp_path: Path) -> None:
|
||||
for name in ("cuisine", "salon", "bureau"):
|
||||
write(tmp_path / "pieces" / f"{name}.yaml", f"home:\n rooms: {{{name}: de la {name}}}\n")
|
||||
write(tmp_path / "pieces" / "notes.txt", "pas du YAML : { ignoré\n")
|
||||
config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\n")
|
||||
rooms = read_config(config)["home"]["rooms"]
|
||||
assert list(rooms) == ["bureau", "cuisine", "salon"]
|
||||
|
||||
|
||||
def test_recursive_pattern(tmp_path: Path) -> None:
|
||||
write(tmp_path / "machines" / "bureau" / "pc.yaml", "machines:\n list: {pc-bureau: {name: le PC}}\n")
|
||||
write(tmp_path / "machines" / "nas.yaml", "machines:\n list: {nas: {name: le NAS}}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: 'machines/**/*.yaml'\n")
|
||||
assert sorted(read_config(config)["machines"]["list"]) == ["nas", "pc-bureau"]
|
||||
|
||||
|
||||
def test_pattern_without_match_warns_but_is_not_an_error(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
||||
config = write(tmp_path / "config.yaml", "include: 'pieces/*.yaml'\naudio: {bits: 16}\n")
|
||||
with caplog.at_level(logging.WARNING, logger="voice_server.settings"):
|
||||
assert read_config(config) == {"audio": {"bits": 16}}
|
||||
assert "pieces/*.yaml" in caplog.text
|
||||
|
||||
|
||||
def test_overlapping_patterns_read_a_file_once(tmp_path: Path) -> None:
|
||||
write(tmp_path / "pieces" / "salon.yaml", "home:\n rooms: {salon: du salon}\n")
|
||||
config = write(tmp_path / "config.yaml", "include: ['pieces/*.yaml', 'pieces/salon.yaml']\n")
|
||||
assert read_config(config) == {"home": {"rooms": {"salon": "du salon"}}}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- erreurs
|
||||
|
||||
def test_missing_file_is_an_error(tmp_path: Path) -> None:
|
||||
config = write(tmp_path / "config.yaml", "include: conf/absent.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"fichier introuvable : conf[/\\]absent\.yaml"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_include_loop_is_an_error(tmp_path: Path) -> None:
|
||||
write(tmp_path / "a.yaml", "include: b.yaml\n")
|
||||
write(tmp_path / "b.yaml", "include: a.yaml\n")
|
||||
config = write(tmp_path / "config.yaml", "include: a.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"boucle d'inclusion \(config\.yaml → a\.yaml → b\.yaml → a\.yaml\)"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_a_file_matching_its_own_pattern_is_a_loop(tmp_path: Path) -> None:
|
||||
write(tmp_path / "conf" / "all.yaml", "include: '*.yaml'\n")
|
||||
config = write(tmp_path / "config.yaml", "include: conf/all.yaml\n")
|
||||
with pytest.raises(ValueError, match="boucle d'inclusion"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_too_many_levels_is_an_error(tmp_path: Path) -> None:
|
||||
for number in range(12):
|
||||
write(tmp_path / f"f{number}.yaml", f"include: f{number + 1}.yaml\n")
|
||||
write(tmp_path / "f12.yaml", "a: 1\n")
|
||||
with pytest.raises(ValueError, match="plus de 8 niveaux"):
|
||||
read_config(tmp_path / "f0.yaml")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["3", "{a: b}", "[1, 2]", "['']"])
|
||||
def test_include_must_be_a_path_or_a_list_of_paths(tmp_path: Path, value: str) -> None:
|
||||
config = write(tmp_path / "config.yaml", f"include: {value}\n")
|
||||
with pytest.raises(ValueError, match="« include » doit être un chemin ou une liste de chemins"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
def test_included_file_must_be_a_mapping(tmp_path: Path) -> None:
|
||||
write(tmp_path / "liste.yaml", "- a\n- b\n")
|
||||
config = write(tmp_path / "config.yaml", "include: liste.yaml\n")
|
||||
with pytest.raises(ValueError, match=r"liste\.yaml : un mapping YAML est attendu"):
|
||||
read_config(config)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- le config.yaml du dépôt
|
||||
|
||||
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."""
|
||||
config = read_config(SERVER_DIR / "config.yaml")
|
||||
assert "include" not in config
|
||||
for section in ("audio", "mqtt", "stt", "home", "machines", "access", "fingerprint"):
|
||||
assert section in config, section
|
||||
raw = (SERVER_DIR / "config.yaml").read_text(encoding="utf-8")
|
||||
for moved in ("home", "machines", "access", "fingerprint"):
|
||||
assert f"\n{moved}:" not in raw, f"{moved} devrait vivre dans conf/"
|
||||
|
||||
|
||||
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."""
|
||||
inside = False
|
||||
host = ""
|
||||
for line in (SERVER_DIR / "config.yaml").read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("mqtt:"):
|
||||
inside = True
|
||||
continue
|
||||
if inside and line.split()[:1] == ["host:"]:
|
||||
host = line.split()[1]
|
||||
break
|
||||
assert host
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- démarrage du serveur
|
||||
|
||||
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
|
||||
error = capsys.readouterr().err
|
||||
assert "configuration invalide" in error
|
||||
assert "« access.default » est défini à la fois dans" in error
|
||||
assert "config.yaml" in error and "access.yaml" in error
|
||||
|
||||
|
||||
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 "fichier introuvable" in capsys.readouterr().err
|
||||
@@ -69,21 +69,22 @@ def test_project_config_loads() -> None:
|
||||
assert all(isinstance(number, int) and number >= 0 and name for number, name in users.items())
|
||||
|
||||
|
||||
def config_with_fingerprint(tmp_path: Path, section: str) -> Path:
|
||||
"""Copie de config.yaml dont la section fingerprint est remplacée (indépendant des doigts de l'utilisateur)."""
|
||||
text = CONFIG.read_text(encoding="utf-8")
|
||||
path = tmp_path / "config.yaml"
|
||||
path.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8")
|
||||
return path
|
||||
def config_with_fingerprint(config: Path, section: str) -> Path:
|
||||
"""config.yaml copié dont la section fingerprint (conf/access.yaml) est remplacée : indépendant des doigts
|
||||
de l'utilisateur."""
|
||||
access = config.parent / "conf" / "access.yaml"
|
||||
text = access.read_text(encoding="utf-8")
|
||||
access.write_text(text[: text.index("\nfingerprint:")] + "\nfingerprint:\n" + section, encoding="utf-8")
|
||||
return config
|
||||
|
||||
|
||||
def test_config_validation(tmp_path: Path) -> None:
|
||||
good = config_with_fingerprint(tmp_path, " users: {1: Denis, 2: Denis}\n")
|
||||
def test_config_validation(config_copy: Path) -> None:
|
||||
good = config_with_fingerprint(config_copy, " users: {1: Denis, 2: Denis}\n")
|
||||
assert load_settings(good).fingerprint.users == {1: "Denis", 2: "Denis"}
|
||||
assert load_settings(config_with_fingerprint(tmp_path, " users: {}\n")).fingerprint.users == {}
|
||||
assert load_settings(config_with_fingerprint(config_copy, " users: {}\n")).fingerprint.users == {}
|
||||
for wrong in ("{abc: Denis}", "{-1: Denis}", "{1: ''}"):
|
||||
with pytest.raises(ValueError, match="fingerprint.users"):
|
||||
load_settings(config_with_fingerprint(tmp_path, f" users: {wrong}\n"))
|
||||
load_settings(config_with_fingerprint(config_copy, f" users: {wrong}\n"))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- phrases
|
||||
@@ -131,7 +132,7 @@ def test_enroll_picks_the_free_slot_and_prints_the_config_line(caplog: pytest.Lo
|
||||
("done", None))})
|
||||
assert command_enroll(board, BOOK, "Marie", None) == 0
|
||||
assert board.sent[1] == {"cmd": "fp_enroll", "id": 4} # 1, 2, 5 nommés, 3 occupé
|
||||
assert "A ajouter dans server/config.yaml" in caplog.text and "4: Marie" in caplog.text
|
||||
assert "A ajouter dans server/conf/access.yaml" in caplog.text and "4: Marie" in caplog.text
|
||||
|
||||
|
||||
def test_enroll_reuses_a_slot_already_named_for_that_person_but_empty(caplog: pytest.LogCaptureFixture) -> None:
|
||||
|
||||
@@ -61,9 +61,9 @@ def test_log_file_receives_the_journal(tmp_path: Path, restore_logging: None) ->
|
||||
assert "essai du journal" in settings.log_file.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_log_file_is_optional(tmp_path: Path) -> None:
|
||||
text = CONFIG.read_text(encoding="utf-8").replace("file: logs/voice-server.log", "file:")
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(text, encoding="utf-8")
|
||||
assert load_settings(config).log_file is None
|
||||
def test_log_file_is_optional(config_copy: Path) -> None:
|
||||
text = config_copy.read_text(encoding="utf-8")
|
||||
assert "file: logs/voice-server.log" in text
|
||||
config_copy.write_text(text.replace("file: logs/voice-server.log", "file:"), encoding="utf-8")
|
||||
assert load_settings(config_copy).log_file is None
|
||||
assert load_settings(CONFIG).log_file == (CONFIG.parent / "logs" / "voice-server.log").resolve()
|
||||
|
||||
@@ -29,6 +29,8 @@ import threading
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from voice_server.audio_resampler import AudioResampler
|
||||
from voice_server.audio_sender import AudioSender
|
||||
from voice_server.fingerprint_book import FingerprintBook
|
||||
@@ -105,7 +107,7 @@ def make_assistant(settings: Settings, resampler: AudioResampler, sender: AudioS
|
||||
# États retenus des agents : reçus dès l'abonnement, même démarrés avant le serveur.
|
||||
link.on_topic(f"{settings.machines.topic_prefix}/+/state", machines.on_state)
|
||||
link.on_topic(f"{settings.machines.topic_prefix}/+/result", machines.on_result)
|
||||
logger.info("machines : %s", ", ".join(settings.machines.machines) or "aucune (config.yaml)")
|
||||
logger.info("machines : %s", ", ".join(settings.machines.machines) or "aucune (section machines)")
|
||||
|
||||
fingers = FingerprintBook(settings.fingerprint)
|
||||
policy = AccessPolicy(settings.access, settings.home, settings.machines)
|
||||
@@ -148,7 +150,12 @@ def main(argv: list[str]) -> int:
|
||||
help="renvoie chaque session a la carte, qui la joue (etape 5), sans modeles")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
settings = load_settings(args.config)
|
||||
try:
|
||||
settings = load_settings(args.config)
|
||||
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
|
||||
setup_logging(settings)
|
||||
logging.getLogger("faster_whisper").setLevel(logging.WARNING) # une ligne par transcription sinon
|
||||
logger.info("enregistrements dans %s", settings.recordings_dir)
|
||||
|
||||
@@ -114,7 +114,7 @@ class AccessPolicy:
|
||||
# Une règle mal écrite serait ignorée en silence (action exigeant alors « complet »).
|
||||
unknown = [f"{device}.{action}" for action in actions if action not in allowed.get(device, ())]
|
||||
if unknown:
|
||||
raise ValueError(f"config.yaml, access.rules : action inconnue {', '.join(unknown)} "
|
||||
raise ValueError(f"configuration, access.rules : action inconnue {', '.join(unknown)} "
|
||||
f"(connues : {', '.join(f'{d}.{a}' for d, acts in allowed.items() for a in acts)})")
|
||||
self._pending: dict[str, _Pending] = {}
|
||||
|
||||
|
||||
@@ -183,7 +183,7 @@ class MachineController:
|
||||
if previous == status:
|
||||
return
|
||||
if machine not in self._settings.machines:
|
||||
logger.warning("agent %s : absent de config.yaml (machines.list), on ne peut pas le nommer", machine)
|
||||
logger.warning("agent %s : absent de la configuration (machines.list), on ne peut pas le nommer", machine)
|
||||
elif status.online:
|
||||
unknown = [action for action in status.actions if action not in self._settings.actions]
|
||||
logger.info("agent %s : en ligne, actions %s%s", machine, ", ".join(status.actions) or "aucune",
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
@@ -12,6 +14,8 @@ from dotenv import load_dotenv
|
||||
|
||||
from voice_server.text_normalize import normalize
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AudioSettings:
|
||||
@@ -154,7 +158,7 @@ def _section(data: dict[str, Any], name: str) -> dict[str, Any]:
|
||||
"""Rend une section du YAML, avec une erreur claire si elle manque."""
|
||||
value = data.get(name)
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f"config.yaml : section « {name} » absente ou invalide")
|
||||
raise ValueError(f"configuration : section « {name} » absente ou invalide")
|
||||
return value # type: ignore[return-value]
|
||||
|
||||
|
||||
@@ -200,17 +204,106 @@ def _fingerprint(data: dict[str, Any]) -> FingerprintSettings:
|
||||
try:
|
||||
number = int(finger_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"config.yaml, fingerprint.users : « {finger_id} » n'est pas un numero d'empreinte") from None
|
||||
raise ValueError(f"configuration, fingerprint.users : « {finger_id} » n'est pas un numero d'empreinte") from None
|
||||
if number < 0 or not str(name).strip():
|
||||
raise ValueError(f"config.yaml, fingerprint.users : empreinte {finger_id} : numero >= 0 et nom non vide requis")
|
||||
raise ValueError(f"configuration, fingerprint.users : empreinte {finger_id} : numero >= 0 et nom non vide requis")
|
||||
users[number] = str(name).strip()
|
||||
return FingerprintSettings(users=users)
|
||||
|
||||
|
||||
class _ConfigReader:
|
||||
"""Lit config.yaml et les fichiers de sa clé « include », et les réunit en un seul dictionnaire.
|
||||
|
||||
Règles (volontairement simples, pour qu'un fichier de plus ne change jamais en silence une valeur) :
|
||||
- les mappings s'additionnent : « home.rooms » peut venir de plusieurs fichiers ;
|
||||
- toute autre valeur (texte, nombre, liste) définie dans deux fichiers est une erreur qui les nomme ;
|
||||
- « include » est un chemin ou une liste de chemins, relatifs au fichier qui les inclut ; les motifs
|
||||
(« conf/machines/*.yaml », « ** ») sont admis, triés par nom ; un fichier peut en inclure d'autres.
|
||||
"""
|
||||
|
||||
MAX_DEPTH = 8
|
||||
|
||||
def __init__(self, root: Path) -> None:
|
||||
self._root = root
|
||||
self.merged: dict[str, Any] = {}
|
||||
self._origins: dict[tuple[str, ...], Path] = {} # clé → fichier qui l'a définie
|
||||
self._loaded: set[Path] = set()
|
||||
|
||||
def _name(self, path: Path) -> str:
|
||||
"""Nom court d'un fichier : relatif au dossier de config.yaml quand c'est possible."""
|
||||
try:
|
||||
return str(path.relative_to(self._root))
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
def _expand(self, base: Path, pattern: str) -> list[Path]:
|
||||
"""Fichiers désignés par un élément d'« include » ; un chemin sans motif doit exister."""
|
||||
candidate = Path(pattern)
|
||||
full = candidate if candidate.is_absolute() else base / candidate
|
||||
if not any(char in pattern for char in "*?["):
|
||||
if not full.is_file():
|
||||
raise ValueError(f"include : fichier introuvable : {self._name(full)}")
|
||||
return [full.resolve()]
|
||||
found = sorted(Path(name).resolve() for name in glob.glob(str(full), recursive=True) if Path(name).is_file())
|
||||
if not found:
|
||||
logger.warning("include : le motif %s ne désigne aucun fichier", pattern)
|
||||
return found
|
||||
|
||||
def _merge(self, target: dict[Any, Any], source: dict[Any, Any], origin: Path, prefix: tuple[str, ...]) -> None:
|
||||
for key, value in source.items():
|
||||
where = (*prefix, _key(key))
|
||||
if key in target:
|
||||
first = self._origins[where]
|
||||
if not (isinstance(value, dict) and isinstance(target[key], dict)):
|
||||
raise ValueError(f"« {'.'.join(where)} » est défini à la fois dans {self._name(first)} "
|
||||
f"et dans {self._name(origin)}")
|
||||
elif isinstance(value, dict):
|
||||
target[key] = {}
|
||||
self._origins[where] = origin
|
||||
else:
|
||||
target[key] = value
|
||||
self._origins[where] = origin
|
||||
continue
|
||||
self._merge(target[key], value, origin, where)
|
||||
|
||||
def load(self, path: Path, chain: tuple[Path, ...] = ()) -> None:
|
||||
resolved = path.resolve()
|
||||
if resolved in chain:
|
||||
loop = " → ".join(self._name(item) for item in (*chain, resolved))
|
||||
raise ValueError(f"include : boucle d'inclusion ({loop})")
|
||||
if len(chain) >= self.MAX_DEPTH:
|
||||
raise ValueError(f"include : plus de {self.MAX_DEPTH} niveaux d'inclusion à partir de {self._name(resolved)}")
|
||||
if resolved in self._loaded: # deux motifs qui se recouvrent : un fichier n'est lu qu'une fois
|
||||
return
|
||||
self._loaded.add(resolved)
|
||||
|
||||
with resolved.open(encoding="utf-8") as stream:
|
||||
data = yaml.safe_load(stream)
|
||||
if data is None:
|
||||
data = {}
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError(f"{self._name(resolved)} : un mapping YAML est attendu à la racine du fichier")
|
||||
raw = data.pop("include", None)
|
||||
patterns = [raw] if isinstance(raw, str) else ([] if raw is None else raw)
|
||||
if not isinstance(patterns, list) or not all(isinstance(item, str) and item for item in patterns):
|
||||
raise ValueError(f"{self._name(resolved)} : « include » doit être un chemin ou une liste de chemins")
|
||||
|
||||
self._merge(self.merged, data, resolved, ())
|
||||
for pattern in patterns:
|
||||
for included in self._expand(resolved.parent, pattern):
|
||||
self.load(included, (*chain, resolved))
|
||||
|
||||
|
||||
def read_config(path: Path) -> dict[str, Any]:
|
||||
"""Lit config.yaml et ses fichiers inclus (clé « include », motifs admis) : un seul dictionnaire."""
|
||||
reader = _ConfigReader(path.resolve().parent)
|
||||
reader.load(path)
|
||||
return reader.merged
|
||||
|
||||
|
||||
def load_settings(path: Path) -> Settings:
|
||||
"""Lit config.yaml, puis le .env voisin s'il existe (identifiants MQTT)."""
|
||||
with path.open(encoding="utf-8") as stream:
|
||||
data: dict[str, Any] = yaml.safe_load(stream) or {}
|
||||
"""Lit config.yaml (et les fichiers qu'il inclut), puis le .env voisin s'il existe (identifiants MQTT)."""
|
||||
data = read_config(path)
|
||||
|
||||
# Les secrets ne sont jamais dans config.yaml : ils viennent de l'environnement.
|
||||
load_dotenv(path.parent / ".env")
|
||||
|
||||
Reference in New Issue
Block a user