mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Offline Piper narration: downloadable voices (settings), automatic level prefetch, durable audio and Pyodide caches
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -38,6 +38,7 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
|||||||
| 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` |
|
||||||
| Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) |
|
| Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) |
|
||||||
| Backend | `backend/` Django : `GET/PUT/DELETE /api/sync/` avec jeton Bearer (haché côté serveur), concurrence optimiste (`base` → 409) |
|
| Backend | `backend/` Django : `GET/PUT/DELETE /api/sync/` avec jeton Bearer (haché côté serveur), concurrence optimiste (`base` → 409) |
|
||||||
|
| Voix hors ligne | `core/OfflineVoices.js` (cache `pyquest-audio`, partagé avec le service worker : narration en cache-first, cache durable ; Pyodide aussi dans un cache versionné `pyquest-pyodide-<version>`), bouton dans les Réglages, préchargement du niveau ouvert ; e2e « voix hors ligne » |
|
||||||
| Pile locale | `make dev-nginx` (`scripts/local_stack.py`) : vrai nginx + Django, mêmes blocs que la prod (`nginx/pyquest-locations.conf.example`) ; `tests/e2e/nginx.test.mjs` ; binaire via `PYQUEST_NGINX` (ne pas utiliser `NGINX`, lue par nginx) |
|
| Pile locale | `make dev-nginx` (`scripts/local_stack.py`) : vrai nginx + Django, mêmes blocs que la prod (`nginx/pyquest-locations.conf.example`) ; `tests/e2e/nginx.test.mjs` ; binaire via `PYQUEST_NGINX` (ne pas utiliser `NGINX`, lue par nginx) |
|
||||||
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
||||||
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
||||||
|
|||||||
@@ -351,3 +351,11 @@ pre {
|
|||||||
transition: none !important;
|
transition: none !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.voices-status:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.voices-message:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
// Narration Piper disponible hors ligne : les fichiers mp3 pré-générés sont stockés dans le cache `pyquest-audio`
|
||||||
|
// (le même que celui lu par le service worker). Sans cela, seuls les extraits déjà écoutés en ligne sont disponibles
|
||||||
|
// hors connexion, et la lecture se rabat sur la voix du système. Les fichiers sont nommés d'après leur contenu : un
|
||||||
|
// fichier en cache n'est donc jamais périmé et le cache survit aux mises à jour de l'application.
|
||||||
|
|
||||||
|
export const AUDIO_CACHE = 'pyquest-audio';
|
||||||
|
|
||||||
|
export class OfflineVoices extends EventTarget {
|
||||||
|
#levelsUrl;
|
||||||
|
#fetch;
|
||||||
|
#caches;
|
||||||
|
#manifests = new Map();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} options
|
||||||
|
* @param {string} options.levelsUrl Racine des niveaux, avec slash final.
|
||||||
|
* @param {typeof fetch} [options.fetchFn]
|
||||||
|
* @param {CacheStorage|undefined} [options.cachesApi] Remplaçable pour les tests.
|
||||||
|
*/
|
||||||
|
constructor({ levelsUrl, fetchFn = (...args) => fetch(...args), cachesApi = globalThis.caches }) {
|
||||||
|
super();
|
||||||
|
this.#levelsUrl = levelsUrl;
|
||||||
|
this.#fetch = fetchFn;
|
||||||
|
this.#caches = cachesApi;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Faux si le navigateur n'a pas l'API Cache (page non sécurisée) : la fonction est alors masquée. */
|
||||||
|
get supported() {
|
||||||
|
return this.#caches !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** URLs des narrations des niveaux donnés, dans la langue donnée. */
|
||||||
|
async urlsFor(levelIds, lang) {
|
||||||
|
const lists = await Promise.all(levelIds.map((id) => this.#levelUrls(id, lang)));
|
||||||
|
return lists.flat();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {Promise<{total: number, cached: number}>} */
|
||||||
|
async status(levelIds, lang) {
|
||||||
|
const urls = await this.urlsFor(levelIds, lang);
|
||||||
|
if (!this.supported) {
|
||||||
|
return { total: urls.length, cached: 0 };
|
||||||
|
}
|
||||||
|
const cache = await this.#caches.open(AUDIO_CACHE);
|
||||||
|
const hits = await Promise.all(urls.map(async (url) => (await cache.match(url)) !== undefined));
|
||||||
|
return { total: urls.length, cached: hits.filter(Boolean).length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Télécharge dans le cache les narrations manquantes (celles déjà en cache ne sont pas retéléchargées).
|
||||||
|
* @param {string[]} levelIds
|
||||||
|
* @param {string} lang
|
||||||
|
* @param {object} [options]
|
||||||
|
* @param {(done: number, total: number) => void} [options.onProgress]
|
||||||
|
* @param {AbortSignal} [options.signal]
|
||||||
|
* @returns {Promise<{total: number, downloaded: number, failed: number}>}
|
||||||
|
*/
|
||||||
|
async download(levelIds, lang, { onProgress = () => {}, signal } = {}) {
|
||||||
|
const urls = await this.urlsFor(levelIds, lang);
|
||||||
|
if (!this.supported) {
|
||||||
|
return { total: urls.length, downloaded: 0, failed: urls.length };
|
||||||
|
}
|
||||||
|
const cache = await this.#caches.open(AUDIO_CACHE);
|
||||||
|
const missing = [];
|
||||||
|
for (const url of urls) {
|
||||||
|
if ((await cache.match(url)) === undefined) {
|
||||||
|
missing.push(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let done = urls.length - missing.length;
|
||||||
|
let downloaded = 0;
|
||||||
|
let failed = 0;
|
||||||
|
onProgress(done, urls.length);
|
||||||
|
const queue = [...missing];
|
||||||
|
const worker = async () => {
|
||||||
|
while (queue.length > 0 && !signal?.aborted) {
|
||||||
|
const url = queue.shift();
|
||||||
|
try {
|
||||||
|
const response = await this.#fetch(url, { signal });
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
await cache.put(url, response);
|
||||||
|
downloaded += 1;
|
||||||
|
} catch {
|
||||||
|
failed += 1;
|
||||||
|
}
|
||||||
|
done += 1;
|
||||||
|
onProgress(done, urls.length);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Deux téléchargements en parallèle : assez rapide sans saturer une connexion modeste.
|
||||||
|
await Promise.all([worker(), worker()]);
|
||||||
|
return { total: urls.length, downloaded, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
async #levelUrls(id, lang) {
|
||||||
|
const manifest = await this.#manifest(id);
|
||||||
|
return Object.keys(manifest[lang] ?? {}).map((key) => new URL(`${id}/audio/${lang}/${key}.mp3`, this.#levelsUrl).href);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Manifeste de narration d'un niveau ({} s'il n'a pas de voix ou si le chargement échoue). */
|
||||||
|
async #manifest(id) {
|
||||||
|
if (!this.#manifests.has(id)) {
|
||||||
|
let manifest = {};
|
||||||
|
try {
|
||||||
|
const response = await this.#fetch(new URL(`${id}/audio/manifest.json`, this.#levelsUrl));
|
||||||
|
if (response.ok) {
|
||||||
|
manifest = await response.json();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
manifest = {};
|
||||||
|
}
|
||||||
|
// Un échec n'est pas mémorisé (réseau coupé) ; un succès l'est.
|
||||||
|
if (Object.keys(manifest).length === 0) {
|
||||||
|
return manifest;
|
||||||
|
}
|
||||||
|
this.#manifests.set(id, manifest);
|
||||||
|
}
|
||||||
|
return this.#manifests.get(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-1
@@ -138,5 +138,12 @@
|
|||||||
"drawing.color.blue": "blue",
|
"drawing.color.blue": "blue",
|
||||||
"drawing.color.orange": "orange",
|
"drawing.color.orange": "orange",
|
||||||
"drawing.color.purple": "purple",
|
"drawing.color.purple": "purple",
|
||||||
"drawing.color.gray": "gray"
|
"drawing.color.gray": "gray",
|
||||||
|
"voices.title": "Offline voices",
|
||||||
|
"voices.help": "The quality voices are files to download once. Without them, offline, only your device's (more rudimentary) voice can read the texts.",
|
||||||
|
"voices.status": "{cached} of {total} voices available offline in this language.",
|
||||||
|
"voices.download": "Download the voices for offline use",
|
||||||
|
"voices.downloading": "Downloading: {done} of {total}…",
|
||||||
|
"voices.done": "Voices downloaded: they will be read even without a connection.",
|
||||||
|
"voices.failed": "{failed} file(s) could not be downloaded. Try again with a connection."
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-1
@@ -138,5 +138,12 @@
|
|||||||
"drawing.color.blue": "bleu",
|
"drawing.color.blue": "bleu",
|
||||||
"drawing.color.orange": "orange",
|
"drawing.color.orange": "orange",
|
||||||
"drawing.color.purple": "violet",
|
"drawing.color.purple": "violet",
|
||||||
"drawing.color.gray": "gris"
|
"drawing.color.gray": "gris",
|
||||||
|
"voices.title": "Voix hors ligne",
|
||||||
|
"voices.help": "Les voix de qualité sont des fichiers à télécharger une fois. Sans cela, hors connexion, seule la voix (plus rudimentaire) de ton appareil peut lire les textes.",
|
||||||
|
"voices.status": "{cached} voix sur {total} disponibles hors ligne dans cette langue.",
|
||||||
|
"voices.download": "Télécharger les voix pour le hors ligne",
|
||||||
|
"voices.downloading": "Téléchargement : {done} sur {total}…",
|
||||||
|
"voices.done": "Voix téléchargées : elles seront lues même sans connexion.",
|
||||||
|
"voices.failed": "{failed} fichier(s) n'ont pas pu être téléchargés. Réessaie avec une connexion."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStor
|
|||||||
import { ProgressStore } from './core/ProgressStore.js';
|
import { ProgressStore } from './core/ProgressStore.js';
|
||||||
import { PyodideWorkerClient } from './core/PyodideWorkerClient.js';
|
import { PyodideWorkerClient } from './core/PyodideWorkerClient.js';
|
||||||
import { SettingsStore } from './core/SettingsStore.js';
|
import { SettingsStore } from './core/SettingsStore.js';
|
||||||
|
import { OfflineVoices } from './core/OfflineVoices.js';
|
||||||
import { SyncClient } from './core/SyncClient.js';
|
import { SyncClient } from './core/SyncClient.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';
|
||||||
@@ -60,6 +61,8 @@ class App {
|
|||||||
#settings;
|
#settings;
|
||||||
#progress;
|
#progress;
|
||||||
#sync;
|
#sync;
|
||||||
|
#offlineVoices;
|
||||||
|
#voicesDownload = null;
|
||||||
#lessons;
|
#lessons;
|
||||||
#audio;
|
#audio;
|
||||||
#voice;
|
#voice;
|
||||||
@@ -94,6 +97,7 @@ class App {
|
|||||||
this.#sync = new SyncClient({ store, progress: this.#progress, endpoint: new URL('api/sync/', document.baseURI).href });
|
this.#sync = new SyncClient({ store, progress: this.#progress, endpoint: new URL('api/sync/', document.baseURI).href });
|
||||||
await this.#sync.load();
|
await this.#sync.load();
|
||||||
this.#lessons = new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href });
|
this.#lessons = new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href });
|
||||||
|
this.#offlineVoices = new OfflineVoices({ levelsUrl: new URL('/levels/', location.href).href });
|
||||||
this.#audio = new AudioEngine({ enabled: settings.soundEnabled, volume: settings.volume });
|
this.#audio = new AudioEngine({ enabled: settings.soundEnabled, volume: settings.volume });
|
||||||
this.#voice = new VoiceEngine({ enabled: settings.voiceEnabled, rate: settings.voiceRate });
|
this.#voice = new VoiceEngine({ enabled: settings.voiceEnabled, rate: settings.voiceRate });
|
||||||
|
|
||||||
@@ -131,6 +135,7 @@ class App {
|
|||||||
this.#panel.addEventListener('sync', (event) => this.#onSync(event.detail));
|
this.#panel.addEventListener('sync', (event) => this.#onSync(event.detail));
|
||||||
this.#sync.addEventListener('change', (event) => this.#panel.setSync(event.detail));
|
this.#sync.addEventListener('change', (event) => this.#panel.setSync(event.detail));
|
||||||
this.#sync.addEventListener('merged', () => this.#renderMap());
|
this.#sync.addEventListener('merged', () => this.#renderMap());
|
||||||
|
this.#panel.addEventListener('voices', () => this.#downloadVoices());
|
||||||
this.#panel.addEventListener('export', () => this.#exportProgress());
|
this.#panel.addEventListener('export', () => this.#exportProgress());
|
||||||
this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file));
|
this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file));
|
||||||
|
|
||||||
@@ -151,6 +156,7 @@ class App {
|
|||||||
// Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche.
|
// Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche.
|
||||||
await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
|
await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
|
||||||
this.#registerServiceWorker();
|
this.#registerServiceWorker();
|
||||||
|
this.#refreshVoiceStatus();
|
||||||
// Synchronisation (si activée) : au démarrage, au retour du réseau et quand l'onglet redevient visible.
|
// Synchronisation (si activée) : au démarrage, au retour du réseau et quand l'onglet redevient visible.
|
||||||
this.#sync.start();
|
this.#sync.start();
|
||||||
window.addEventListener('online', () => this.#sync.sync());
|
window.addEventListener('online', () => this.#sync.sync());
|
||||||
@@ -196,6 +202,7 @@ class App {
|
|||||||
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
|
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
|
||||||
this.#updateLevelNav(session.title);
|
this.#updateLevelNav(session.title);
|
||||||
await this.#manager.start(session, { greeting });
|
await this.#manager.start(session, { greeting });
|
||||||
|
this.#prefetchLevelVoices(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
async #renderMap() {
|
async #renderMap() {
|
||||||
@@ -286,6 +293,46 @@ class App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Nombre de narrations déjà disponibles hors ligne dans la langue courante (affiché dans les réglages). */
|
||||||
|
async #refreshVoiceStatus() {
|
||||||
|
const supported = this.#offlineVoices.supported && this.#voice.supported;
|
||||||
|
if (!supported) {
|
||||||
|
this.#panel.setVoices({ supported: false });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { total, cached } = await this.#offlineVoices.status(this.#levelIds, this.#i18n.lang);
|
||||||
|
this.#panel.setVoices({ supported: true, total, cached, running: false, message: '' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Télécharge toutes les narrations de la langue courante pour une écoute hors ligne. */
|
||||||
|
async #downloadVoices() {
|
||||||
|
if (this.#voicesDownload) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lang = this.#i18n.lang;
|
||||||
|
this.#voicesDownload = true;
|
||||||
|
this.#panel.setVoices({ running: true, done: 0, message: '' });
|
||||||
|
try {
|
||||||
|
const result = await this.#offlineVoices.download(this.#levelIds, lang, {
|
||||||
|
onProgress: (done, total) => this.#panel.setVoices({ running: true, done, total }),
|
||||||
|
});
|
||||||
|
const message = result.failed > 0 ? this.#i18n.t('voices.failed', { failed: result.failed }) : this.#i18n.t('voices.done');
|
||||||
|
await this.#refreshVoiceStatus();
|
||||||
|
this.#panel.setVoices({ message });
|
||||||
|
} finally {
|
||||||
|
this.#voicesDownload = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Précharge discrètement la narration du niveau ouvert : elle sera lisible hors ligne, sans action de l'apprenant. */
|
||||||
|
#prefetchLevelVoices(id) {
|
||||||
|
// Économie de données demandée par le navigateur : on ne télécharge rien sans clic.
|
||||||
|
if (navigator.connection?.saveData || !this.#offlineVoices.supported || !this.#voice.supported) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.#offlineVoices.download([id], this.#i18n.lang).then(() => this.#refreshVoiceStatus()).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
async #onSync({ action, token }) {
|
async #onSync({ action, token }) {
|
||||||
const t = (key) => this.#i18n.t(key);
|
const t = (key) => this.#i18n.t(key);
|
||||||
const say = (key) => this.#panel.setSync(this.#sync.state, key ? t(key) : '');
|
const say = (key) => this.#panel.setSync(this.#sync.state, key ? t(key) : '');
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ export class SettingsPanel extends EventTarget {
|
|||||||
#syncRoot = el('fieldset', { class: 'setting-group sync-group' });
|
#syncRoot = el('fieldset', { class: 'setting-group sync-group' });
|
||||||
#syncState = { enabled: false, token: null, status: 'off', error: null, lastSync: null };
|
#syncState = { enabled: false, token: null, status: 'off', error: null, lastSync: null };
|
||||||
#syncMessage = '';
|
#syncMessage = '';
|
||||||
|
#voicesRoot = el('fieldset', { class: 'setting-group voices-group' });
|
||||||
|
#voicesState = { supported: false, total: 0, cached: 0, running: false, done: 0, message: '' };
|
||||||
|
|
||||||
/** @param {import('../i18n/i18n.js').I18n} i18n */
|
/** @param {import('../i18n/i18n.js').I18n} i18n */
|
||||||
constructor(i18n) {
|
constructor(i18n) {
|
||||||
@@ -43,6 +45,7 @@ export class SettingsPanel extends EventTarget {
|
|||||||
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.#testButton('settings.testVoice', 'voice'),
|
||||||
|
this.#voicesRoot,
|
||||||
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 }),
|
||||||
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
|
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
|
||||||
this.#backupSection(),
|
this.#backupSection(),
|
||||||
@@ -50,6 +53,13 @@ export class SettingsPanel extends EventTarget {
|
|||||||
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
|
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
|
||||||
);
|
);
|
||||||
this.#renderSync();
|
this.#renderSync();
|
||||||
|
this.#renderVoices();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Met à jour la section « Voix hors ligne » (état du téléchargement des narrations). */
|
||||||
|
setVoices(state) {
|
||||||
|
this.#voicesState = { ...this.#voicesState, ...state };
|
||||||
|
this.#renderVoices();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Met à jour la section de synchronisation (état du SyncClient ; `message` : résultat d'une action). */
|
/** Met à jour la section de synchronisation (état du SyncClient ; `message` : résultat d'une action). */
|
||||||
@@ -92,6 +102,41 @@ export class SettingsPanel extends EventTarget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#renderVoices() {
|
||||||
|
const t = (key, params) => this.#i18n.t(key, params);
|
||||||
|
const state = this.#voicesState;
|
||||||
|
if (!state.supported) {
|
||||||
|
this.#voicesRoot.replaceChildren();
|
||||||
|
this.#voicesRoot.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.#voicesRoot.hidden = false;
|
||||||
|
const focused = this.#voicesRoot.contains(document.activeElement);
|
||||||
|
const status = state.running
|
||||||
|
? t('voices.downloading', { done: state.done, total: state.total })
|
||||||
|
: t('voices.status', { cached: state.cached, total: state.total });
|
||||||
|
const button = el('button', {
|
||||||
|
type: 'button',
|
||||||
|
class: 'btn',
|
||||||
|
id: 'voices-download',
|
||||||
|
disabled: state.running || (state.total > 0 && state.cached >= state.total),
|
||||||
|
text: t('voices.download'),
|
||||||
|
onclick: () => this.dispatchEvent(new Event('voices')),
|
||||||
|
});
|
||||||
|
this.#voicesRoot.replaceChildren(
|
||||||
|
el('legend', { text: t('voices.title') }),
|
||||||
|
el('p', { class: 'hint', text: t('voices.help') }),
|
||||||
|
el('p', { class: 'voices-status', role: 'status', tabindex: '-1', text: status }),
|
||||||
|
button,
|
||||||
|
// Résultat du dernier téléchargement : annoncé aux lecteurs d'écran.
|
||||||
|
el('p', { class: 'voices-message', role: 'status', text: state.message }),
|
||||||
|
);
|
||||||
|
if (focused) {
|
||||||
|
// Le bouton se désactive quand tout est téléchargé : le focus passe alors à l'état, sans se perdre.
|
||||||
|
(button.disabled ? this.#voicesRoot.querySelector('.voices-status') : button)?.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#renderSync() {
|
#renderSync() {
|
||||||
const t = (key, params) => this.#i18n.t(key, params);
|
const t = (key, params) => this.#i18n.t(key, params);
|
||||||
const state = this.#syncState;
|
const state = this.#syncState;
|
||||||
|
|||||||
+23
-7
@@ -4,6 +4,12 @@
|
|||||||
// Les en-têtes COOP/COEP du document viennent du serveur ; ce worker ne les fabrique pas.
|
// Les en-têtes COOP/COEP du document viennent du serveur ; ce worker ne les fabrique pas.
|
||||||
|
|
||||||
const CACHE_VERSION = 'pyquest-v5';
|
const CACHE_VERSION = 'pyquest-v5';
|
||||||
|
// Caches à longue durée de vie : leur nom ne change pas à chaque déploiement.
|
||||||
|
// - narration Piper : fichiers nommés d'après leur contenu, donc jamais périmés ; les télécharger une fois suffit
|
||||||
|
// (page : OfflineVoices) et ils survivent aux mises à jour de l'application ;
|
||||||
|
// - Pyodide : versionné (le nom du cache change seulement si la version de Pyodide change, voir scripts/build.py).
|
||||||
|
const AUDIO_CACHE = 'pyquest-audio';
|
||||||
|
const PYODIDE_CACHE = 'pyquest-pyodide-dev';
|
||||||
|
|
||||||
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'css/guide.css', 'css/progress.css', 'icons/icon.svg', 'js/main.js'];
|
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'css/guide.css', 'css/progress.css', 'icons/icon.svg', 'js/main.js'];
|
||||||
|
|
||||||
@@ -16,7 +22,7 @@ self.addEventListener('activate', (event) => {
|
|||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
caches
|
caches
|
||||||
.keys()
|
.keys()
|
||||||
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key))))
|
.then((keys) => Promise.all(keys.filter((key) => ![CACHE_VERSION, AUDIO_CACHE, PYODIDE_CACHE].includes(key)).map((key) => caches.delete(key))))
|
||||||
.then(() => self.clients.claim()),
|
.then(() => self.clients.claim()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -32,18 +38,28 @@ self.addEventListener('fetch', (event) => {
|
|||||||
if (isAuthorTool(url.pathname)) {
|
if (isAuthorTool(url.pathname)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Pyodide (versionné, immuable, lourd) : cache d'abord. Tout le reste (code, niveaux, audio) :
|
// Pyodide (versionné, immuable, lourd) et narration (nommée d'après son contenu) : cache d'abord, dans leurs
|
||||||
// réseau d'abord, cache en repli hors ligne — jamais de code périmé servi en ligne.
|
// caches durables. Tout le reste (code, niveaux) : réseau d'abord, cache en repli hors ligne — jamais de code
|
||||||
const immutable = url.pathname.startsWith('/vendor/pyodide/');
|
// périmé servi en ligne.
|
||||||
event.respondWith(immutable ? fromCache(request) : fromNetwork(request));
|
if (url.pathname.startsWith('/vendor/pyodide/')) {
|
||||||
|
event.respondWith(fromCache(request, PYODIDE_CACHE));
|
||||||
|
} else if (isNarration(url.pathname)) {
|
||||||
|
event.respondWith(fromCache(request, AUDIO_CACHE));
|
||||||
|
} else {
|
||||||
|
event.respondWith(fromNetwork(request));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function isNarration(pathname) {
|
||||||
|
return /^\/levels\/[^/]+\/audio\/[a-z]+\/[0-9a-f]+\.mp3$/.test(pathname) || /^\/assets\/voice\/[a-z]+\/[0-9a-f]+\.mp3$/.test(pathname);
|
||||||
|
}
|
||||||
|
|
||||||
function isAuthorTool(pathname) {
|
function isAuthorTool(pathname) {
|
||||||
return pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname);
|
return pathname === '/author.html' || pathname === '/css/author.css' || pathname.startsWith('/js/author/') || /^\/js\/i18n\/author\.[a-z]+\.json$/.test(pathname);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fromCache(request) {
|
async function fromCache(request, cacheName) {
|
||||||
const cache = await caches.open(CACHE_VERSION);
|
const cache = await caches.open(cacheName);
|
||||||
const cached = await cache.match(request);
|
const cached = await cache.match(request);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
return cached;
|
return cached;
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ PyQuest aims at **WCAG 2.2 AA**. The **Settings** button opens the following pan
|
|||||||
| Guide character | shows or hides the encouragement bubbles |
|
| Guide character | shows or hides the encouragement bubbles |
|
||||||
| Sound effects / Volume | success and error sounds, can be turned off; "Test the sound" |
|
| Sound effects / Volume | success and error sounds, can be turned off; "Test the sound" |
|
||||||
| Voice / Speed | the "Listen" button of explanations, can be turned off; "Test the voice" |
|
| Voice / Speed | the "Listen" button of explanations, can be turned off; "Test the voice" |
|
||||||
|
| Offline voices | downloads the quality voices so you can hear them without a connection (see below) |
|
||||||
| Author mode | shows the link to the [level editor](../contribute/author-editor.md) |
|
| Author mode | shows the link to the [level editor](../contribute/author-editor.md) |
|
||||||
|
|
||||||
Sound and voice **never** start on their own. No information is conveyed by sound or colour alone: every result is
|
Sound and voice **never** start on their own. No information is conveyed by sound or colour alone: every result is
|
||||||
@@ -43,3 +44,10 @@ badges have their states in text, and the canvas drawing has a description and a
|
|||||||
|
|
||||||
PyQuest is an installable web app (PWA). After a first complete load it works without a connection; your browser
|
PyQuest is an installable web app (PWA). After a first complete load it works without a connection; your browser
|
||||||
may offer to install it.
|
may offer to install it.
|
||||||
|
|
||||||
|
### Offline voices
|
||||||
|
|
||||||
|
The quality voices (Piper) are audio files. The level you open is **preloaded automatically**; for all the others, open
|
||||||
|
**Settings → Offline voices → Download the voices for offline use** (about 4 MB per language, once). Without it, offline,
|
||||||
|
only the excerpts you already listened to remain available and the rest is read by your device's more rudimentary voice.
|
||||||
|
Downloaded voices survive application updates; the download must be redone for the other language if you switch.
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ PyQuest vise le niveau **WCAG 2.2 AA**. Le bouton **Réglages** ouvre le panneau
|
|||||||
| Personnage-guide | affiche ou masque les bulles d'encouragement |
|
| Personnage-guide | affiche ou masque les bulles d'encouragement |
|
||||||
| Effets sonores / Volume | sons de réussite et d'erreur, désactivables ; « Tester le son » |
|
| Effets sonores / Volume | sons de réussite et d'erreur, désactivables ; « Tester le son » |
|
||||||
| Voix / Vitesse | bouton « Écouter » des explications, désactivable ; « Tester la voix » |
|
| Voix / Vitesse | bouton « Écouter » des explications, désactivable ; « Tester la voix » |
|
||||||
|
| Voix hors ligne | télécharge les voix de qualité pour les entendre sans connexion (voir ci-dessous) |
|
||||||
| Mode auteur | affiche le lien vers l'[éditeur de niveaux](../contribute/author-editor.md) |
|
| Mode auteur | affiche le lien vers l'[éditeur de niveaux](../contribute/author-editor.md) |
|
||||||
|
|
||||||
Le son et la voix ne démarrent **jamais** tout seuls. Aucune information n'est transmise uniquement par le son ou
|
Le son et la voix ne démarrent **jamais** tout seuls. Aucune information n'est transmise uniquement par le son ou
|
||||||
@@ -44,3 +45,11 @@ progression et les badges ont leurs états en texte, le dessin du canvas a une d
|
|||||||
|
|
||||||
PyQuest est une application web installable (PWA). Après un premier chargement complet, elle fonctionne sans
|
PyQuest est une application web installable (PWA). Après un premier chargement complet, elle fonctionne sans
|
||||||
connexion ; le navigateur peut te proposer de l'installer.
|
connexion ; le navigateur peut te proposer de l'installer.
|
||||||
|
|
||||||
|
### Les voix hors ligne
|
||||||
|
|
||||||
|
Les voix de qualité (Piper) sont des fichiers audio. Le niveau que tu ouvres est **préchargé automatiquement** ; pour tous
|
||||||
|
les autres, ouvre **Réglages → Voix hors ligne → Télécharger les voix pour le hors ligne** (environ 4 Mo par langue, une
|
||||||
|
seule fois). Sans cela, hors connexion, seuls les extraits déjà écoutés restent disponibles et le reste est lu par la
|
||||||
|
voix de ton appareil, plus rudimentaire. Les voix téléchargées survivent aux mises à jour de l'application ; le
|
||||||
|
téléchargement est à refaire pour l'autre langue si tu en changes.
|
||||||
|
|||||||
@@ -68,6 +68,8 @@ def main() -> int:
|
|||||||
precache = shell_files()
|
precache = shell_files()
|
||||||
worker = DIST / "service-worker.js"
|
worker = DIST / "service-worker.js"
|
||||||
source = worker.read_text(encoding="utf-8")
|
source = worker.read_text(encoding="utf-8")
|
||||||
|
pyodide_version = (pyodide / ".version").read_text(encoding="utf-8").strip() if (pyodide / ".version").exists() else "dev"
|
||||||
|
source = re.sub(r"const PYODIDE_CACHE = '[^']*';", f"const PYODIDE_CACHE = 'pyquest-pyodide-{pyodide_version}';", source)
|
||||||
source, shell_count = re.subn(r"const SHELL = \[.*?\];", f"const SHELL = {json.dumps(precache)};", source, flags=re.S)
|
source, shell_count = re.subn(r"const SHELL = \[.*?\];", f"const SHELL = {json.dumps(precache)};", source, flags=re.S)
|
||||||
source, version_count = re.subn(
|
source, version_count = re.subn(
|
||||||
r"const CACHE_VERSION = '[^']*';", f"const CACHE_VERSION = 'pyquest-{content_hash(precache)}';", source
|
r"const CACHE_VERSION = '[^']*';", f"const CACHE_VERSION = 'pyquest-{content_hash(precache)}';", source
|
||||||
|
|||||||
@@ -206,6 +206,59 @@ test('narration : fichier Piper lu jusqu\'au bout (politique autoplay par défau
|
|||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('voix hors ligne : télécharger les narrations Piper puis les écouter sans connexion', { skip, timeout: 180000 }, async () => {
|
||||||
|
const context = await browser.newContext();
|
||||||
|
const page = await context.newPage();
|
||||||
|
const errors = [];
|
||||||
|
page.on('pageerror', (error) => errors.push(error.message));
|
||||||
|
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', () => {
|
||||||
|
if (this.src.startsWith('blob:')) window.__audio.ended += 1; // lecture d'un fichier Piper (pas la voix système)
|
||||||
|
});
|
||||||
|
this.addEventListener('error', () => (window.__audio.errors += 1));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// La voix du système ne doit jamais servir ici : on compte ses lectures.
|
||||||
|
window.__systemVoice = 0;
|
||||||
|
const speak = window.speechSynthesis?.speak?.bind(window.speechSynthesis);
|
||||||
|
if (speak) window.speechSynthesis.speak = (...args) => ((window.__systemVoice += 1), speak(...args));
|
||||||
|
});
|
||||||
|
await page.goto(base);
|
||||||
|
await page.waitForSelector('.explain', { timeout: 60000 });
|
||||||
|
// Le service worker contrôle la page (condition pour servir le cache hors ligne).
|
||||||
|
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 30000 });
|
||||||
|
|
||||||
|
// Réglages : télécharger toutes les voix de la langue.
|
||||||
|
await page.locator('#settings-toggle').click();
|
||||||
|
const group = page.locator('.settings .voices-group');
|
||||||
|
await group.getByRole('button', { name: 'Télécharger les voix pour le hors ligne' }).click();
|
||||||
|
await group.locator('.voices-message').getByText(/Voix téléchargées/).waitFor({ timeout: 90000 });
|
||||||
|
const status = await group.locator('.voices-status').textContent();
|
||||||
|
const [, cached, total] = status.match(/(\d+) voix sur (\d+)/) ?? [];
|
||||||
|
assert.ok(Number(total) > 40 && cached === total, `toutes les voix du français sont en cache : ${status}`);
|
||||||
|
assert.equal(await group.getByRole('button', { name: 'Télécharger les voix pour le hors ligne' }).isDisabled(), true);
|
||||||
|
await page.locator('.drawer-right .drawer-close').click();
|
||||||
|
await page.locator('.drawer-right.is-open').waitFor({ state: 'hidden' });
|
||||||
|
|
||||||
|
// Hors connexion : un niveau lointain se lit avec la voix Piper (fichier du cache), pas avec la synthèse système.
|
||||||
|
await context.setOffline(true);
|
||||||
|
await page.evaluate(() => (location.hash = '#/levels/09-dicts'));
|
||||||
|
await page.waitForFunction(() => document.querySelector('#level-current')?.textContent.includes('Niveau 10'), null, { timeout: 30000 });
|
||||||
|
const listen = page.locator('.explain .voice-button').first();
|
||||||
|
await listen.waitFor({ state: 'visible' });
|
||||||
|
await listen.click();
|
||||||
|
await page.waitForFunction(() => window.__audio.ended >= 1, null, { timeout: 30000 });
|
||||||
|
assert.equal(await page.evaluate(() => window.__systemVoice), 0, 'la voix du système ne doit pas avoir servi');
|
||||||
|
assert.equal(await page.evaluate(() => window.__audio.errors), 0);
|
||||||
|
assert.doesNotMatch(await page.textContent('.toast-region'), /Impossible de lire/);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
test('niveau 07 : boucle while avec plusieurs saisies successives dans l\'interface', { skip, timeout: 120000 }, async () => {
|
test('niveau 07 : boucle while avec plusieurs saisies successives dans l\'interface', { skip, timeout: 120000 }, async () => {
|
||||||
const page = await (await browser.newContext()).newPage();
|
const page = await (await browser.newContext()).newPage();
|
||||||
const errors = [];
|
const errors = [];
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert';
|
||||||
|
import { OfflineVoices, AUDIO_CACHE } from '../../app/js/core/OfflineVoices.js';
|
||||||
|
|
||||||
|
// Faux CacheStorage minimal : match/put par URL.
|
||||||
|
function fakeCaches() {
|
||||||
|
const stores = new Map();
|
||||||
|
return {
|
||||||
|
stores,
|
||||||
|
open: async (name) => {
|
||||||
|
if (!stores.has(name)) stores.set(name, new Map());
|
||||||
|
const store = stores.get(name);
|
||||||
|
return { match: async (url) => store.get(String(url)), put: async (url, response) => void store.set(String(url), response) };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifests = {
|
||||||
|
'00-intro': { fr: { aaa: {}, bbb: {} }, en: { ccc: {} } },
|
||||||
|
'01-hello': { fr: { ddd: {} } },
|
||||||
|
'02-none': {},
|
||||||
|
};
|
||||||
|
|
||||||
|
function server({ failUrls = [], offline = false } = {}) {
|
||||||
|
const calls = [];
|
||||||
|
const fetchFn = async (input) => {
|
||||||
|
const url = String(input);
|
||||||
|
calls.push(url);
|
||||||
|
if (offline) throw new TypeError('offline');
|
||||||
|
const id = url.match(/levels\/([^/]+)\/audio\/manifest\.json$/)?.[1];
|
||||||
|
if (id) return id in manifests ? new Response(JSON.stringify(manifests[id])) : new Response('', { status: 404 });
|
||||||
|
if (failUrls.some((bad) => url.endsWith(bad))) return new Response('', { status: 500 });
|
||||||
|
return new Response('mp3');
|
||||||
|
};
|
||||||
|
return { fetchFn, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
const levelsUrl = 'https://x.test/levels/';
|
||||||
|
const ids = ['00-intro', '01-hello', '02-none', '99-missing'];
|
||||||
|
|
||||||
|
test('les URLs viennent des manifestes, par langue ; niveaux sans voix ou inconnus ignorés', async () => {
|
||||||
|
const { fetchFn } = server();
|
||||||
|
const voices = new OfflineVoices({ levelsUrl, fetchFn, cachesApi: fakeCaches() });
|
||||||
|
assert.deepEqual(await voices.urlsFor(ids, 'fr'), [
|
||||||
|
'https://x.test/levels/00-intro/audio/fr/aaa.mp3',
|
||||||
|
'https://x.test/levels/00-intro/audio/fr/bbb.mp3',
|
||||||
|
'https://x.test/levels/01-hello/audio/fr/ddd.mp3',
|
||||||
|
]);
|
||||||
|
assert.deepEqual(await voices.urlsFor(ids, 'en'), ['https://x.test/levels/00-intro/audio/en/ccc.mp3']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('télécharger remplit le cache audio, avec progression ; seul ce qui manque est téléchargé', async () => {
|
||||||
|
const caches = fakeCaches();
|
||||||
|
const { fetchFn, calls } = server();
|
||||||
|
const voices = new OfflineVoices({ levelsUrl, fetchFn, cachesApi: caches });
|
||||||
|
assert.deepEqual(await voices.status(ids, 'fr'), { total: 3, cached: 0 });
|
||||||
|
const progress = [];
|
||||||
|
const result = await voices.download(ids, 'fr', { onProgress: (done, total) => progress.push([done, total]) });
|
||||||
|
assert.deepEqual(result, { total: 3, downloaded: 3, failed: 0 });
|
||||||
|
assert.deepEqual(progress.at(-1), [3, 3]);
|
||||||
|
assert.equal(caches.stores.get(AUDIO_CACHE).size, 3);
|
||||||
|
assert.deepEqual(await voices.status(ids, 'fr'), { total: 3, cached: 3 });
|
||||||
|
|
||||||
|
const mp3Before = calls.filter((url) => url.endsWith('.mp3')).length;
|
||||||
|
assert.deepEqual(await voices.download(ids, 'fr'), { total: 3, downloaded: 0, failed: 0 });
|
||||||
|
assert.equal(calls.filter((url) => url.endsWith('.mp3')).length, mp3Before, 'rien de retéléchargé');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un échec isolé est compté sans bloquer les autres ; hors ligne, tout échoue proprement', async () => {
|
||||||
|
const caches = fakeCaches();
|
||||||
|
const voices = new OfflineVoices({ levelsUrl, fetchFn: server({ failUrls: ['bbb.mp3'] }).fetchFn, cachesApi: caches });
|
||||||
|
assert.deepEqual(await voices.download(ids, 'fr'), { total: 3, downloaded: 2, failed: 1 });
|
||||||
|
assert.equal(caches.stores.get(AUDIO_CACHE).size, 2);
|
||||||
|
// Relancer ne réessaie que le fichier manquant.
|
||||||
|
const retry = new OfflineVoices({ levelsUrl, fetchFn: server().fetchFn, cachesApi: caches });
|
||||||
|
assert.deepEqual(await retry.download(ids, 'fr'), { total: 3, downloaded: 1, failed: 0 });
|
||||||
|
|
||||||
|
const offline = new OfflineVoices({ levelsUrl, fetchFn: server({ offline: true }).fetchFn, cachesApi: fakeCaches() });
|
||||||
|
assert.deepEqual(await offline.download(ids, 'fr'), { total: 0, downloaded: 0, failed: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('annulation : plus aucun téléchargement après abort', async () => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const { fetchFn, calls } = server();
|
||||||
|
const voices = new OfflineVoices({ levelsUrl, fetchFn, cachesApi: fakeCaches() });
|
||||||
|
controller.abort();
|
||||||
|
const result = await voices.download(ids, 'fr', { signal: controller.signal });
|
||||||
|
assert.equal(result.downloaded, 0);
|
||||||
|
assert.equal(calls.filter((url) => url.endsWith('.mp3')).length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sans API Cache : non pris en charge, aucune erreur', async () => {
|
||||||
|
const voices = new OfflineVoices({ levelsUrl, fetchFn: server().fetchFn, cachesApi: undefined });
|
||||||
|
assert.equal(voices.supported, false);
|
||||||
|
assert.deepEqual(await voices.status(ids, 'fr'), { total: 3, cached: 0 });
|
||||||
|
assert.deepEqual(await voices.download(ids, 'fr'), { total: 3, downloaded: 0, failed: 3 });
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user