Thomas-PEYROT/japanese-webtranslate / tools / build-dict.js
#!/usr/bin/env node
/**
* Génère data/jmdict.json à partir des exports JSON de jmdict-simplified.
*
* Usage :
* node tools/build-dict.js <jmdict-fre.json> <jmdict-eng.json> [sortie.json]
*
* - Le dictionnaire français est utilisé en priorité (toutes les entrées).
* - L'anglais sert de repli pour les mots absents du français,
* en ne gardant que les entrées marquées "common".
*
* Format de sortie :
* { "表面形": ["lecture"|null, "glose1", "glose2", ...] }
* La clé est chaque forme kanji et chaque forme kana de l'entrée.
*/
const fs = require("fs");
const path = require("path");
const MAX_GLOSSES = 4;
function pickReading(word, kanjiText) {
const kanas = word.kana;
if (kanjiText == null) {
return null; // clé kana : la lecture est la clé elle-même
}
// Kana commun applicable en priorité, sinon premier kana applicable
const applicable = kanas.filter(
(k) => k.appliesToKanji.includes("*") || k.appliesToKanji.includes(kanjiText)
);
const common = applicable.find((k) => k.common);
return (common || applicable[0] || kanas[0] || {}).text || null;
}
function glosses(word) {
const out = [];
for (const sense of word.sense) {
for (const g of sense.gloss) {
out.push(g.text);
if (out.length >= MAX_GLOSSES) return out;
}
}
return out;
}
function addWord(dict, word) {
const g = glosses(word);
if (g.length === 0) return;
for (const kanji of word.kanji) {
if (!(kanji.text in dict)) {
dict[kanji.text] = [pickReading(word, kanji.text), ...g];
}
}
// Formes kana indexées aussi (ex. する pour l'entrée 為る) :
// la surface form renvoyée par kuromoji est souvent la forme kana.
for (const kana of word.kana) {
if (!(kana.text in dict)) {
dict[kana.text] = [null, ...g];
}
}
}
function isCommon(word) {
return word.kanji.some((k) => k.common) || word.kana.some((k) => k.common);
}
function main() {
const [frePath, engPath, outPath = "data/jmdict.json"] = process.argv.slice(2);
if (!frePath || !engPath) {
console.error("Usage: node tools/build-dict.js <jmdict-fre.json> <jmdict-eng.json> [sortie.json]");
process.exit(1);
}
const dict = {};
const fre = JSON.parse(fs.readFileSync(frePath, "utf8"));
for (const word of fre.words) addWord(dict, word);
const afterFre = Object.keys(dict).length;
const eng = JSON.parse(fs.readFileSync(engPath, "utf8"));
let engKept = 0;
for (const word of eng.words) {
if (isCommon(word)) {
const before = Object.keys(dict).length;
addWord(dict, word);
if (Object.keys(dict).length > before) engKept++;
}
}
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, JSON.stringify(dict));
const sizeMb = (fs.statSync(outPath).size / 1024 / 1024).toFixed(1);
console.log(`Clés FR : ${afterFre}, entrées EN conservées : ${engKept}`);
console.log(`Total : ${Object.keys(dict).length} clés → ${outPath} (${sizeMb} Mo)`);
}
main();