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:
denis
2026-10-17 14:50:06 +02:00
parent 3f10adb36b
commit 5d2cc0eedf
13 changed files with 431 additions and 9 deletions
+122
View File
@@ -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
View File
@@ -138,5 +138,12 @@
"drawing.color.blue": "blue",
"drawing.color.orange": "orange",
"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
View File
@@ -138,5 +138,12 @@
"drawing.color.blue": "bleu",
"drawing.color.orange": "orange",
"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."
}
+47
View File
@@ -8,6 +8,7 @@ import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStor
import { ProgressStore } from './core/ProgressStore.js';
import { PyodideWorkerClient } from './core/PyodideWorkerClient.js';
import { SettingsStore } from './core/SettingsStore.js';
import { OfflineVoices } from './core/OfflineVoices.js';
import { SyncClient } from './core/SyncClient.js';
import { ValidationEngine } from './core/ValidationEngine.js';
import { VoiceEngine } from './core/VoiceEngine.js';
@@ -60,6 +61,8 @@ class App {
#settings;
#progress;
#sync;
#offlineVoices;
#voicesDownload = null;
#lessons;
#audio;
#voice;
@@ -94,6 +97,7 @@ class App {
this.#sync = new SyncClient({ store, progress: this.#progress, endpoint: new URL('api/sync/', document.baseURI).href });
await this.#sync.load();
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.#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.#sync.addEventListener('change', (event) => this.#panel.setSync(event.detail));
this.#sync.addEventListener('merged', () => this.#renderMap());
this.#panel.addEventListener('voices', () => this.#downloadVoices());
this.#panel.addEventListener('export', () => this.#exportProgress());
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.
await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
this.#registerServiceWorker();
this.#refreshVoiceStatus();
// Synchronisation (si activée) : au démarrage, au retour du réseau et quand l'onglet redevient visible.
this.#sync.start();
window.addEventListener('online', () => this.#sync.sync());
@@ -196,6 +202,7 @@ class App {
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
this.#updateLevelNav(session.title);
await this.#manager.start(session, { greeting });
this.#prefetchLevelVoices(id);
}
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 }) {
const t = (key) => this.#i18n.t(key);
const say = (key) => this.#panel.setSync(this.#sync.state, key ? t(key) : '');
+45
View File
@@ -10,6 +10,8 @@ export class SettingsPanel extends EventTarget {
#syncRoot = el('fieldset', { class: 'setting-group sync-group' });
#syncState = { enabled: false, token: null, status: 'off', error: null, lastSync: null };
#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 */
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.voice', 'checkbox', { value: settings.voiceEnabled, key: 'voiceEnabled' }),
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.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
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,
);
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). */
@@ -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() {
const t = (key, params) => this.#i18n.t(key, params);
const state = this.#syncState;