Add ErrorTranslator with fr/en error catalogs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:05:58 +02:00
parent f91f5856f7
commit 2a8ae21e78
4 changed files with 389 additions and 1 deletions
+1 -1
View File
@@ -46,7 +46,7 @@ Le brief original est [`prompt-pyquest.md`](prompt-pyquest.md) (résumé fidèle
4. ✅ FAIT — `app/js/core/LessonEngine.js` + `LevelSession.js` + `app/js/lib/js-yaml` — charge `manifest.json` + `level.yaml`, expose les steps.
5. ✅ FAIT — `app/js/core/ValidationEngine.js` — interprète les `tests[].kind` du schéma (stdout_equals,
var_equals, etc.) de façon agnostique au contenu.
6. `app/js/core/ErrorTranslator.js` — traduit les tracebacks Python en messages simples fr/en
6. ✅ FAIT — `app/js/core/ErrorTranslator.js` + `app/js/i18n/errors.{fr,en}.json` — traduit les tracebacks Python en messages simples fr/en
(cf. ton de l'exemple 2 du brief).
7. `app/js/core/ProgressStore.js` — IndexedDB (XP, badges, streaks, niveaux complétés) + export/import.
8. `app/js/core/AudioEngine.js` + `app/js/core/VoiceEngine.js` — effets sonores et
+84
View File
@@ -0,0 +1,84 @@
// Traduit une erreur Python (type + message) en explication simple, fr/en.
// La logique de reconnaissance est ici ; les textes sont dans app/js/i18n/errors.<lang>.json.
// Règles ordonnées : première correspondance gagnante. `params` nomme les groupes capturés.
const RULES = [
{ type: 'NameError', pattern: /name '(.+)' is not defined/, key: 'NameError', params: ['name'] },
{ type: 'UnboundLocalError', pattern: /local variable '(.+?)'/, key: 'UnboundLocalError', params: ['name'] },
{ type: 'SyntaxError', pattern: /unterminated (?:triple-quoted )?string literal/, key: 'SyntaxError.unterminated_string' },
{ type: 'SyntaxError', pattern: /'(.)' was never closed/, key: 'SyntaxError.never_closed', params: ['char'] },
{ type: 'SyntaxError', pattern: /unmatched '(.)'/, key: 'SyntaxError.unmatched', params: ['char'] },
{ type: 'SyntaxError', pattern: /expected ':'/, key: 'SyntaxError.expected_colon' },
{ type: 'SyntaxError', pattern: /Missing parentheses in call to 'print'/, key: 'SyntaxError.print_parens' },
{ type: 'SyntaxError', pattern: /Perhaps you forgot a comma/, key: 'SyntaxError.forgot_comma' },
{ type: 'SyntaxError', pattern: /invalid decimal literal/, key: 'SyntaxError.invalid_number' },
{ type: 'IndentationError', pattern: /expected an indented block/, key: 'IndentationError.expected_block' },
{ type: 'TypeError', pattern: /unsupported operand type\(s\) for (.+?): '(.+?)' and '(.+?)'/, key: 'TypeError.operand', params: ['op', 'left', 'right'] },
{ type: 'TypeError', pattern: /can only concatenate str \(not "(.+?)"\) to str/, key: 'TypeError.concat', params: ['other'] },
{ type: 'TypeError', pattern: /'(.+?)' object is not callable/, key: 'TypeError.not_callable', params: ['type'] },
{ type: 'TypeError', pattern: /(\w+)\(\) takes (.+?) positional arguments? but (\d+) (?:was|were) given/, key: 'TypeError.arg_count', params: ['fn', 'expected', 'given'] },
{ type: 'TypeError', pattern: /(\w+)\(\) missing (\d+) required positional arguments?/, key: 'TypeError.missing_arg', params: ['fn', 'count'] },
{ type: 'ValueError', pattern: /invalid literal for int\(\) with base 10: (.+)/, key: 'ValueError.invalid_int', params: ['value'] },
{ type: 'ValueError', pattern: /could not convert string to float: (.+)/, key: 'ValueError.invalid_float', params: ['value'] },
{ type: 'AttributeError', pattern: /'(.+?)' object has no attribute '(.+?)'/, key: 'AttributeError', params: ['type', 'attr'] },
{ type: 'ModuleNotFoundError', pattern: /No module named '(.+?)'/, key: 'ModuleNotFoundError', params: ['module'] },
{ type: 'KeyError', pattern: /^(.*)$/s, key: 'KeyError', params: ['key'] },
];
export class ErrorTranslator {
#catalogs;
#defaultLang;
/**
* @param {Record<string, Record<string, {title: string, explanation: string, tip: string}>>} catalogs
* Catalogues par langue (contenu de errors.fr.json, errors.en.json).
* @param {string} [defaultLang]
*/
constructor(catalogs, defaultLang = 'fr') {
this.#catalogs = catalogs;
this.#defaultLang = defaultLang;
}
/**
* @param {{type: string, message: string, lineno: number|null, traceback: string}} error
* @param {string} [lang]
* @returns {{type: string, title: string, explanation: string, tip: string, line: number|null, traceback: string}}
*/
translate(error, lang = this.#defaultLang) {
const catalog = this.#catalogs[lang] ?? this.#catalogs[this.#defaultLang];
const { key, params } = this.#match(error, catalog);
const entry = catalog[key];
return {
type: error.type,
title: this.#format(entry.title, params),
explanation: this.#format(entry.explanation, params),
tip: this.#format(entry.tip, params),
line: error.lineno ?? null,
// Traceback brut conservé pour l'affichage « voir le détail technique ».
traceback: error.traceback ?? '',
};
}
#match(error, catalog) {
const message = error.message ?? '';
for (const rule of RULES) {
if (rule.type !== error.type) {
continue;
}
const found = rule.pattern.exec(message);
if (found && catalog[rule.key]) {
const params = Object.fromEntries((rule.params ?? []).map((name, i) => [name, found[i + 1]]));
return { key: rule.key, params };
}
}
if (catalog[error.type]) {
return { key: error.type, params: {} };
}
// Type d'erreur sans traduction dédiée : message générique avec le texte brut de Python.
return { key: 'Unknown', params: { type: error.type, message } };
}
#format(template, params) {
return template.replace(/\{(\w+)\}/g, (whole, name) => params[name] ?? whole);
}
}
+152
View File
@@ -0,0 +1,152 @@
{
"NameError": {
"title": "Python doesn't know \"{name}\"",
"explanation": "You are using the name {name}, but it has not been created yet at this point.",
"tip": "Check the spelling (capital letters count) and make sure you wrote {name} = ... before using it. To show text, put it between quotes."
},
"UnboundLocalError": {
"title": "The variable \"{name}\" is used too early",
"explanation": "Python found {name} in a function before it was given a value.",
"tip": "Give {name} a value before reading it."
},
"SyntaxError": {
"title": "Python doesn't understand this line",
"explanation": "The sentence is badly written: a symbol is missing or there is one too many.",
"tip": "Reread the line shown, and the one before it too: quotes, parentheses and colons are the usual causes."
},
"SyntaxError.unterminated_string": {
"title": "A text is not closed",
"explanation": "You opened a quote but never closed it.",
"tip": "Add the missing quote at the end of the text."
},
"SyntaxError.never_closed": {
"title": "A closing \"{char}\" is missing",
"explanation": "You opened a \"{char}\" that is never closed.",
"tip": "Count the opening and closing symbols: there must be as many of each."
},
"SyntaxError.unmatched": {
"title": "An extra \"{char}\"",
"explanation": "You close a \"{char}\" that was never opened.",
"tip": "Remove it, or add the matching opening symbol."
},
"SyntaxError.expected_colon": {
"title": "A colon \":\" is missing",
"explanation": "This line must end with \":\" to announce the block that follows.",
"tip": "Add \":\" at the end of the line."
},
"SyntaxError.print_parens": {
"title": "print() is written with parentheses",
"explanation": "In Python 3, the text to show goes between parentheses.",
"tip": "Write print(\"your text\")."
},
"SyntaxError.forgot_comma": {
"title": "A comma may be missing",
"explanation": "Two items follow each other without a separator.",
"tip": "Add a comma between the items of a list or a call."
},
"SyntaxError.invalid_number": {
"title": "This number is badly written",
"explanation": "A number cannot be directly followed by letters.",
"tip": "To multiply, write 2 * x. For text, use quotes."
},
"IndentationError": {
"title": "The indentation of this line is wrong",
"explanation": "In Python, the spaces at the start of a line matter: they show which block it belongs to.",
"tip": "Align this line with the others of the same block, using 4 spaces."
},
"IndentationError.expected_block": {
"title": "An indented block is missing",
"explanation": "After a line ending with \":\", the next line must be shifted by 4 spaces.",
"tip": "Add 4 spaces at the start of the following line."
},
"TypeError": {
"title": "These values don't go together",
"explanation": "You are trying an operation on types that are not compatible.",
"tip": "Check each value's type with type(), and convert if needed with int(), float() or str()."
},
"TypeError.operand": {
"title": "Cannot do \"{op}\" between {left} and {right}",
"explanation": "A {left} and a {right} cannot be combined with \"{op}\".",
"tip": "Convert one of the values: int() or float() for a number, str() for text."
},
"TypeError.concat": {
"title": "You cannot glue text and a {other} together",
"explanation": "\"+\" glues texts together, but one of the values here is a {other}.",
"tip": "Turn it into text with str(), or separate the values with commas in print()."
},
"TypeError.not_callable": {
"title": "A {type} is not called like a function",
"explanation": "Parentheses right after a name mean \"call a function\", but this name holds a {type}.",
"tip": "Remove the parentheses, or check that you did not reuse a function's name for a variable."
},
"TypeError.arg_count": {
"title": "{fn}() did not get the right number of values",
"explanation": "{fn}() expects {expected}, and you gave {given}.",
"tip": "Count the values between the parentheses of the call."
},
"TypeError.missing_arg": {
"title": "{fn}() got too few values",
"explanation": "{count} required value(s) are missing in the call to {fn}().",
"tip": "Compare the call with the function's definition: each parameter expects a value."
},
"ValueError": {
"title": "This value is not acceptable here",
"explanation": "The type is right, but the content does not suit this operation.",
"tip": "Check what the value contains with print()."
},
"ValueError.invalid_int": {
"title": "{value} is not a whole number",
"explanation": "int() can only convert text that looks like a whole number, such as \"42\".",
"tip": "Check there are no letters, comma or spaces in the text."
},
"ValueError.invalid_float": {
"title": "{value} is not a number",
"explanation": "float() can only convert text such as \"3.14\".",
"tip": "Use a dot, not a comma, for decimals."
},
"ZeroDivisionError": {
"title": "You cannot divide by zero",
"explanation": "A division whose divisor is 0 has no result.",
"tip": "Check the value you divide by."
},
"IndexError": {
"title": "This position does not exist in the list",
"explanation": "You ask for an item beyond the end of the list. Positions start at 0.",
"tip": "A list of 3 items has positions 0, 1 and 2. Check with len()."
},
"KeyError": {
"title": "The key {key} does not exist",
"explanation": "The dictionary does not contain this key.",
"tip": "Check the key's spelling, or test it with \"in\" before reading it."
},
"AttributeError": {
"title": "A {type} has no \"{attr}\"",
"explanation": "You ask a {type} for something it cannot do or does not have.",
"tip": "Check the spelling of {attr}, and the type of the value."
},
"ModuleNotFoundError": {
"title": "The module \"{module}\" cannot be found",
"explanation": "Python finds no module with this name.",
"tip": "Check the spelling of the import. Some modules are not available in the browser."
},
"KeyboardInterrupt": {
"title": "Execution stopped",
"explanation": "The program was interrupted before it finished.",
"tip": "If it was an endless loop, check that its condition becomes false at some point."
},
"EOFError": {
"title": "The program is waiting for input",
"explanation": "input() asks the user for a value, which is not possible in this cell.",
"tip": "Replace input() with a value written directly in the code."
},
"RecursionError": {
"title": "A function calls itself endlessly",
"explanation": "Python stopped the program because the function calls itself too many times.",
"tip": "Add a stopping condition to the function."
},
"Unknown": {
"title": "An error occurred: {type}",
"explanation": "Message from Python: {message}",
"tip": "Reread the line shown and compare it with the level's examples."
}
}
+152
View File
@@ -0,0 +1,152 @@
{
"NameError": {
"title": "Python ne connaît pas « {name} »",
"explanation": "Tu utilises le nom {name}, mais il n'a pas encore été créé à cet endroit.",
"tip": "Vérifie l'orthographe (majuscules comprises) et assure-toi d'avoir écrit {name} = ... avant de l'utiliser. Pour afficher du texte, mets-le entre guillemets."
},
"UnboundLocalError": {
"title": "La variable « {name} » est utilisée trop tôt",
"explanation": "Python a trouvé {name} dans une fonction avant qu'une valeur ne lui soit donnée.",
"tip": "Donne une valeur à {name} avant de la lire."
},
"SyntaxError": {
"title": "Python ne comprend pas cette ligne",
"explanation": "La phrase est mal écrite : il manque ou il y a en trop un symbole.",
"tip": "Relis la ligne indiquée, et regarde aussi celle d'avant : guillemets, parenthèses et deux-points sont les causes habituelles."
},
"SyntaxError.unterminated_string": {
"title": "Un texte n'est pas fermé",
"explanation": "Tu as ouvert un guillemet mais tu ne l'as pas refermé.",
"tip": "Ajoute le guillemet manquant à la fin du texte."
},
"SyntaxError.never_closed": {
"title": "Il manque un « {char} » fermant",
"explanation": "Tu as ouvert un « {char} » qui n'est jamais refermé.",
"tip": "Compte les ouvrants et les fermants : il doit y en avoir autant."
},
"SyntaxError.unmatched": {
"title": "Un « {char} » est en trop",
"explanation": "Tu fermes un « {char} » qui n'a jamais été ouvert.",
"tip": "Supprime-le, ou ajoute le symbole ouvrant correspondant."
},
"SyntaxError.expected_colon": {
"title": "Il manque un deux-points « : »",
"explanation": "Cette ligne doit se terminer par « : » pour annoncer le bloc qui suit.",
"tip": "Ajoute « : » à la fin de la ligne."
},
"SyntaxError.print_parens": {
"title": "print() s'écrit avec des parenthèses",
"explanation": "En Python 3, le texte à afficher se place entre parenthèses.",
"tip": "Écris print(\"ton texte\")."
},
"SyntaxError.forgot_comma": {
"title": "Il manque peut-être une virgule",
"explanation": "Deux éléments se suivent sans séparateur.",
"tip": "Ajoute une virgule entre les éléments d'une liste ou d'un appel."
},
"SyntaxError.invalid_number": {
"title": "Ce nombre est mal écrit",
"explanation": "Un nombre ne peut pas être directement suivi de lettres.",
"tip": "Pour multiplier, écris 2 * x. Pour du texte, utilise des guillemets."
},
"IndentationError": {
"title": "Le décalage de cette ligne est incorrect",
"explanation": "En Python, les espaces au début d'une ligne comptent : ils indiquent quel bloc elle appartient.",
"tip": "Aligne cette ligne avec les autres du même bloc, avec 4 espaces."
},
"IndentationError.expected_block": {
"title": "Il manque un bloc indenté",
"explanation": "Après la ligne qui se termine par « : », la ligne suivante doit être décalée de 4 espaces.",
"tip": "Ajoute 4 espaces au début de la ligne qui suit."
},
"TypeError": {
"title": "Ces valeurs ne vont pas ensemble",
"explanation": "Tu essaies de faire une opération sur des types qui ne sont pas compatibles.",
"tip": "Vérifie le type de chaque valeur avec type(), et convertis si besoin avec int(), float() ou str()."
},
"TypeError.operand": {
"title": "Impossible de faire « {op} » entre {left} et {right}",
"explanation": "Un {left} et un {right} ne peuvent pas être combinés avec « {op} ».",
"tip": "Convertis l'une des valeurs : int(), float() pour un nombre, str() pour du texte."
},
"TypeError.concat": {
"title": "On ne peut pas coller un texte et un {other}",
"explanation": "Le « + » colle des textes entre eux, mais là une des valeurs est de type {other}.",
"tip": "Transforme-la en texte avec str(), ou sépare les valeurs par des virgules dans print()."
},
"TypeError.not_callable": {
"title": "Un {type} ne s'appelle pas comme une fonction",
"explanation": "Les parenthèses juste après un nom signifient « appeler une fonction », mais ce nom contient un {type}.",
"tip": "Retire les parenthèses, ou vérifie que tu n'as pas réutilisé le nom d'une fonction pour une variable."
},
"TypeError.arg_count": {
"title": "{fn}() n'a pas reçu le bon nombre de valeurs",
"explanation": "{fn}() en attend {expected}, et tu en as donné {given}.",
"tip": "Compte les valeurs entre les parenthèses de l'appel."
},
"TypeError.missing_arg": {
"title": "{fn}() a reçu trop peu de valeurs",
"explanation": "Il manque {count} valeur(s) obligatoire(s) dans l'appel de {fn}().",
"tip": "Compare l'appel avec la définition de la fonction : chaque paramètre attend une valeur."
},
"ValueError": {
"title": "La valeur n'est pas acceptable ici",
"explanation": "Le type est bon, mais le contenu ne convient pas à cette opération.",
"tip": "Vérifie ce que contient la valeur avec print()."
},
"ValueError.invalid_int": {
"title": "{value} n'est pas un nombre entier",
"explanation": "int() ne sait convertir que du texte qui ressemble à un nombre entier, comme \"42\".",
"tip": "Vérifie qu'il n'y a ni lettres, ni virgule, ni espace dans le texte."
},
"ValueError.invalid_float": {
"title": "{value} n'est pas un nombre",
"explanation": "float() ne sait convertir que du texte comme \"3.14\".",
"tip": "Utilise un point et non une virgule pour les décimales."
},
"ZeroDivisionError": {
"title": "On ne peut pas diviser par zéro",
"explanation": "Une division dont le diviseur vaut 0 n'a pas de résultat.",
"tip": "Vérifie la valeur par laquelle tu divises."
},
"IndexError": {
"title": "Cette position n'existe pas dans la liste",
"explanation": "Tu demandes un élément plus loin que la fin de la liste. Les positions commencent à 0.",
"tip": "Une liste de 3 éléments a les positions 0, 1 et 2. Vérifie avec len()."
},
"KeyError": {
"title": "La clé {key} n'existe pas",
"explanation": "Le dictionnaire ne contient pas cette clé.",
"tip": "Vérifie l'orthographe de la clé, ou teste-la avec « in » avant de la lire."
},
"AttributeError": {
"title": "Un {type} n'a pas de « {attr} »",
"explanation": "Tu demandes à un {type} quelque chose qu'il ne sait pas faire ou ne possède pas.",
"tip": "Vérifie l'orthographe de {attr}, ainsi que le type de la valeur."
},
"ModuleNotFoundError": {
"title": "Le module « {module} » est introuvable",
"explanation": "Python ne trouve pas de module de ce nom.",
"tip": "Vérifie l'orthographe de l'import. Certains modules ne sont pas disponibles dans le navigateur."
},
"KeyboardInterrupt": {
"title": "Exécution arrêtée",
"explanation": "Le programme a été interrompu avant d'être terminé.",
"tip": "Si c'était une boucle sans fin, vérifie que sa condition devient fausse à un moment."
},
"EOFError": {
"title": "Le programme attend une saisie",
"explanation": "input() demande une valeur à l'utilisateur, ce qui n'est pas possible dans cette cellule.",
"tip": "Remplace input() par une valeur écrite directement dans le code."
},
"RecursionError": {
"title": "Une fonction s'appelle elle-même sans fin",
"explanation": "Python a arrêté le programme car la fonction se rappelle trop de fois.",
"tip": "Ajoute une condition d'arrêt à la fonction."
},
"Unknown": {
"title": "Une erreur est survenue : {type}",
"explanation": "Message de Python : {message}",
"tip": "Relis la ligne indiquée et compare-la avec les exemples du niveau."
}
}