Rework sound effects and add pre-generated Piper narration

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 12:29:51 +02:00
parent 61eccb2f80
commit 7050cb1ac6
60 changed files with 918 additions and 83 deletions
+2
View File
@@ -15,6 +15,8 @@ backend/db.sqlite3
backend/**/*.mo backend/**/*.mo
backend/staticfiles/ backend/staticfiles/
backend/.venv/ backend/.venv/
.venv-voice/
.cache/
backend/venv/ backend/venv/
# Environnement virtuel Python de développement # Environnement virtuel Python de développement
+5 -4
View File
@@ -71,13 +71,14 @@ Commandes : `make test` (JS `node:test`, Python `unittest`, backend Django, vali
niveaux), `make test-e2e` (Chromium), `make typecheck` (pyright), `make dev`, `make build`. niveaux), `make test-e2e` (Chromium), `make typecheck` (pyright), `make dev`, `make build`.
Pyodide épinglé 314.0.7 (Python 3.14.2) via `make vendor-pyodide`. Pyodide épinglé 314.0.7 (Python 3.14.2) via `make vendor-pyodide`.
**À traiter en premier à la reprise** : améliorer le son (jugé « inaudible et de mauvaise **À traiter en premier à la reprise** : recueillir le retour d'écoute de l'utilisateur sur les
qualité » par l'utilisateur) — pistes dans CONTEXT.md ; puis niveaux 04 et suivants. nouveaux effets sonores et la voix Piper (retour initial : « inaudible et de mauvaise qualité »),
ajuster si besoin (voir CONTEXT.md) ; puis niveaux 04 et suivants.
## Règles de travail apprises ## Règles de travail apprises
- Chaque niveau ajouté : `fr` **et** `en`, `make validate-levels`, entrée dans - Chaque niveau ajouté : `fr` **et** `en`, `make validate-levels`, `make voice` si des étapes ont
`levels/manifest.json`, parcours e2e si le niveau introduit un comportement nouveau. `voice: true` (commiter les mp3), entrée dans `levels/manifest.json`, parcours e2e si le niveau introduit un comportement nouveau.
- Tester dans un vrai navigateur dès qu'un comportement dépend d'API navigateur : des écarts - Tester dans un vrai navigateur dès qu'un comportement dépend d'API navigateur : des écarts
Node/Chromium (ex. `encodeInto` sur `SharedArrayBuffer`) ne se voient qu'ainsi. Node/Chromium (ex. `encodeInto` sur `SharedArrayBuffer`) ne se voient qu'ainsi.
- Les commits sont autorisés « quand nécessaire » : un commit par composant cohérent, message en - Les commits sont autorisés « quand nécessaire » : un commit par composant cohérent, message en
+25 -16
View File
@@ -1,6 +1,6 @@
# Contexte de session — à lire en premier en reprenant ce projet # Contexte de session — à lire en premier en reprenant ce projet
Dernière mise à jour : 2026-10-14 (fin de session). Dernier commit de travail : voir `git log`. Dernière mise à jour : 2026-10-16. Dernier commit de travail : voir `git log`.
## Où on en est ## Où on en est
@@ -29,7 +29,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
| Validation | `app/js/core/ValidationEngine.js` (kinds déclaratifs), rejeux à `inputs` dans `app/js/ui/CellManager.js` | | Validation | `app/js/core/ValidationEngine.js` (kinds déclaratifs), rejeux à `inputs` dans `app/js/ui/CellManager.js` |
| Erreurs | `app/js/core/ErrorTranslator.js` + `app/js/i18n/errors.{fr,en}.json` | | Erreurs | `app/js/core/ErrorTranslator.js` + `app/js/i18n/errors.{fr,en}.json` |
| Progression | `app/js/core/ProgressStore.js`, `KeyValueStores.js` (IndexedDB/mémoire), `SettingsStore.js` | | Progression | `app/js/core/ProgressStore.js`, `KeyValueStores.js` (IndexedDB/mémoire), `SettingsStore.js` |
| Audio / voix | `app/js/core/AudioEngine.js` (sons synthétisés), `VoiceEngine.js` (speechSynthesis) | | Audio / voix | `app/js/core/AudioEngine.js` (sons synthétisés), `VoiceEngine.js` (mp3 Piper + repli speechSynthesis), `speechKey.js` ; `scripts/generate_voice.py`, `voice_key.py` |
| UI | `app/js/ui/` (CellView, CellManager, NotebookView, HintPanel, ProgressMap, BadgeToast, SettingsPanel, dom.js), `app/js/i18n/{i18n.js,fr.json,en.json}`, `app/css/app.css` | | UI | `app/js/ui/` (CellView, CellManager, NotebookView, HintPanel, ProgressMap, BadgeToast, SettingsPanel, dom.js), `app/js/i18n/{i18n.js,fr.json,en.json}`, `app/css/app.css` |
| Shell PWA | `app/index.html`, `app/js/main.js`, `app/service-worker.js`, `app/manifest.webmanifest` | | Shell PWA | `app/index.html`, `app/js/main.js`, `app/service-worker.js`, `app/manifest.webmanifest` |
| Tooling | `Makefile`, `scripts/{dev_server,validate_levels,build}.py`, `scripts/vendor_pyodide.sh` | | Tooling | `Makefile`, `scripts/{dev_server,validate_levels,build}.py`, `scripts/vendor_pyodide.sh` |
@@ -45,7 +45,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
des saisies scriptées (rejeu isolé). des saisies scriptées (rejeu isolé).
- `input()` **réel** (option b) : worker bloqué par `Atomics.wait`, champ de saisie dans la - `input()` **réel** (option b) : worker bloqué par `Atomics.wait`, champ de saisie dans la
cellule, l'invite va dans stdout, pas la réponse. Sans isolation : `EOFError`. cellule, l'invite va dans stdout, pas la réponse. Sans isolation : `EOFError`.
- Sons **synthétisés** (Web Audio), pas de fichiers mp3. - Effets sonores **synthétisés** (Web Audio) ; narration = mp3 **pré-générés** avec Piper (build).
- YAML lu côté navigateur par js-yaml 4.3.2 vendorisé. - YAML lu côté navigateur par js-yaml 4.3.2 vendorisé.
- Tests JS : **`node:test`** sans dépendance ; e2e : `playwright-core` + Chromium système. - Tests JS : **`node:test`** sans dépendance ; e2e : `playwright-core` + Chromium système.
- Synchronisation : jeton aléatoire côté client, sans compte ; fusion côté client - Synchronisation : jeton aléatoire côté client, sans compte ; fusion côté client
@@ -55,18 +55,25 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
## À faire — priorités pour la prochaine session ## À faire — priorités pour la prochaine session
1. **🔊 Améliorer le son (retour utilisateur : « inaudible et de mauvaise qualité »).** 1. **🔊 Son : traité le 2026-10-16, à valider à l'oreille par l'utilisateur.**
Constat : `AudioEngine` synthétise les sons (oscillateurs). Pistes à traiter, à *écouter sur - *Effets* : `AudioEngine` réécrit (synthèse additive en carillon, enveloppe exponentielle,
un vrai appareil* (impossible à valider en test automatique) : gain maître + compresseur). Mesures automatiques (`tests/e2e/audio.test.mjs`) : crête
- niveau trop bas : crête = `BASE_GAIN (0.15) × volume (0.8) ≈ 0.12`, notes de 0,1–0,5 s ; −3 à −5 dBFS, niveau efficace ≈ −19 dBFS pour les 4 sons (≈ +13 dB de crête par rapport à
monter nettement le gain, ajouter un `GainNode` maître + `DynamicsCompressorNode` ; l'ancien, estimé : l'ancien plafonnait à ≈ −18 dBFS). `AUDIO_DUMP_DIR=/tmp/fx make test-e2e`
- timbre : `square`/`sawtooth` agressifs et pauvres ; préférer sinus/triangle + harmoniques, écrit les .wav pour les écouter. Bouton « Tester le son » dans les réglages.
enveloppe ADSR avec `exponentialRampToValueAtTime`, éventuellement filtre passe-bas ; - *Voix* : narration **pré-générée avec Piper** (`make voice`) : mp3 mono 48 kbit/s normalisés
- vérifier que le contexte est bien `running` au moment du `play()` (déblocage `unlock()` au à −18 LUFS, voix `fr_FR-siwis-medium` (CC BY 4.0) et `en_US-ljspeech-high` (domaine public),
premier clic ; contrôler iOS) et que le volume des réglages (0–1) est appliqué ; débit ×1,1 ; fichiers dans `levels/<id>/audio/<lang>/<clé>.mp3` (+ échantillon réglages dans
- alternative : échantillons audio courts libres de droits (CC0) vendorisés dans `app/assets/voice/`). Clé = FNV-1a 64 du texte lu (`scripts/voice_key.py` ↔
`app/assets/sounds/` (compatible licence, cache service worker à prévoir) ; `app/js/core/speechKey.js`, vecteurs de test communs). `VoiceEngine` lit le fichier (via blob,
- ajouter un bouton « tester le son » dans `SettingsPanel` pour régler/valider rapidement. compatible iOS) et se replie sur `speechSynthesis` s'il manque. Crédits/licences :
`levels/AUDIO-CREDITS.md`. `make check-voice` (dans `make test`) détecte un fichier manquant.
- **À faire** : l'utilisateur doit écouter effets et voix (la qualité perçue ne se mesure pas) ;
ajuster gain/timbre (`NOTE_PEAK`, `BELL`, compresseur) ou voix/débit (`VOICES`, `LENGTH_SCALE`
dans `scripts/generate_voice.py`) selon son retour. La voix est **désactivée par défaut**
(réglage « Voix ») : à reconsidérer. Piper = GPL-3.0 mais outil de build seulement.
- Whisper (dictée) et pyannote (diarisation) : écartés (hors besoin ; pyannote = modèles à accès
restreint). Whisper reste une option d'accessibilité lointaine (dicter une réponse à `input()`).
2. **Niveaux 04 à 14** (tableau dans `docs/design/05-curriculum.md`). Méthode : écrire le YAML 2. **Niveaux 04 à 14** (tableau dans `docs/design/05-curriculum.md`). Méthode : écrire le YAML
(fr + en obligatoires), `make validate-levels`, ajouter au manifeste, parcours e2e. Prochain : (fr + en obligatoires), `make validate-levels`, ajouter au manifeste, parcours e2e. Prochain :
**04 Calculer** (opérateurs, `%`, priorités ; mission convertisseur d'unités). **04 Calculer** (opérateurs, `%`, priorités ; mission convertisseur d'unités).
@@ -87,7 +94,8 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
```bash ```bash
git log --oneline | head # où on en est git log --oneline | head # où on en est
make install # venv .venv + Pyodide (déjà vendorisé = no-op) make install # venv .venv + Pyodide (déjà vendorisé = no-op)
make test # JS + Python + backend + validation des niveaux make test # JS + Python + backend + niveaux + narration à jour
make voice # (re)génère la narration (venv .venv-voice, ffmpeg requis)
make test-e2e # parcours Chromium (CHROMIUM=/usr/bin/chromium par défaut) make test-e2e # parcours Chromium (CHROMIUM=/usr/bin/chromium par défaut)
make typecheck # pyright (backend inclus) make typecheck # pyright (backend inclus)
make dev # http://127.0.0.1:8000/ make dev # http://127.0.0.1:8000/
@@ -110,6 +118,7 @@ Contrôle d'un son/UI à la main : `make dev` puis ouvrir l'URL dans un navigate
avec le bouton « Envoyer » de la saisie). avec le bouton « Envoyer » de la saisie).
- Messages d'erreur Python : validés sur Python 3.14.2 (Pyodide) ; à recontrôler si la version - Messages d'erreur Python : validés sur Python 3.14.2 (Pyodide) ; à recontrôler si la version
de Pyodide change (`tests/js/error-translator.test.mjs` utilise le `python3` du poste). de Pyodide change (`tests/js/error-translator.test.mjs` utilise le `python3` du poste).
- Après tout ajout/modification d'un texte `explain` avec `voice: true` : `make voice` puis commit des mp3.
- Ne pas lancer de `pkill -f` large : il peut tuer le shell de l'outil. - Ne pas lancer de `pkill -f` large : il peut tuer le shell de l'outil.
## Git ## Git
+10 -1
View File
@@ -49,6 +49,15 @@ Un niveau ne contient **jamais de code exécutable** autre que le code de dépar
affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur
(`app/js/core/ValidationEngine.js`), pas par un fichier de niveau. (`app/js/core/ValidationEngine.js`), pas par un fichier de niveau.
### Narration vocale
Une étape `explain` avec `voice: true` propose un bouton « Écouter ». La narration est un fichier
mp3 **pré-généré** avec Piper : après avoir ajouté ou modifié un texte narré, lancez `make voice`
(télécharge les voix au premier lancement, nécessite `ffmpeg`) et commitez les fichiers
`levels/<id>/audio/`. `make check-voice` (inclus dans `make test`) échoue si un fichier manque ou est
périmé. Sans fichier, l'application se rabat sur la voix du système. Voix et licences :
[levels/AUDIO-CREDITS.md](levels/AUDIO-CREDITS.md).
### Accessibilité ### Accessibilité
Aucune information ne doit passer uniquement par la couleur ou le son. Les images décoratives Aucune information ne doit passer uniquement par la couleur ou le son. Les images décoratives
@@ -73,7 +82,7 @@ ont un `alt` vide ; une illustration porteuse de sens doit être décrite dans l
tone, runnable `starter`, `tests`, graduated `hints`, `solution`, motivating `mission`). tone, runnable `starter`, `tests`, graduated `hints`, `solution`, motivating `mission`).
3. Provide both `fr` and `en` for every text. 3. Provide both `fr` and `en` for every text.
4. List the level in `levels/manifest.json`. 4. List the level in `levels/manifest.json`.
5. Run `make validate-levels`. 5. Run `make validate-levels`; for narrated steps (`voice: true`) run `make voice` and commit the generated `audio/` files (see `levels/AUDIO-CREDITS.md`).
Levels never contain executable code other than the starter and solution shown to the learner: Levels never contain executable code other than the starter and solution shown to the learner:
new kinds of validation are added to the engine, not to level files. new kinds of validation are added to the engine, not to level files.
+12 -4
View File
@@ -5,7 +5,7 @@ VENV := .venv
VENV_PY := $(VENV)/bin/python VENV_PY := $(VENV)/bin/python
PORT ?= 8000 PORT ?= 8000
.PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python test-backend test-e2e typecheck clean .PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python test-backend test-e2e typecheck voice check-voice clean
help: ## Affiche cette aide help: ## Affiche cette aide
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}' @grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
@@ -29,7 +29,7 @@ validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, t
build: $(VENV)/.installed ## Construit dist/ pour la production build: $(VENV)/.installed ## Construit dist/ pour la production
$(VENV_PY) scripts/build.py $(VENV_PY) scripts/build.py
test: test-js test-python test-backend validate-levels ## Lance tous les tests test: test-js test-python test-backend validate-levels check-voice ## Lance tous les tests
test-js: ## Tests JavaScript (node:test, aucune dépendance) test-js: ## Tests JavaScript (node:test, aucune dépendance)
node --test tests/js/*.test.mjs node --test tests/js/*.test.mjs
@@ -43,11 +43,19 @@ test-backend: $(VENV)/.installed ## Tests du backend Django (nécessite Django d
test-e2e: ## Tests bout en bout dans Chromium (CHROMIUM=/chemin/navigateur) test-e2e: ## Tests bout en bout dans Chromium (CHROMIUM=/chemin/navigateur)
npm --prefix tests/e2e install --silent npm --prefix tests/e2e install --silent
node --test tests/e2e/e2e.test.mjs node --test tests/e2e/*.test.mjs
typecheck: $(VENV)/.installed ## Vérifie les types Python avec pyright typecheck: $(VENV)/.installed ## Vérifie les types Python avec pyright
$(VENV)/bin/pyright $(VENV)/bin/pyright
voice: ## Génère la narration (Piper → mp3) pour les textes de niveaux ; voir levels/AUDIO-CREDITS.md
$(PYTHON) -m venv .venv-voice
.venv-voice/bin/pip install --quiet -r requirements-voice.txt
cd scripts && ../.venv-voice/bin/python generate_voice.py
check-voice: $(VENV)/.installed ## Vérifie que toute la narration est générée et à jour
cd scripts && ../$(VENV_PY) generate_voice.py --check
clean: ## Supprime dist/, caches et environnement virtuel clean: ## Supprime dist/, caches et environnement virtuel
rm -rf dist $(VENV) rm -rf dist $(VENV) .venv-voice
find . -name __pycache__ -type d -prune -exec rm -rf {} + find . -name __pycache__ -type d -prune -exec rm -rf {} +
+1 -1
View File
@@ -7,7 +7,7 @@ beginners and advanced learners alike.
a Web Worker: genuine error messages, translated into plain language. a Web Worker: genuine error messages, translated into plain language.
- Notebook-style cells, progressive hints, automatic exercise validation. - Notebook-style cells, progressive hints, automatic exercise validation.
- Declarative levels (YAML): adding a level requires no code change. - Declarative levels (YAML): adding a level requires no code change.
- XP, badges, daily streaks, optional sounds and voice, French/English interface. - XP, badges, daily streaks, optional sound effects and narration (pre-generated Piper voices), French/English interface.
- Accessibility target: WCAG 2.2 AA (full keyboard use, light/dark themes, adjustable text size). - Accessibility target: WCAG 2.2 AA (full keyboard use, light/dark themes, adjustable text size).
> Version française : [README.md](README.md) > Version française : [README.md](README.md)
+1 -1
View File
@@ -7,7 +7,7 @@ fonctionne hors ligne (PWA), pour les débutants comme pour les plus avancés.
Web Worker : les vrais messages d'erreur, traduits en langage simple. Web Worker : les vrais messages d'erreur, traduits en langage simple.
- Console à cellules façon notebook, indices progressifs, validation automatique des exercices. - Console à cellules façon notebook, indices progressifs, validation automatique des exercices.
- Niveaux déclaratifs (YAML) : ajouter un niveau ne demande aucune modification du code. - Niveaux déclaratifs (YAML) : ajouter un niveau ne demande aucune modification du code.
- XP, badges, séries de jours, sons et voix optionnels, interface fr/en. - XP, badges, séries de jours, effets sonores et narration vocale (voix Piper pré-générées) optionnels, interface fr/en.
- Accessibilité visée : WCAG 2.2 AA (clavier complet, thèmes clair/sombre, taille de texte réglable). - Accessibilité visée : WCAG 2.2 AA (clavier complet, thèmes clair/sombre, taille de texte réglable).
> English version: [README-EN.md](README-EN.md) > English version: [README-EN.md](README-EN.md)
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
{
"en": {
"23087e367ecc886e": {
"text": "Hello, I am the voice of PyQuest. This is how I will read the explanations.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"c4262bd49831c690": {
"text": "Bonjour, je suis la voix de PyQuest. Voici comment je lirai les explications.",
"voice": "fr_FR-siwis-medium"
}
}
}
+95 -34
View File
@@ -1,37 +1,61 @@
// Effets sonores courts via Web Audio API, synthétisés (aucun fichier audio à servir ni à licencier). // Effets sonores courts via Web Audio API, synthétisés (aucun fichier audio à servir ni à licencier).
// Toujours désactivable ; jamais déclenché avant un geste utilisateur (contrainte autoplay iOS). // Toujours désactivable ; jamais déclenché avant un geste utilisateur (contrainte autoplay iOS).
//
// Timbre : synthèse additive (fondamentale + 2 harmoniques, sinusoïdes) avec une attaque nette et
// une extinction exponentielle, pour un son de « carillon » doux plutôt que des ondes brutes.
// Niveau : un gain maître puis un compresseur ramènent tous les sons à un volume comparable et
// audible sans saturer (voir tests/e2e : mesure de crête et de niveau efficace).
// Chaque son est une suite de notes : fréquence (Hz), début et durée (s), forme d'onde. // Partiels d'un timbre : [multiple de la fréquence, amplitude relative].
const BELL = [
[1, 1],
[2, 0.35],
[3, 0.12],
];
const SOFT = [
[1, 1],
[2, 0.5],
];
// Chaque note : fréquence (Hz), début et durée (s), gain relatif (accords : < 1), timbre.
const SOUNDS = { const SOUNDS = {
success_small: [ success_small: [
{ frequency: 659.25, start: 0, duration: 0.12, type: 'sine' }, { frequency: 659.25, start: 0, duration: 0.3, gain: 0.9, timbre: BELL },
{ frequency: 880, start: 0.1, duration: 0.2, type: 'sine' }, { frequency: 880, start: 0.11, duration: 0.5, gain: 1, timbre: BELL },
], ],
success_big: [ success_big: [
{ frequency: 523.25, start: 0, duration: 0.12, type: 'triangle' }, { frequency: 523.25, start: 0, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 659.25, start: 0.12, duration: 0.12, type: 'triangle' }, { frequency: 659.25, start: 0.12, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 783.99, start: 0.24, duration: 0.12, type: 'triangle' }, { frequency: 783.99, start: 0.24, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 1046.5, start: 0.36, duration: 0.35, type: 'triangle' }, { frequency: 1046.5, start: 0.36, duration: 0.9, gain: 0.6, timbre: BELL },
{ frequency: 783.99, start: 0.36, duration: 0.9, gain: 0.5, timbre: BELL },
{ frequency: 523.25, start: 0.36, duration: 0.9, gain: 0.5, timbre: BELL },
], ],
level_unlocked: [ level_unlocked: [
{ frequency: 392, start: 0, duration: 0.15, type: 'square' }, { frequency: 392, start: 0, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 523.25, start: 0.15, duration: 0.15, type: 'square' }, { frequency: 523.25, start: 0.14, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 659.25, start: 0.3, duration: 0.15, type: 'square' }, { frequency: 659.25, start: 0.28, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 783.99, start: 0.45, duration: 0.15, type: 'square' }, { frequency: 783.99, start: 0.42, duration: 0.3, gain: 0.8, timbre: BELL },
{ frequency: 1046.5, start: 0.6, duration: 0.5, type: 'square' }, { frequency: 1046.5, start: 0.56, duration: 1.2, gain: 0.6, timbre: BELL },
{ frequency: 783.99, start: 0.56, duration: 1.2, gain: 0.45, timbre: BELL },
{ frequency: 659.25, start: 0.56, duration: 1.2, gain: 0.45, timbre: BELL },
], ],
error: [ error: [
{ frequency: 220, start: 0, duration: 0.18, type: 'sawtooth' }, { frequency: 293.66, start: 0, duration: 0.25, gain: 0.9, timbre: SOFT },
{ frequency: 174.61, start: 0.15, duration: 0.25, type: 'sawtooth' }, { frequency: 220, start: 0.16, duration: 0.45, gain: 1, timbre: SOFT },
], ],
}; };
// Les sons « square » et « sawtooth » sont agressifs : gain de base réduit. const ATTACK_S = 0.008;
const BASE_GAIN = 0.15; const SILENCE = 0.0001; // cible de l'extinction exponentielle (ne peut pas valoir 0)
// Niveau de crête d'une note de gain 1 avant compresseur : laisse de la marge aux accords.
const NOTE_PEAK = 0.45;
export class AudioEngine { export class AudioEngine {
#createContext; #createContext;
#context = null; #context = null;
#master = null;
#output = null;
#enabled; #enabled;
#volume; #volume;
@@ -56,6 +80,51 @@ export class AudioEngine {
return Object.keys(SOUNDS); return Object.keys(SOUNDS);
} }
/**
* Construit la chaîne de sortie (gain maître → compresseur → sortie) et renvoie ses nœuds.
* Exposé pour que les tests rendent les sons hors ligne avec exactement la même chaîne.
*/
static buildOutput(context, volume) {
const master = context.createGain();
master.gain.value = volume;
const compressor = context.createDynamicsCompressor();
compressor.threshold.value = -14;
compressor.knee.value = 10;
compressor.ratio.value = 6;
compressor.attack.value = 0.003;
compressor.release.value = 0.2;
master.connect(compressor).connect(context.destination);
return { input: master, master };
}
/**
* Programme les notes d'un son sur `destination`, à partir de `when`.
* @returns {number} durée totale en secondes (queue d'extinction comprise)
*/
static schedule(context, destination, name, when = context.currentTime) {
let end = 0;
for (const note of SOUNDS[name]) {
const noteStart = when + note.start;
const noteEnd = noteStart + note.duration;
const peak = NOTE_PEAK * note.gain;
for (const [multiple, amplitude] of note.timbre) {
const oscillator = context.createOscillator();
const gain = context.createGain();
oscillator.type = 'sine';
oscillator.frequency.value = note.frequency * multiple;
// Attaque courte (pas de clic), puis extinction exponentielle.
gain.gain.setValueAtTime(0, noteStart);
gain.gain.linearRampToValueAtTime(peak * amplitude, noteStart + ATTACK_S);
gain.gain.exponentialRampToValueAtTime(SILENCE, noteEnd);
oscillator.connect(gain).connect(destination);
oscillator.start(noteStart);
oscillator.stop(noteEnd + 0.02);
}
end = Math.max(end, note.start + note.duration + 0.02);
}
return end;
}
get enabled() { get enabled() {
return this.#enabled; return this.#enabled;
} }
@@ -75,6 +144,9 @@ export class AudioEngine {
setVolume(volume) { setVolume(volume) {
this.#volume = Math.min(1, Math.max(0, volume)); this.#volume = Math.min(1, Math.max(0, volume));
if (this.#master) {
this.#master.gain.value = this.#volume;
}
} }
/** /**
@@ -84,6 +156,11 @@ export class AudioEngine {
async unlock() { async unlock() {
if (!this.#context) { if (!this.#context) {
this.#context = this.#createContext(); this.#context = this.#createContext();
if (this.#context) {
const output = AudioEngine.buildOutput(this.#context, this.#volume);
this.#master = output.master;
this.#output = output.input;
}
} }
if (this.#context?.state === 'suspended') { if (this.#context?.state === 'suspended') {
await this.#context.resume(); await this.#context.resume();
@@ -96,26 +173,10 @@ export class AudioEngine {
* @returns {boolean} vrai si le son a été lancé * @returns {boolean} vrai si le son a été lancé
*/ */
play(name) { play(name) {
const notes = SOUNDS[name]; if (!this.#enabled || !this.#context || this.#context.state !== 'running' || !SOUNDS[name]) {
if (!this.#enabled || !this.#context || this.#context.state !== 'running' || !notes) {
return false; return false;
} }
const context = this.#context; AudioEngine.schedule(this.#context, this.#output, name);
const now = context.currentTime;
for (const note of notes) {
const oscillator = context.createOscillator();
const gain = context.createGain();
const peak = BASE_GAIN * this.#volume;
oscillator.type = note.type;
oscillator.frequency.value = note.frequency;
// Enveloppe courte pour éviter les clics de début et de fin.
gain.gain.setValueAtTime(0, now + note.start);
gain.gain.linearRampToValueAtTime(peak, now + note.start + 0.01);
gain.gain.linearRampToValueAtTime(0, now + note.start + note.duration);
oscillator.connect(gain).connect(context.destination);
oscillator.start(now + note.start);
oscillator.stop(now + note.start + note.duration + 0.02);
}
return true; return true;
} }
} }
+9
View File
@@ -1,5 +1,7 @@
// Parcours d'un niveau par l'apprenant : étapes localisées puis mission finale. // Parcours d'un niveau par l'apprenant : étapes localisées puis mission finale.
import { speechKey } from './speechKey.js';
export class LevelSession { export class LevelSession {
#level; #level;
#lang; #lang;
@@ -77,6 +79,11 @@ export class LevelSession {
return true; return true;
} }
#audioUrl(step) {
const lang = step.text[this.#lang] ? this.#lang : 'fr';
return new URL(`audio/${lang}/${speechKey(lang, step.text[lang])}.mp3`, this.#baseUrl).href;
}
#localize(value) { #localize(value) {
return value?.[this.#lang] ?? value?.fr ?? ''; return value?.[this.#lang] ?? value?.fr ?? '';
} }
@@ -95,6 +102,8 @@ export class LevelSession {
text: this.#localize(step.text), text: this.#localize(step.text),
voice: step.voice ?? false, voice: step.voice ?? false,
image: step.image ? new URL(step.image, this.#baseUrl).href : null, image: step.image ? new URL(step.image, this.#baseUrl).href : null,
// Narration pré-générée (make voice) ; absente = repli sur la voix du système.
audioUrl: step.voice ? this.#audioUrl(step) : null,
}; };
} }
return { return {
+106 -12
View File
@@ -1,13 +1,20 @@
// Narration vocale optionnelle via speechSynthesis (voix du système, aucun service tiers). // Narration vocale optionnelle, à appeler uniquement depuis un geste utilisateur (bouton « Écouter »).
// À appeler uniquement depuis un geste utilisateur (bouton « Écouter »), jamais automatiquement. // 1) fichier audio pré-généré avec Piper (make voice) : même qualité partout, hors ligne ;
// 2) repli : speechSynthesis (voix du système) si le fichier est absent ou illisible.
// Aucun service tiers.
const LANG_TAGS = { fr: 'fr-FR', en: 'en-US' }; const LANG_TAGS = { fr: 'fr-FR', en: 'en-US' };
export class VoiceEngine { export class VoiceEngine {
#synth; #synth;
#UtteranceClass; #UtteranceClass;
#AudioClass;
#fetch;
#enabled; #enabled;
#rate; #rate;
#audio = null;
#objectUrl = null;
#session = 0;
/** /**
* @param {object} [options] * @param {object} [options]
@@ -15,22 +22,28 @@ export class VoiceEngine {
* @param {number} [options.rate] Vitesse de 0.5 à 2 (1 = normale). * @param {number} [options.rate] Vitesse de 0.5 à 2 (1 = normale).
* @param {SpeechSynthesis|null} [options.synth] Remplaçable pour les tests. * @param {SpeechSynthesis|null} [options.synth] Remplaçable pour les tests.
* @param {typeof SpeechSynthesisUtterance} [options.Utterance] * @param {typeof SpeechSynthesisUtterance} [options.Utterance]
* @param {typeof Audio|undefined} [options.AudioClass]
* @param {typeof fetch} [options.fetchFn]
*/ */
constructor({ constructor({
enabled = true, enabled = true,
rate = 1, rate = 1,
synth = globalThis.speechSynthesis ?? null, synth = globalThis.speechSynthesis ?? null,
Utterance = globalThis.SpeechSynthesisUtterance, Utterance = globalThis.SpeechSynthesisUtterance,
AudioClass = globalThis.Audio,
fetchFn = (...args) => fetch(...args),
} = {}) { } = {}) {
this.#synth = synth; this.#synth = synth;
this.#UtteranceClass = Utterance; this.#UtteranceClass = Utterance;
this.#AudioClass = AudioClass;
this.#fetch = fetchFn;
this.#enabled = enabled; this.#enabled = enabled;
this.#rate = rate; this.#rate = rate;
} }
/** Faux sur les navigateurs sans speechSynthesis : l'UI masque alors le bouton. */ /** Faux si ni fichier audio ni speechSynthesis ne sont utilisables : l'UI masque le bouton. */
get supported() { get supported() {
return this.#synth !== null && this.#UtteranceClass !== undefined; return this.#AudioClass !== undefined || (this.#synth !== null && this.#UtteranceClass !== undefined);
} }
get enabled() { get enabled() {
@@ -50,19 +63,104 @@ export class VoiceEngine {
setRate(rate) { setRate(rate) {
this.#rate = Math.min(2, Math.max(0.5, rate)); this.#rate = Math.min(2, Math.max(0.5, rate));
if (this.#audio) {
this.#audio.playbackRate = this.#rate;
}
} }
/** /**
* Lit un texte. Résout à la fin de la lecture ; false si rien n'a été lu. * Lit un texte. Résout à la fin de la lecture ; false si rien n'a été lu ou si elle a été interrompue.
* @param {string} text Markdown léger toléré (les `` ` `` sont retirés). * @param {string} text Markdown léger toléré (les `` ` `` sont retirés pour la synthèse système).
* @param {string} [lang] 'fr' ou 'en'. * @param {string} [lang] 'fr' ou 'en'.
* @param {object} [options]
* @param {string|null} [options.audioUrl] Fichier pré-généré à préférer à la synthèse système.
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
speak(text, lang = 'fr') { async speak(text, lang = 'fr', { audioUrl = null } = {}) {
if (!this.supported || !this.#enabled) { if (!this.supported || !this.#enabled) {
return Promise.resolve(false); return false;
} }
this.cancel(); this.cancel();
const session = this.#session;
if (audioUrl && this.#AudioClass) {
const played = await this.#playFile(audioUrl, session);
if (played !== null) {
return played;
}
}
if (session !== this.#session) {
return false;
}
return this.#speakWithSystemVoice(text, lang);
}
/** Interrompt toute lecture en cours (fichier ou synthèse). */
cancel() {
this.#session += 1;
this.#releaseAudio();
this.#synth?.cancel();
}
/**
* Joue un fichier audio. Renvoie true (terminé), false (interrompu) ou null si le fichier est
* indisponible, auquel cas l'appelant se rabat sur la voix système.
*/
async #playFile(url, session) {
let blob;
try {
const response = await this.#fetch(url);
if (!response.ok) {
return null;
}
blob = await response.blob();
} catch {
return null;
}
if (session !== this.#session) {
return false;
}
// Lecture depuis un blob : pas de requêtes Range (exigées par iOS pour un flux direct).
this.#objectUrl = URL.createObjectURL(blob);
const audio = new this.#AudioClass(this.#objectUrl);
audio.playbackRate = this.#rate;
this.#audio = audio;
return new Promise((resolve) => {
let started = false;
audio.onplaying = () => {
started = true;
};
audio.onended = () => {
this.#releaseAudio();
resolve(true);
};
audio.onpause = () => resolve(false);
audio.onerror = () => {
this.#releaseAudio();
resolve(started ? false : null);
};
Promise.resolve(audio.play()).catch(() => {
this.#releaseAudio();
resolve(null);
});
});
}
#releaseAudio() {
if (this.#audio) {
this.#audio.onpause = null;
this.#audio.pause?.();
this.#audio = null;
}
if (this.#objectUrl) {
URL.revokeObjectURL(this.#objectUrl);
this.#objectUrl = null;
}
}
#speakWithSystemVoice(text, lang) {
if (this.#synth === null || this.#UtteranceClass === undefined) {
return Promise.resolve(false);
}
const utterance = new this.#UtteranceClass(this.#clean(text)); const utterance = new this.#UtteranceClass(this.#clean(text));
utterance.lang = LANG_TAGS[lang] ?? lang; utterance.lang = LANG_TAGS[lang] ?? lang;
utterance.rate = this.#rate; utterance.rate = this.#rate;
@@ -78,10 +176,6 @@ export class VoiceEngine {
}); });
} }
cancel() {
this.#synth?.cancel();
}
/** Voix du système correspondant à la langue, en privilégiant l'étiquette exacte. */ /** Voix du système correspondant à la langue, en privilégiant l'étiquette exacte. */
#pickVoice(tag) { #pickVoice(tag) {
const voices = this.#synth.getVoices?.() ?? []; const voices = this.#synth.getVoices?.() ?? [];
+20
View File
@@ -0,0 +1,20 @@
// Clé de narration : relie un texte de niveau à son fichier audio pré-généré.
// Doit rester strictement identique à scripts/voice_key.py (vecteurs de test communs).
const FNV_OFFSET = 0xcbf29ce484222325n;
const FNV_PRIME = 0x100000001b3n;
const MASK = 0xffffffffffffffffn;
/** Texte réellement lu : sans backticks Markdown, espaces normalisés. */
export function speechText(text) {
return text.replace(/`/g, '').replace(/\s+/g, ' ').trim();
}
/** Empreinte FNV-1a 64 bits (16 caractères hexadécimaux) de la langue et du texte lu. */
export function speechKey(lang, text) {
let value = FNV_OFFSET;
for (const byte of new TextEncoder().encode(`${lang}\n${speechText(text)}`)) {
value = ((value ^ BigInt(byte)) * FNV_PRIME) & MASK;
}
return value.toString(16).padStart(16, '0');
}
+4
View File
@@ -59,5 +59,9 @@
"settings.sound": "Sound effects", "settings.sound": "Sound effects",
"settings.volume": "Volume", "settings.volume": "Volume",
"settings.voice": "Voice", "settings.voice": "Voice",
"voice.sample": "Hello, I am the voice of PyQuest. This is how I will read the explanations.",
"settings.testSound": "Test the sound",
"settings.testVoice": "Test the voice",
"settings.voiceOffNotice": "Turn the voice on in the settings first.",
"settings.voiceRate": "Voice speed" "settings.voiceRate": "Voice speed"
} }
+4
View File
@@ -59,5 +59,9 @@
"settings.sound": "Effets sonores", "settings.sound": "Effets sonores",
"settings.volume": "Volume", "settings.volume": "Volume",
"settings.voice": "Voix", "settings.voice": "Voix",
"voice.sample": "Bonjour, je suis la voix de PyQuest. Voici comment je lirai les explications.",
"settings.testSound": "Tester le son",
"settings.testVoice": "Tester la voix",
"settings.voiceOffNotice": "Active d'abord la voix dans les réglages.",
"settings.voiceRate": "Vitesse de la voix" "settings.voiceRate": "Vitesse de la voix"
} }
+22 -1
View File
@@ -10,6 +10,7 @@ import { SettingsStore } from './core/SettingsStore.js';
import { ValidationEngine } from './core/ValidationEngine.js'; import { ValidationEngine } from './core/ValidationEngine.js';
import { VoiceEngine } from './core/VoiceEngine.js'; import { VoiceEngine } from './core/VoiceEngine.js';
import { I18n } from './i18n/i18n.js'; import { I18n } from './i18n/i18n.js';
import { speechKey } from './core/speechKey.js';
import { BadgeToast } from './ui/BadgeToast.js'; import { BadgeToast } from './ui/BadgeToast.js';
import { CellManager } from './ui/CellManager.js'; import { CellManager } from './ui/CellManager.js';
import { NotebookView } from './ui/NotebookView.js'; import { NotebookView } from './ui/NotebookView.js';
@@ -56,6 +57,7 @@ class App {
#audio; #audio;
#voice; #voice;
#manager; #manager;
#toast;
#map; #map;
#panel; #panel;
#levelIds = []; #levelIds = [];
@@ -81,10 +83,11 @@ class App {
const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href }); const client = new PyodideWorkerClient({ indexURL: new URL('/vendor/pyodide/', location.href).href });
const notebook = new NotebookView(this.#i18n, { const notebook = new NotebookView(this.#i18n, {
onSpeak: (text) => this.#voice.speak(text, this.#i18n.lang), onSpeak: (text, step) => this.#voice.speak(text, this.#i18n.lang, { audioUrl: step.audioUrl }),
canSpeak: () => this.#voice.supported && this.#voice.enabled, canSpeak: () => this.#voice.supported && this.#voice.enabled,
}); });
const toast = new BadgeToast(this.#i18n); const toast = new BadgeToast(this.#i18n);
this.#toast = toast;
this.#manager = new CellManager({ this.#manager = new CellManager({
i18n: this.#i18n, i18n: this.#i18n,
notebook, notebook,
@@ -101,6 +104,7 @@ class App {
this.#map.addEventListener('select', (event) => this.#openLevel(event.detail.id)); this.#map.addEventListener('select', (event) => this.#openLevel(event.detail.id));
this.#panel = new SettingsPanel(this.#i18n); this.#panel = new SettingsPanel(this.#i18n);
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail)); this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
document.getElementById('progress-region').append(this.#map.element); document.getElementById('progress-region').append(this.#map.element);
document.getElementById('notebook-region').append(notebook.element); document.getElementById('notebook-region').append(notebook.element);
@@ -168,6 +172,23 @@ class App {
} }
} }
/** Échantillons des réglages : le clic est le geste utilisateur qui débloque le son. */
async #onTest(kind) {
if (kind === 'sound') {
await this.#audio.unlock();
this.#audio.play('success_big');
return;
}
if (!this.#voice.enabled) {
this.#toast.show(this.#i18n.t('settings.voiceOffNotice'));
return;
}
const lang = this.#i18n.lang;
const sample = this.#i18n.t('voice.sample');
const audioUrl = new URL(`assets/voice/${lang}/${speechKey(lang, sample)}.mp3`, document.baseURI).href;
await this.#voice.speak(sample, lang, { audioUrl });
}
#registerServiceWorker() { #registerServiceWorker() {
// Repli : sans service worker (http hors localhost, navigateur ancien), l'app fonctionne en ligne. // Repli : sans service worker (http hors localhost, navigateur ancien), l'app fonctionne en ligne.
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
+4 -3
View File
@@ -12,7 +12,7 @@ export class NotebookView {
/** /**
* @param {import('../i18n/i18n.js').I18n} i18n * @param {import('../i18n/i18n.js').I18n} i18n
* @param {object} [options] * @param {object} [options]
* @param {(text: string) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton. * @param {(text: string, step: object) => Promise<boolean>} [options.onSpeak] Lecture vocale ; absent = pas de bouton.
* @param {() => boolean} [options.canSpeak] Évalué à chaque étape : la voix est-elle activée ? * @param {() => boolean} [options.canSpeak] Évalué à chaque étape : la voix est-elle activée ?
*/ */
constructor(i18n, { onSpeak = null, canSpeak = () => true } = {}) { constructor(i18n, { onSpeak = null, canSpeak = () => true } = {}) {
@@ -48,13 +48,14 @@ export class NotebookView {
} }
/** Étape d'explication : texte, et bouton de lecture si la voix est demandée par le niveau. */ /** Étape d'explication : texte, et bouton de lecture si la voix est demandée par le niveau. */
addExplain({ text, voice, image }) { addExplain(step) {
const { text, voice, image } = step;
const children = [el('p', {}, renderInline(text))]; const children = [el('p', {}, renderInline(text))];
if (image) { if (image) {
children.push(el('img', { src: image, alt: '' })); children.push(el('img', { src: image, alt: '' }));
} }
if (voice && this.#onSpeak && this.#canSpeak()) { if (voice && this.#onSpeak && this.#canSpeak()) {
children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text) })); children.push(el('button', { type: 'button', class: 'btn', text: this.#i18n.t('voice.listen'), onclick: () => this.#onSpeak(text, step) }));
} }
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children)); return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
} }
+14 -1
View File
@@ -1,5 +1,6 @@
// Panneau de réglages : accessible au clavier, chaque champ a un label visible. // Panneau de réglages : accessible au clavier, chaque champ a un label visible.
// Émet 'change' (detail: { key, value }) ; l'application persiste et applique. // Émet 'change' (detail: { key, value }) et 'test' (detail: { kind: 'sound' | 'voice' }) ;
// l'application persiste, applique, et joue les échantillons.
import { el, uniqueId } from './dom.js'; import { el, uniqueId } from './dom.js';
@@ -35,12 +36,24 @@ export class SettingsPanel extends EventTarget {
key: 'theme', key: 'theme',
}), }),
this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }), this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }),
this.#testButton('settings.testSound', 'sound'),
this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }), this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }),
this.#field('settings.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }), this.#field('settings.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }),
this.#testButton('settings.testVoice', 'voice'),
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }), this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
); );
} }
#testButton(labelKey, kind) {
const button = el('button', {
type: 'button',
class: 'btn',
text: this.#i18n.t(labelKey),
onclick: () => this.dispatchEvent(new CustomEvent('test', { detail: { kind } })),
});
return el('div', { class: 'setting' }, button);
}
#field(labelKey, kind, { value, options = [], key, number = false, ...range }) { #field(labelKey, kind, { value, options = [], key, number = false, ...range }) {
const id = uniqueId('setting'); const id = uniqueId('setting');
const emit = (newValue) => this.dispatchEvent(new CustomEvent('change', { detail: { key, value: newValue } })); const emit = (newValue) => this.dispatchEvent(new CustomEvent('change', { detail: { key, value: newValue } }));
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
{
"en": {
"3377dbceba2bc0b7": {
"text": "A program is a list of instructions. The computer reads them one by one, from top to bottom.",
"voice": "en_US-ljspeech-high"
},
"430223b95c3fa880": {
"text": "The computer guesses nothing. It does exactly what you write, nothing more. That is why we must be precise.",
"voice": "en_US-ljspeech-high"
},
"b076ad3710ea6882": {
"text": "Python is a language for writing these instructions. In the next level, you write your first line.",
"voice": "en_US-ljspeech-high"
},
"d9f081c67f104001": {
"text": "Like a recipe: 1. Crack the eggs. 2. Beat the eggs. 3. Cook the omelette. Change the order and the result changes.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"01f59f4dd745df14": {
"text": "Python est un langage pour écrire ces instructions. Dans le prochain niveau, tu écris ta première ligne.",
"voice": "fr_FR-siwis-medium"
},
"057035f93c3e455c": {
"text": "L'ordinateur ne devine rien. Il fait exactement ce que tu écris, rien de plus. C'est pour ça qu'on doit être précis.",
"voice": "fr_FR-siwis-medium"
},
"52435bdffec79d76": {
"text": "Comme une recette : 1. Casser les œufs. 2. Battre les œufs. 3. Cuire l'omelette. Si tu changes l'ordre, le résultat change.",
"voice": "fr_FR-siwis-medium"
},
"b691d6ad0208b825": {
"text": "Un programme est une liste d'instructions. L'ordinateur les lit une par une, de haut en bas.",
"voice": "fr_FR-siwis-medium"
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
{
"en": {
"6bb0749a98111d4b": {
"text": "print() shows text on the screen. The text goes between quotes, inside the parentheses.",
"voice": "en_US-ljspeech-high"
},
"a5c2adba55f3c70c": {
"text": "Text between quotes is called a string. Each print() writes on a new line.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"54eb6e343fdd61b5": {
"text": "print() affiche du texte à l'écran. Le texte va entre guillemets, dans les parenthèses.",
"voice": "fr_FR-siwis-medium"
},
"eb34bc4286d352bc": {
"text": "Un texte entre guillemets s'appelle une chaîne de caractères. Chaque print() écrit sur une nouvelle ligne.",
"voice": "fr_FR-siwis-medium"
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
{
"en": {
"1e3d9deb4223b3ec": {
"text": "There are several types. str: text (\"cat\"). int: a whole number (7). float: a decimal number (3.14, with a dot).",
"voice": "en_US-ljspeech-high"
},
"53c913acebcde4f6": {
"text": "A variable is a box with a name. You put a value in it: age = 12. The = sign stores the value in the box.",
"voice": "en_US-ljspeech-high"
},
"a7bc4151dfb8b449": {
"text": "You can calculate with variables: total = price * 3. A variable can also be reassigned later.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"34140c6135df449f": {
"text": "Une variable est une boîte avec un nom. Tu y ranges une valeur : age = 12. Le signe = range la valeur dans la boîte.",
"voice": "fr_FR-siwis-medium"
},
"a631adfba4ea98e4": {
"text": "Il existe plusieurs types. str : du texte (\"chat\"). int : un nombre entier (7). float : un nombre à virgule (3.14, avec un point).",
"voice": "fr_FR-siwis-medium"
},
"b01fc242e75a475e": {
"text": "Tu peux calculer avec des variables : total = price * 3. Une variable peut aussi être réaffectée plus tard.",
"voice": "fr_FR-siwis-medium"
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
{
"en": {
"5001c3ed998b7d08": {
"text": "Careful: input() always returns text (str), even if you type a number. To calculate, convert with int() for a whole number.",
"voice": "en_US-ljspeech-high"
},
"9b1fde4f226e7312": {
"text": "For a decimal number, use float(). Write the number with a dot: 2.5.",
"voice": "en_US-ljspeech-high"
},
"b6ee93b31ce24973": {
"text": "input() asks a question and waits for an answer. What you type is stored in a variable.",
"voice": "en_US-ljspeech-high"
}
},
"fr": {
"10106ac3ec9e360e": {
"text": "Pour un nombre à virgule, utilise float(). Écris le nombre avec un point : 2.5.",
"voice": "fr_FR-siwis-medium"
},
"93d150defcc1afd3": {
"text": "Attention : input() renvoie toujours du texte (str), même si tu tapes un nombre. Pour calculer, convertis avec int() pour un entier.",
"voice": "fr_FR-siwis-medium"
},
"f78f76c20364c000": {
"text": "input() pose une question et attend une réponse. Ce que tu tapes est rangé dans une variable.",
"voice": "fr_FR-siwis-medium"
}
}
}
+26
View File
@@ -0,0 +1,26 @@
# Crédits audio / Audio credits
La narration des niveaux est **pré-générée** par synthèse vocale (`make voice`, script
`scripts/generate_voice.py`) ; les fichiers `levels/*/audio/**/*.mp3` et
`app/assets/voice/**/*.mp3` en sont le résultat. Les effets sonores de l'interface sont
synthétisés dans le navigateur (`app/js/core/AudioEngine.js`) et ne reprennent aucun échantillon.
Narration is **pre-generated** with speech synthesis (`make voice`). UI sound effects are
synthesized in the browser and use no samples.
## Moteur / Engine
- [Piper](https://github.com/OHF-Voice/piper1-gpl) (GPL-3.0-or-later), utilisé **uniquement comme
outil de build** : il n'est pas embarqué dans l'application, seuls les fichiers audio produits
sont distribués. Piper is used as a build tool only; it is not shipped with the app.
## Voix / Voices (modèles de [rhasspy/piper-voices](https://huggingface.co/rhasspy/piper-voices))
| Langue | Voix | Jeu de données | Licence | Attribution |
|---|---|---|---|---|
| fr | `fr_FR-siwis-medium` | [SIWIS French Speech Synthesis Database](https://datashare.is.ed.ac.uk/handle/10283/2353), University of Edinburgh | CC BY 4.0 | Voix issue de la base SIWIS (Honnet et al., University of Edinburgh), licence CC BY 4.0 : https://creativecommons.org/licenses/by/4.0/ |
| en | `en_US-ljspeech-high` | [LJ Speech](https://keithito.com/LJ-Speech-Dataset/) | Domaine public | — |
Vérifier le `MODEL_CARD` d'une voix avant d'en changer : certaines voix Piper sont sous licence
non commerciale (ex. `en_US-hfc_female-medium`, CC BY-NC-SA) ou copyleft (ex. `fr_FR-tom-medium`,
AGPLv3) et ne conviennent pas à ce projet.
+2 -1
View File
@@ -17,6 +17,7 @@
"venvPath": ".", "venvPath": ".",
"venv": ".venv", "venv": ".venv",
"extraPaths": [ "extraPaths": [
"app/python" "app/python",
"scripts"
] ]
} }
+4
View File
@@ -0,0 +1,4 @@
# Génération de la narration (make voice). Outil de build uniquement, jamais embarqué dans l'app :
# piper-tts est sous GPL-3.0 ; seuls les fichiers audio produits sont distribués.
piper-tts>=1.3
PyYAML>=6.0
Binary file not shown.
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Pré-génère la narration avec Piper : un mp3 par texte `explain` (voice: true) et par langue,
plus l'échantillon de voix des réglages (clé `voice.sample` des catalogues d'interface).
Fichiers produits : levels/<id>/audio/<lang>/<clé>.mp3 + manifest.json par niveau, et
app/assets/voice/<lang>/<clé>.mp3 + manifest.json pour l'échantillon.
Outil de build : nécessite `make voice` (environnement .venv-voice avec piper-tts, GPL, et ffmpeg).
Les voix utilisées et leurs licences sont documentées dans levels/AUDIO-CREDITS.md.
"""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
import sys
import tempfile
import wave
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
from voice_key import speech_key, speech_text
ROOT = Path(__file__).resolve().parent.parent
LEVELS_DIR = ROOT / "levels"
CACHE_DIR = ROOT / ".cache" / "piper-voices"
UI_AUDIO_DIR = ROOT / "app" / "assets" / "voice"
I18N_DIR = ROOT / "app" / "js" / "i18n"
SAMPLE_KEY = "voice.sample"
# Voix choisies pour leur licence (CC-BY 4.0 pour siwis, domaine public pour ljspeech).
VOICES = {"fr": "fr_FR-siwis-medium", "en": "en_US-ljspeech-high"}
# Débit légèrement ralenti (1.0 = normal) : public débutant.
LENGTH_SCALE = 1.1
# Niveau sonore cible commun à tous les fichiers (loudnorm), pour une écoute confortable.
FFMPEG_FILTER = "loudnorm=I=-18:TP=-2:LRA=7"
@dataclass(frozen=True)
class Job:
group: str # id de niveau, ou "ui" pour l'échantillon des réglages
lang: str
key: str
text: str
@property
def base_dir(self) -> Path:
return UI_AUDIO_DIR if self.group == "ui" else LEVELS_DIR / self.group / "audio"
@property
def path(self) -> Path:
return self.base_dir / self.lang / f"{self.key}.mp3"
def collect_jobs() -> list[Job]:
"""Un job par texte `explain` à narrer et par langue disponible."""
jobs: list[Job] = []
for path in sorted(LEVELS_DIR.glob("*/level.yaml")):
level: dict[str, Any] = yaml.safe_load(path.read_text(encoding="utf-8"))
for step in level.get("steps", []):
if step.get("type") != "explain" or not step.get("voice"):
continue
for lang in VOICES:
text = step["text"].get(lang)
if text:
jobs.append(Job(level["id"], lang, speech_key(lang, text), speech_text(text)))
for lang in VOICES:
catalog: dict[str, str] = json.loads((I18N_DIR / f"{lang}.json").read_text(encoding="utf-8"))
jobs.append(Job("ui", lang, speech_key(lang, catalog[SAMPLE_KEY]), speech_text(catalog[SAMPLE_KEY])))
return jobs
def manifest_path(group: str) -> Path:
return (UI_AUDIO_DIR if group == "ui" else LEVELS_DIR / group / "audio") / "manifest.json"
def read_manifest(group: str) -> dict[str, dict[str, dict[str, str]]]:
path = manifest_path(group)
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
def is_current(job: Job, manifest: dict[str, dict[str, dict[str, str]]]) -> bool:
entry = manifest.get(job.lang, {}).get(job.key)
return job.path.exists() and entry is not None and entry["voice"] == VOICES[job.lang]
def synthesize(jobs: list[Job]) -> None:
# Import tardif : piper-tts n'est installé que dans .venv-voice (make voice), pas dans .venv.
from piper import PiperVoice, SynthesisConfig # pyright: ignore[reportMissingImports]
from piper.download_voices import download_voice # pyright: ignore[reportMissingImports]
if shutil.which("ffmpeg") is None:
sys.exit("ffmpeg est requis pour encoder les mp3.")
CACHE_DIR.mkdir(parents=True, exist_ok=True)
voices: dict[str, Any] = {}
config = SynthesisConfig(length_scale=LENGTH_SCALE)
for job in jobs:
if job.lang not in voices:
model = CACHE_DIR / f"{VOICES[job.lang]}.onnx"
if not model.exists():
download_voice(VOICES[job.lang], CACHE_DIR)
voices[job.lang] = PiperVoice.load(model)
job.path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
wav_path = Path(tmp) / "speech.wav"
with wave.open(str(wav_path), "wb") as wav_file:
voices[job.lang].synthesize_wav(job.text, wav_file, config)
subprocess.run(
["ffmpeg", "-y", "-loglevel", "error", "-i", str(wav_path), "-ac", "1", "-af", FFMPEG_FILTER,
"-ar", "22050", "-c:a", "libmp3lame", "-b:a", "48k", str(job.path)],
check=True,
)
print(f" {job.group}/{job.lang}/{job.key}.mp3 ({job.path.stat().st_size // 1024} Ko)")
def write_manifests(jobs: list[Job]) -> None:
"""Écrit un manifeste par groupe et supprime les fichiers audio devenus orphelins."""
by_group: dict[str, list[Job]] = {}
for job in jobs:
by_group.setdefault(job.group, []).append(job)
audio_dirs = {UI_AUDIO_DIR, *LEVELS_DIR.glob("*/audio")}
for audio_dir in audio_dirs:
group = "ui" if audio_dir == UI_AUDIO_DIR else audio_dir.parent.name
wanted = {job.path for job in by_group.get(group, [])}
for mp3 in audio_dir.glob("*/*.mp3"):
if mp3 not in wanted:
mp3.unlink()
print(f" supprimé (orphelin) : {mp3.relative_to(ROOT)}")
if group not in by_group and audio_dir.exists():
shutil.rmtree(audio_dir)
for group, group_jobs in by_group.items():
manifest: dict[str, dict[str, dict[str, str]]] = {}
for job in group_jobs:
manifest.setdefault(job.lang, {})[job.key] = {"voice": VOICES[job.lang], "text": job.text}
manifest_path(group).write_text(json.dumps(manifest, indent=4, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="vérifie sans générer ; code 1 si des fichiers manquent")
parser.add_argument("--force", action="store_true", help="régénère tous les fichiers")
args = parser.parse_args()
jobs = collect_jobs()
manifests = {group: read_manifest(group) for group in {job.group for job in jobs}}
todo = jobs if args.force else [job for job in jobs if not is_current(job, manifests[job.group])]
if args.check:
for job in todo:
print(f"manquant ou périmé : {job.group}/{job.lang}/{job.key} « {job.text[:50]} »")
print(f"{len(todo)} fichier(s) à générer sur {len(jobs)}.")
return 1 if todo else 0
print(f"{len(todo)} fichier(s) à générer sur {len(jobs)}.")
synthesize(todo)
write_manifests(jobs)
return 0
if __name__ == "__main__":
sys.exit(main())
+25
View File
@@ -0,0 +1,25 @@
"""Clé de narration : relie un texte de niveau à son fichier audio.
Doit rester strictement identique à `app/js/core/speechKey.js` (vecteurs de test communs).
"""
from __future__ import annotations
import re
_FNV_OFFSET = 0xCBF29CE484222325
_FNV_PRIME = 0x100000001B3
_MASK = 0xFFFFFFFFFFFFFFFF
def speech_text(text: str) -> str:
"""Texte réellement lu : sans backticks Markdown, espaces normalisés."""
return re.sub(r"\s+", " ", text.replace("`", "")).strip()
def speech_key(lang: str, text: str) -> str:
"""Empreinte FNV-1a 64 bits (16 hexa) de la langue et du texte lu."""
value = _FNV_OFFSET
for byte in f"{lang}\n{speech_text(text)}".encode("utf-8"):
value = ((value ^ byte) * _FNV_PRIME) & _MASK
return f"{value:016x}"
+79
View File
@@ -0,0 +1,79 @@
// Effets sonores : rendu hors ligne dans Chromium (même chaîne que la lecture réelle), puis mesure
// de la crête et du niveau efficace. Définir AUDIO_DUMP_DIR pour écrire des .wav à écouter.
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { after, before, test } from 'node:test';
import assert from 'node:assert';
import { chromium } from 'playwright-core';
const root = new URL('../../', import.meta.url).pathname;
const executablePath = process.env.CHROMIUM ?? '/usr/bin/chromium';
const port = 8128;
const skip = !existsSync(executablePath) && `navigateur absent (${executablePath})`;
const SAMPLE_RATE = 44100;
let server;
let browser;
before(async () => {
if (skip) return;
server = spawn('python3', [`${root}scripts/dev_server.py`, '--port', String(port)], { env: { ...process.env, PYQUEST_QUIET: '1' }, stdio: 'ignore' });
await new Promise((resolve) => setTimeout(resolve, 1000));
browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
});
after(async () => {
await browser?.close();
server?.kill();
});
const toDb = (value) => 20 * Math.log10(value);
function wav16(samples) {
const buffer = Buffer.alloc(44 + samples.length * 2);
buffer.write('RIFF', 0);
buffer.writeUInt32LE(36 + samples.length * 2, 4);
buffer.write('WAVEfmt ', 8);
buffer.writeUInt32LE(16, 16);
buffer.writeUInt16LE(1, 20); // PCM
buffer.writeUInt16LE(1, 22); // mono
buffer.writeUInt32LE(SAMPLE_RATE, 24);
buffer.writeUInt32LE(SAMPLE_RATE * 2, 28);
buffer.writeUInt16LE(2, 32);
buffer.writeUInt16LE(16, 34);
buffer.write('data', 36);
buffer.writeUInt32LE(samples.length * 2, 40);
samples.forEach((value, index) => buffer.writeInt16LE(Math.round(Math.max(-1, Math.min(1, value)) * 32767), 44 + index * 2));
return buffer;
}
test('les effets sonores sont audibles, sans saturation', { skip, timeout: 60000 }, async () => {
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${port}/`);
const rendered = await page.evaluate(async (rate) => {
const { AudioEngine } = await import('/js/core/AudioEngine.js');
const sounds = {};
for (const name of AudioEngine.soundNames) {
const context = new OfflineAudioContext(1, rate * 3, rate);
const { input } = AudioEngine.buildOutput(context, 0.8); // volume par défaut des réglages
const duration = AudioEngine.schedule(context, input, name, 0);
const buffer = await context.startRendering();
sounds[name] = Array.from(buffer.getChannelData(0).slice(0, Math.ceil(duration * rate)));
}
return sounds;
}, SAMPLE_RATE);
const dump = process.env.AUDIO_DUMP_DIR;
if (dump) mkdirSync(dump, { recursive: true });
for (const [name, samples] of Object.entries(rendered)) {
const peak = Math.max(...samples.map(Math.abs));
const active = samples.filter((value) => Math.abs(value) > 0.001);
const rms = Math.sqrt(active.reduce((sum, value) => sum + value * value, 0) / active.length);
console.log(`${name.padEnd(15)} durée ${(samples.length / SAMPLE_RATE).toFixed(2)} s crête ${toDb(peak).toFixed(1)} dBFS efficace ${toDb(rms).toFixed(1)} dBFS`);
if (dump) writeFileSync(`${dump}/fx-${name}.wav`, wav16(samples));
// Audible : crête au moins -8 dBFS, niveau efficace au moins -26 dBFS ; jamais de saturation.
assert.ok(toDb(peak) >= -8, `${name} trop faible : crête ${toDb(peak).toFixed(1)} dBFS`);
assert.ok(toDb(peak) <= -0.5, `${name} sature : crête ${toDb(peak).toFixed(1)} dBFS`);
assert.ok(toDb(rms) >= -26, `${name} trop faible : efficace ${toDb(rms).toFixed(1)} dBFS`);
}
});
+47
View File
@@ -145,3 +145,50 @@ test('niveau 03 : saisie interactive et validation par rejeu scripté', { skip,
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
}); });
test('narration : fichier Piper lu jusqu\'au bout, échantillon des réglages, repli', { skip, timeout: 120000 }, async () => {
const browser2 = await chromium.launch({ executablePath, args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] });
try {
const page = await (await browser2.newContext()).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const served = [];
page.on('response', (response) => {
if (response.url().endsWith('.mp3')) served.push(`${response.status()} ${response.headers()['content-type']}`);
});
// Espionne les lectures pour savoir si un fichier est allé jusqu'à la fin.
await page.addInitScript(() => {
window.__audio = { ended: 0, errors: 0 };
const Original = window.Audio;
window.Audio = class extends Original {
constructor(...args) {
super(...args);
this.addEventListener('ended', () => (window.__audio.ended += 1));
this.addEventListener('error', () => (window.__audio.errors += 1));
}
};
});
await page.goto(base);
await page.waitForSelector('.explain', { timeout: 60000 });
// La voix est désactivée par défaut : pas de bouton « Écouter ».
assert.equal(await page.locator('.explain button', { hasText: 'Écouter' }).count(), 0);
await page.locator('#settings-toggle').click();
await page.getByLabel('Voix', { exact: true }).check();
await page.locator('.settings').getByRole('button', { name: 'Tester la voix' }).click();
await page.waitForFunction(() => window.__audio.ended >= 1, null, { timeout: 30000 });
// Narration d'une étape de niveau : relance le niveau pour afficher le bouton.
await page.locator('.level-button', { hasText: 'Ton premier programme' }).click();
await page.waitForSelector('.explain button');
const before = await page.evaluate(() => window.__audio.ended);
await page.locator('.explain button', { hasText: 'Écouter' }).click();
await page.waitForFunction((count) => window.__audio.ended > count, before, { timeout: 30000 });
assert.ok(served.length >= 2 && served.every((entry) => entry.startsWith('200 audio/mpeg')), `mp3 servis : ${served}`);
assert.equal(await page.evaluate(() => window.__audio.errors), 0);
assert.deepEqual(errors, []);
} finally {
await browser2.close();
}
});
+27 -4
View File
@@ -2,12 +2,13 @@ import { AudioEngine } from '../../app/js/core/AudioEngine.js';
import { VoiceEngine } from '../../app/js/core/VoiceEngine.js'; import { VoiceEngine } from '../../app/js/core/VoiceEngine.js';
import assert from 'node:assert'; import assert from 'node:assert';
let osc = 0; let osc = 0;
const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: {}, gain: { setValueAtTime() {}, linearRampToValueAtTime() {} } }); const param = () => ({ value: 0, setValueAtTime() {}, linearRampToValueAtTime() {}, exponentialRampToValueAtTime() {} });
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node }; const node = () => ({ connect: (n) => n, start() {}, stop() {}, frequency: param(), gain: param(), threshold: param(), knee: param(), ratio: param(), attack: param(), release: param() });
const ctx = { state: 'suspended', currentTime: 0, destination: {}, resume: async function () { this.state = 'running'; }, createOscillator: () => { osc++; return node(); }, createGain: node, createDynamicsCompressor: node };
const a = new AudioEngine({ contextFactory: () => ctx }); const a = new AudioEngine({ contextFactory: () => ctx });
assert.equal(a.play('success_small'), false); // pas débloqué assert.equal(a.play('success_small'), false); // pas débloqué
await a.unlock(); await a.unlock();
assert.equal(a.play('success_small'), true); assert.equal(osc, 2); assert.equal(a.play('success_small'), true); assert.equal(osc, 6); // 2 notes × 3 partiels
assert.equal(a.play('nope'), false); assert.equal(a.play('nope'), false);
a.setEnabled(false); assert.equal(a.play('error'), false); a.setEnabled(false); assert.equal(a.play('error'), false);
a.setEnabled(true); a.setVolume(5); assert.equal(a.volume, 1); a.setEnabled(true); a.setVolume(5); assert.equal(a.volume, 1);
@@ -21,5 +22,27 @@ assert.equal(await v.speak('Utilise `print()` ici', 'fr'), true);
const u = spoken.at(-1); assert.equal(u.text, 'Utilise print() ici'); assert.equal(u.voice.lang, 'fr-FR'); assert.equal(u.lang, 'fr-FR'); const u = spoken.at(-1); assert.equal(u.text, 'Utilise print() ici'); assert.equal(u.voice.lang, 'fr-FR'); assert.equal(u.lang, 'fr-FR');
v.setRate(9); assert.equal(v.rate, 2); v.setRate(9); assert.equal(v.rate, 2);
v.setEnabled(false); assert.equal(await v.speak('x'), false); v.setEnabled(false); assert.equal(await v.speak('x'), false);
assert.equal(new VoiceEngine({ synth: null, Utterance: undefined }).supported, false); assert.equal(new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined }).supported, false);
// Narration par fichier pré-généré, avec repli sur la voix système si le fichier manque.
globalThis.URL.createObjectURL = () => 'blob:fake';
globalThis.URL.revokeObjectURL = () => {};
const played = [];
class FakeAudio {
constructor(src) { this.src = src; played.push(this); }
play() { queueMicrotask(() => { this.onplaying?.(); this.onended?.(); }); return Promise.resolve(); }
pause() {}
}
const spoken2 = [];
const synth2 = { cancel() {}, getVoices: () => [], speak(u) { spoken2.push(u.text); setTimeout(() => u.onend(), 0); } };
const files = { ok: true };
const fetchFn = async (url) => (url.endsWith('/there.mp3') ? { ok: true, blob: async () => new Blob(['x']) } : { ok: false });
const v2 = new VoiceEngine({ synth: synth2, Utterance: U, AudioClass: FakeAudio, fetchFn });
assert.equal(await v2.speak('Texte', 'fr', { audioUrl: '/a/there.mp3' }), true);
assert.equal(played.length, 1); assert.deepEqual(spoken2, []); // fichier lu, pas de voix système
assert.equal(await v2.speak('Repli `x`', 'fr', { audioUrl: '/a/absent.mp3' }), true);
assert.equal(played.length, 1); assert.deepEqual(spoken2, ['Repli x']); // fichier absent : repli
v2.setRate(1.5); assert.equal(v2.rate, 1.5);
const noAudioNoSynth = new VoiceEngine({ synth: null, Utterance: undefined, AudioClass: undefined });
assert.equal(noAudioNoSynth.supported, false);
console.log('audio/voice ok'); console.log('audio/voice ok');
+10
View File
@@ -0,0 +1,10 @@
// Vecteurs communs avec tests/python/test_voice_key.py : les deux implémentations doivent concorder.
import { speechKey, speechText } from '../../app/js/core/speechKey.js';
import assert from 'node:assert';
assert.equal(speechText(' Un `print()` affiche\n du texte. '), 'Un print() affiche du texte.');
assert.equal(speechKey('fr', 'Un `print()` affiche du texte.'), '0933ff041539352b');
assert.equal(speechKey('en', 'Héllo wörld'), '87e2e25e5123e565');
assert.equal(speechKey('fr', ''), 'dc8d3218feba4761');
assert.notEqual(speechKey('fr', 'Bonjour'), speechKey('en', 'Bonjour'));
console.log('speech key ok');
+36
View File
@@ -0,0 +1,36 @@
// Chaque étape narrée de chaque niveau doit avoir son fichier audio (make voice), dans les deux
// langues, à l'URL exacte que construit LevelSession ; idem pour l'échantillon des réglages.
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import assert from 'node:assert';
import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs';
import { LevelSession } from '../../app/js/core/LevelSession.js';
import { speechKey } from '../../app/js/core/speechKey.js';
const root = new URL('../../', import.meta.url).pathname;
const base = 'http://x/levels/';
const missing = [];
let checked = 0;
for (const id of readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name))) {
const level = yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
for (const lang of ['fr', 'en']) {
const session = new LevelSession(level, lang, `${base}${id}/`);
for (let i = 0; i < session.stepCount; i++, session.next()) {
const step = session.step;
if (step.type !== 'explain' || !step.voice) continue;
checked += 1;
assert.ok(step.audioUrl.startsWith(`${base}${id}/audio/${lang}/`), step.audioUrl);
const file = `${root}levels/${step.audioUrl.slice(base.length)}`;
if (!existsSync(file)) missing.push(file);
}
}
}
for (const lang of ['fr', 'en']) {
const sample = JSON.parse(readFileSync(`${root}app/js/i18n/${lang}.json`, 'utf8'))['voice.sample'];
const file = `${root}app/assets/voice/${lang}/${speechKey(lang, sample)}.mp3`;
checked += 1;
if (!existsSync(file)) missing.push(file);
}
assert.ok(checked > 0);
assert.deepEqual(missing, [], 'narration manquante : lancer make voice');
console.log(`voice assets ok (${checked} fichiers)`);
+28
View File
@@ -0,0 +1,28 @@
"""Vecteurs communs avec tests/js/speech-key.test.mjs : les deux implémentations doivent concorder."""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
from voice_key import speech_key, speech_text # noqa: E402
class VoiceKeyTest(unittest.TestCase):
def test_text_is_normalised(self) -> None:
self.assertEqual(speech_text(" Un `print()` affiche\n du texte. "), "Un print() affiche du texte.")
def test_vectors_match_javascript(self) -> None:
self.assertEqual(speech_key("fr", "Un `print()` affiche du texte."), "0933ff041539352b")
self.assertEqual(speech_key("en", "Héllo wörld"), "87e2e25e5123e565")
self.assertEqual(speech_key("fr", ""), "dc8d3218feba4761")
def test_language_changes_key(self) -> None:
self.assertNotEqual(speech_key("fr", "Bonjour"), speech_key("en", "Bonjour"))
if __name__ == "__main__":
unittest.main()