Repository Public
1import { describe, expect, it } from "vitest";2import { alignmentQuality, alignScript, emphasisCandidates, normalizeToken, pauses, sentenceCues, type AlignedWord } from "../src/media/align";3import { cuesFromAligned, karaokeCues } from "../src/media/captions";4import type { WordTiming } from "../src/lib/contracts";56/** Alignement du script sur les mots entendus : TypeScript pur, aucun réseau, aucun modèle, aucun Python. */78/** Mots entendus fictifs : `per` secondes par mot, collés les uns aux autres sauf blancs explicites (`gaps` : rang → secondes). */9function heardFrom(wordsList: string[], start = 0, per = 0.3, gaps: Record<number, number> = {}): WordTiming[] {10 let t = start;11 return wordsList.map((word, i) => {12 t += gaps[i] ?? 0;13 const w = { word, start: Math.round(t * 1000) / 1000, end: Math.round((t + per) * 1000) / 1000 };14 t += per;15 return w;16 });17}18/** Propriétés garanties quelle que soit l'entrée. */19function expectWellFormed(aligned: AlignedWord[], script: string, window: { start: number; end: number }, min = 0.04) {20 const tokens = script.trim().split(/\s+/);21 expect(aligned.map((w) => w.word)).toEqual(tokens);22 for (const [i, w] of aligned.entries()) {23 expect(w.index).toBe(i);24 expect(Number.isFinite(w.start) && Number.isFinite(w.end), `${w.word} fini`).toBe(true);25 expect(w.start, `${w.word} début dans la fenêtre`).toBeGreaterThanOrEqual(window.start);26 expect(w.end, `${w.word} fin dans la fenêtre`).toBeLessThanOrEqual(window.end + 1e-9);27 expect(w.end, `${w.word} fin > début`).toBeGreaterThan(w.start);28 expect(w.end - w.start, `${w.word} ≥ 40 ms`).toBeGreaterThanOrEqual(min - 0.0011);29 if (i) {30 expect(w.start, `${w.word} croissant`).toBeGreaterThanOrEqual(aligned[i - 1].start);31 expect(w.start, `${w.word} sans chevauchement`).toBeGreaterThanOrEqual(aligned[i - 1].end);32 expect(w.sentence).toBeGreaterThanOrEqual(aligned[i - 1].sentence);33 }34 }35}36/** Générateur pseudo-aléatoire à graine (mulberry32) : les perturbations sont reproductibles. */37function rng(seed: number) {38 let a = seed >>> 0;39 return () => {40 a = (a + 0x6d2b79f5) >>> 0;41 let t = a;42 t = Math.imul(t ^ (t >>> 15), t | 1);43 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);44 return ((t ^ (t >>> 14)) >>> 0) / 4294967296;45 };46}4748describe("alignScript", () => {49 it("normalise accents, élisions, traits d'union, nombres et symboles", () => {50 expect(normalizeToken("L'Électricité,")).toEqual(["l", "electricite"]);51 expect(normalizeToken("quatre-vingt-quatorze")).toEqual(["quatre", "vingt", "quatorze"]);52 expect(normalizeToken("157,63")).toEqual(["157", "63"]);53 expect(normalizeToken("$")).toEqual(["dollars"]);54 expect(normalizeToken("94 %")).toEqual(["94", "pourcent"]);55 expect(normalizeToken("—")).toEqual([]);56 expect(normalizeToken("cœur")).toEqual(["coeur"]);57 });5859 it("correspondance exacte : chaque mot du script reprend les temps entendus, avec sa ponctuation", () => {60 const script = "Bonjour et bienvenue. Le Québec produit son électricité.";61 const heard = heardFrom(["Bonjour", "et", "bienvenue.", "Le", "Québec", "produit", "son", "électricité."], 0.2, 0.3);62 const a = alignScript(script, heard, { start: 0, end: 3 });63 expectWellFormed(a, script, { start: 0, end: 3 });64 expect(a.every((w) => w.confidence === "matched")).toBe(true);65 for (const [i, w] of a.entries()) expect(w).toMatchObject({ start: heard[i].start, end: heard[i].end });66 expect(a.map((w) => w.sentence)).toEqual([0, 0, 0, 1, 1, 1, 1, 1]);67 expect(alignmentQuality(a)).toEqual({ matched: 8, total: 8, ratio: 1 });68 });6970 it("ponctuation et casse de Whisper différentes du script : toujours retrouvé", () => {71 const script = "« Vraiment ? » dit-elle, étonnée.";72 const heard = heardFrom(["vraiment", "dit", "elle", "etonnee"], 0, 0.4);73 const a = alignScript(script, heard, { start: 0, end: 2 });74 expectWellFormed(a, script, { start: 0, end: 2 });75 expect(a.filter((w) => w.confidence === "matched").map((w) => w.word)).toEqual(["Vraiment", "dit-elle,", "étonnée."]);76 const dit = a.find((w) => w.word === "dit-elle,")!; // deux mots entendus pour un mot du script77 expect(dit.end).toBe(1.2);78 expect(dit.start).toBeCloseTo(0.48, 3); // 0,4 s + 40 ms pour chacun des deux signes isolés79 expect(alignmentQuality(a)).toEqual({ matched: 3, total: 3, ratio: 1 }); // les signes isolés ne comptent pas80 });8182 it("mot manqué par Whisper : interpolé entre ses voisins, les autres gardent leurs temps", () => {83 const script = "Le chat noir dort sur le canapé rouge.";84 const heard = heardFrom(["Le", "chat", "dort", "sur", "le", "canapé", "rouge."], 0, 0.3, { 2: 0.3 }); // blanc de 0,3 s à la place de « noir »85 const a = alignScript(script, heard, { start: 0, end: 3 });86 expectWellFormed(a, script, { start: 0, end: 3 });87 const noir = a[2];88 expect(noir).toMatchObject({ word: "noir", confidence: "interpolated", start: 0.6, end: 0.9 });89 expect(a[1]).toMatchObject({ word: "chat", confidence: "matched", start: 0.3, end: 0.6 });90 expect(a[3]).toMatchObject({ word: "dort", confidence: "matched", start: 0.9, end: 1.2 });91 expect(alignmentQuality(a)).toEqual({ matched: 7, total: 8, ratio: 7 / 8 });92 });9394 it("mot manqué sans blanc entre les voisins : l'intervalle des voisins est repartagé", () => {95 const script = "Le chat noir dort.";96 const heard = heardFrom(["Le", "chat", "dort."], 0, 0.4); // « chat » et « dort » se touchent97 const a = alignScript(script, heard, { start: 0, end: 1.2 });98 expectWellFormed(a, script, { start: 0, end: 1.2 });99 expect(a[2].confidence).toBe("interpolated");100 expect(a[1].start).toBe(0.4); // bornes extérieures réelles conservées101 expect(a[3].end).toBe(1.2);102 expect(a[2].end - a[2].start).toBeGreaterThan(0.15); // « noir » a une vraie place, pas 40 ms103 });104105 it("mot inventé par Whisper : ignoré, le reste ne bouge pas", () => {106 const script = "Le Québec produit son électricité.";107 const heard = heardFrom(["Le", "Québec", "euh", "produit", "son", "électricité.", "Merci."], 0, 0.3);108 const a = alignScript(script, heard, { start: 0, end: 2.5 });109 expectWellFormed(a, script, { start: 0, end: 2.5 });110 expect(a.every((w) => w.confidence === "matched")).toBe(true);111 expect(a[2]).toMatchObject({ word: "produit", start: 0.9, end: 1.2 });112 expect(a[4]).toMatchObject({ word: "électricité.", start: 1.5, end: 1.8 });113 });114115 it("orthographe voisine (nom propre mal entendu) : retrouvé", () => {116 const a = alignScript("Anthropic entre en Bourse.", heardFrom(["Antropic", "entre", "en", "bourse"], 0, 0.3), { start: 0, end: 1.2 });117 expect(a.map((w) => w.confidence)).toEqual(["matched", "matched", "matched", "matched"]);118 });119120 describe("nombres", () => {121 const script = "Le total atteint 1 157,63 $ par mois.";122 const window = { start: 0, end: 5 };123 const cases: { name: string; heard: WordTiming[]; from: number; to: number }[] = [124 { name: "chiffres regroupés", heard: [...heardFrom(["Le", "total", "atteint"], 0, 0.3), { word: "1157,63", start: 0.9, end: 2.1 }, { word: "dollars", start: 2.1, end: 2.5 }, ...heardFrom(["par", "mois."], 2.5, 0.3)], from: 0.9, to: 2.5 },125 { name: "symbole collé au nombre", heard: [...heardFrom(["Le", "total", "atteint"], 0, 0.3), { word: "1", start: 0.9, end: 1.1 }, { word: "157,63$", start: 1.1, end: 2.5 }, ...heardFrom(["par", "mois."], 2.5, 0.3)], from: 0.9, to: 2.5 },126 { name: "nombre épelé", heard: [...heardFrom(["Le", "total", "atteint"], 0, 0.3), ...heardFrom(["mille", "cent", "cinquante-sept", "dollars", "et", "soixante-trois"], 0.9, 0.3), ...heardFrom(["par", "mois."], 2.7, 0.3)], from: 0.9, to: 2.7 },127 ];128 it.each(cases)("« 1 157,63 $ » — $name : le nombre couvre l'intervalle entendu, la suite n'est pas décalée", ({ heard, from, to }) => {129 const a = alignScript(script, heard, window);130 expectWellFormed(a, script, window);131 const [un, cent, dollar, par, mois] = a.slice(3);132 expect(a.slice(0, 3).map((w) => [w.start, w.end, w.confidence])).toEqual([[0, 0.3, "matched"], [0.3, 0.6, "matched"], [0.6, 0.9, "matched"]]);133 expect(un.start).toBeCloseTo(from, 3);134 expect(dollar.end).toBeLessThanOrEqual(to + 1e-9);135 expect(dollar.end).toBeGreaterThan(from + 0.5);136 expect([un, cent, dollar].some((w) => w.confidence === "matched")).toBe(true);137 expect(par).toMatchObject({ word: "par", confidence: "matched", start: to });138 expect(mois).toMatchObject({ word: "mois.", confidence: "matched" });139 });140141 it("« mille » dans le script, « 1000 » entendu ; « 3 » ↔ « trois » ; « 94 % » ↔ « quatre-vingt-quatorze pour cent »", () => {142 const a = alignScript("Il gagne mille dollars.", heardFrom(["Il", "gagne", "1000", "dollars"], 0, 0.3), { start: 0, end: 1.2 });143 expect(a.map((w) => w.confidence)).toEqual(["matched", "matched", "matched", "matched"]);144 expect(a[2]).toMatchObject({ word: "mille", start: 0.6 });145 const b = alignScript("Les 3 amis.", heardFrom(["Les", "trois", "amis"], 0, 0.3), { start: 0, end: 0.9 });146 expect(b[1]).toMatchObject({ word: "3", confidence: "matched", start: 0.3, end: 0.6 });147 const s = "Soit 94 % du réseau.";148 const c = alignScript(s, heardFrom(["Soit", "quatre-vingt-quatorze", "pour", "cent", "du", "réseau."], 0, 0.3), { start: 0, end: 1.8 });149 expectWellFormed(c, s, { start: 0, end: 1.8 });150 expect(c[1].start).toBeCloseTo(0.3, 3);151 expect(c[2].end).toBeCloseTo(1.2, 3);152 expect(c[3]).toMatchObject({ word: "du", confidence: "matched", start: 1.2 });153 });154155 it("nombre jamais entendu : interpolé, sans faire dérailler la suite", () => {156 const s = "En 2026 le prix monte encore.";157 const a = alignScript(s, heardFrom(["En", "le", "prix", "monte", "encore"], 0, 0.3, { 1: 0.6 }), { start: 0, end: 2.1 });158 expectWellFormed(a, s, { start: 0, end: 2.1 });159 expect(a[1]).toMatchObject({ word: "2026", confidence: "interpolated", start: 0.3, end: 0.9 });160 expect(a.slice(2).every((w) => w.confidence === "matched")).toBe(true);161 });162 });163164 it("élisions françaises : « l'argent » entendu en un mot, en deux mots, ou avec une apostrophe typographique", () => {165 const script = "L’argent qu'il n'a pas, c'est aujourd'hui l'essentiel.";166 const window = { start: 0, end: 4 };167 const whole = alignScript(script, heardFrom(["L'argent", "qu'il", "n'a", "pas,", "c'est", "aujourd'hui", "l'essentiel."], 0, 0.4), window);168 expectWellFormed(whole, script, window);169 expect(whole.every((w) => w.confidence === "matched")).toBe(true);170 expect(whole[0]).toMatchObject({ start: 0, end: 0.4 });171 const split = alignScript(script, heardFrom(["L'", "argent", "qu'", "il", "n'", "a", "pas", "c'", "est", "aujourd'", "hui", "l'", "essentiel"], 0, 0.2), window);172 expectWellFormed(split, script, window);173 expect(split.every((w) => w.confidence === "matched")).toBe(true);174 expect(split[0]).toMatchObject({ word: "L’argent", start: 0, end: 0.4 }); // « L' » + « argent »175 expect(split[5]).toMatchObject({ word: "aujourd'hui", start: 1.8, end: 2.2 });176 });177178 it("aucun mot entendu : répartition au prorata des caractères, tout interpolé", () => {179 const script = "Un mot extraordinairement long.";180 const a = alignScript(script, [], { start: 2, end: 6 });181 expectWellFormed(a, script, { start: 2, end: 6 });182 expect(a.every((w) => w.confidence === "interpolated")).toBe(true);183 expect(a[0].start).toBe(2);184 expect(a[a.length - 1].end).toBe(6);185 expect(a[2].end - a[2].start).toBeGreaterThan((a[0].end - a[0].start) * 5);186 expect(alignmentQuality(a)).toEqual({ matched: 0, total: 4, ratio: 0 });187 expect(alignScript(" ", [], { start: 0, end: 1 })).toEqual([]);188 expect(alignmentQuality([])).toEqual({ matched: 0, total: 0, ratio: 0 });189 });190191 it("mots entendus inutilisables (temps non finis, hors fenêtre, vides) : jamais de temps invalide", () => {192 const script = "Trois mots ici.";193 const a = alignScript(script, [{ word: "Trois", start: NaN, end: 1 }, { word: "", start: 0, end: 1 }, { word: "mots", start: -2, end: -1 }, { word: "ici", start: 9, end: 12 }], { start: 0, end: 2 });194 expectWellFormed(a, script, { start: 0, end: 2 });195 });196197 it("fenêtre trop courte pour 40 ms par mot : durée minimale réduite, mais ordre et bornes tenus", () => {198 const script = "un deux trois quatre cinq six sept huit neuf dix";199 const a = alignScript(script, [], { start: 1, end: 1.2 });200 expectWellFormed(a, script, { start: 1, end: 1.2 }, 0.02);201 });202203 it("propriétés tenues sous perturbations aléatoires à graine (mots retirés, ajoutés, déformés, temps bruités)", () => {204 const script = "Hydro-Québec a versé 3,4 milliards $ à l'État en 2025 : c'est 12 % de plus qu'en 2024, malgré des hivers « très » doux. "205 + "Pourquoi ? Parce que l'exportation vers New York rapporte davantage… et que les réservoirs étaient pleins !";206 const tokens = script.split(/\s+/);207 const extras = ["euh", "donc", "2", "mille", "Merci", "l'", "voilà."];208 for (let seed = 1; seed <= 40; seed++) {209 const r = rng(seed);210 const window = { start: Math.round(r() * 5 * 1000) / 1000, end: 0 };211 window.end = window.start + 2 + r() * 40;212 const heard: WordTiming[] = [];213 let t = window.start - 0.5 + r();214 for (const tok of tokens) {215 const roll = r();216 if (roll < 0.15) continue; // mot manqué217 if (roll < 0.25) heard.push({ word: extras[Math.floor(r() * extras.length)], start: t, end: (t += r() * 0.3) }); // mot inventé218 const word = roll > 0.9 ? tok.slice(0, Math.max(1, tok.length - 2)) : roll > 0.8 ? tok.toUpperCase() : tok;219 const start = t + (r() - 0.3) * 0.2, end = start + (r() - 0.1) * 0.6; // chevauchements et durées négatives possibles220 heard.push({ word, start, end });221 t = Math.max(t, end) + (r() < 0.1 ? r() * 1.5 : 0);222 }223 const a = alignScript(script, heard, window);224 expectWellFormed(a, script, window);225 const q = alignmentQuality(a);226 expect(q.matched).toBeLessThanOrEqual(q.total);227 expect(q.ratio, `graine ${seed}`).toBeGreaterThan(0.5);228 expect(alignScript(script, heard, window)).toEqual(a); // déterministe229 }230 });231});232233describe("sentenceCues, pauses, emphasisCandidates", () => {234 const script = "Bonjour à tous. Le Québec exporte 12 % de son électricité vers New York. Pourquoi ?";235 const heard = heardFrom(["Bonjour", "à", "tous.", "Le", "Québec", "exporte", "12", "%", "de", "son", "électricité", "vers", "New", "York.", "Pourquoi"], 0, 0.3, { 3: 0.5, 5: 0.3, 14: 0.8 });236 const end = heard[heard.length - 1].end + 0.5;237 const a = alignScript(script, heard, { start: 0, end });238239 it("sentenceCues : une réplique par phrase, bornée par ses vrais mots", () => {240 const cues = sentenceCues(a);241 expect(cues.map((c) => c.text)).toEqual(["Bonjour à tous.", "Le Québec exporte 12 % de son électricité vers New York.", "Pourquoi ?"]);242 expect(cues.map((c) => c.sentence)).toEqual([0, 1, 2]);243 expect(cues[0]).toMatchObject({ start: 0, end: 0.9 });244 expect(cues[1].start).toBeCloseTo(1.4, 3);245 expect(cues[1].end).toBeCloseTo(heard[13].end, 3);246 expect(cues[2].start).toBeCloseTo(heard[14].start, 3);247 for (const [i, c] of cues.entries()) if (i) expect(c.start).toBeGreaterThanOrEqual(cues[i - 1].end);248 expect(sentenceCues([])).toEqual([]);249 });250251 it("pauses : silences entre mots consécutifs, seuil réglable", () => {252 const p = pauses(a);253 expect(p.map((x) => [x.afterIndex, x.seconds])).toEqual([[2, 0.5], [4, 0.3], [13, 0.8]]);254 expect(p[0].at).toBeCloseTo(0.9, 3);255 expect(a[p[2].afterIndex].word).toBe("York.");256 expect(pauses(a, 0.6).map((x) => x.afterIndex)).toEqual([13]);257 expect(pauses([])).toEqual([]);258 });259260 it("emphasisCandidates : nombres, noms propres hors début de phrase, mots après une pause ; jamais les mots-outils", () => {261 const picked = emphasisCandidates(a, "fr").map((i) => a[i].word);262 expect(picked).toEqual(["Québec", "exporte", "12", "%", "New", "York."]); // « exporte » suit une pause dans la phrase263 for (const w of ["à", "de", "son", "vers", "Le", "Bonjour", "Pourquoi", "?"]) expect(picked, w).not.toContain(w); // « Pourquoi » : simple respiration entre phrases264 const slow = alignScript("nous avons vraiment gagné cette manche hier",265 [...heardFrom(["nous", "avons"], 0, 0.3), { word: "vraiment", start: 0.6, end: 2.2 }, ...heardFrom(["gagné", "cette", "manche", "hier"], 2.2, 0.3)], { start: 0, end: 3.4 });266 expect(emphasisCandidates(slow, "fr").map((i) => slow[i].word)).toEqual(["vraiment"]);267 const en = alignScript("The NASA budget rose by 5 percent in Houston.", [], { start: 0, end: 4 });268 expect(emphasisCandidates(en, "en").map((i) => en[i].word)).toEqual(["NASA", "5", "percent", "Houston."]);269 });270});271272describe("cuesFromAligned, karaokeCues", () => {273 const lineOk = (text: string, max = 42) => text.split("\n").length <= 2 && text.split("\n").every((l) => l.length <= max);274 const script = "Bonjour et bienvenue dans cette vidéo. Le Québec produit 94 % de son électricité grâce à ses grands barrages du Nord, "275 + "construits pour la plupart entre 1960 et 1990, puis agrandis au fil des décennies par de nouveaux ouvrages. Merci !";276 const tokens = script.split(/\s+/);277 const heard = heardFrom(tokens.filter((t) => !["%", "!"].includes(t)).map((t) => t.replace(/[.,]/g, "").toLowerCase()), 0.2, 0.3, { 6: 0.4 });278 const end = heard[heard.length - 1].end + 0.4;279 const a = alignScript(script, heard, { start: 0, end });280281 it("cuesFromAligned : texte du script, coupes aux phrases puis aux virgules, 2 lignes de 42 caractères, pas de chevauchement", () => {282 const cues = cuesFromAligned(a);283 expect(cues[0]).toMatchObject({ text: "Bonjour et bienvenue dans cette vidéo.", start: 0.2 });284 expect(cues[cues.length - 1].text).toBe("Merci !");285 expect(cues.map((c) => c.text.replace(/\n/g, " ")).join(" ")).toBe(script); // tout le script, rien d'autre286 for (const [i, c] of cues.entries()) {287 expect(lineOk(c.text), c.text).toBe(true);288 expect(c.end).toBeGreaterThan(c.start);289 expect(c.end - c.start).toBeLessThanOrEqual(6.5);290 if (i) expect(c.start).toBeGreaterThanOrEqual(cues[i - 1].end);291 }292 const middle = cues.slice(1, -1).map((c) => c.text.replace(/\n/g, " "));293 expect(middle.length).toBeGreaterThanOrEqual(2);294 expect(middle.slice(0, -1).every((t) => /,$/.test(t)), middle.join(" | ")).toBe(true); // la longue phrase est coupée aux virgules295 expect(middle.some((t) => /^[%!?:;]/.test(t))).toBe(false);296 });297298 it("cuesFromAligned respecte maxChars et maxSeconds ; entrée vide → aucune réplique", () => {299 const narrow = cuesFromAligned(a, { maxChars: 20 });300 expect(narrow.every((c) => lineOk(c.text, 20)), narrow.map((c) => c.text).join(" | ")).toBe(true);301 const slow = alignScript("un deux trois quatre cinq six sept huit neuf dix onze douze", heardFrom("un deux trois quatre cinq six sept huit neuf dix onze douze".split(" "), 0, 1), { start: 0, end: 12 });302 const short = cuesFromAligned(slow, { maxSeconds: 3 });303 expect(short.every((c) => c.end - c.start <= 3.01)).toBe(true);304 expect(short.map((c) => c.text.replace(/\n/g, " ")).join(" ")).toBe("un deux trois quatre cinq six sept huit neuf dix onze douze");305 expect(cuesFromAligned([])).toEqual([]);306 expect(karaokeCues([])).toEqual([]);307 });308309 it("karaokeCues : mêmes répliques, avec les temps de chaque mot", () => {310 const cues = cuesFromAligned(a), k = karaokeCues(a);311 expect(k.map(({ start, end, text }) => ({ start, end, text }))).toEqual(cues);312 expect(k.flatMap((c) => c.words.map((w) => w.text))).toEqual(tokens);313 for (const c of k) {314 expect(c.words.map((w) => w.text).join(" ")).toBe(c.text.replace(/\n/g, " "));315 expect(c.words[0].start).toBe(c.start);316 for (const [i, w] of c.words.entries()) {317 expect(w.end).toBeGreaterThan(w.start);318 expect(w.start).toBeGreaterThanOrEqual(c.start);319 if (i) expect(w.start).toBeGreaterThanOrEqual(c.words[i - 1].end);320 }321 }322 const quebec = k.flatMap((c) => c.words).find((w) => w.text === "Québec")!;323 const src = heard.find((h) => h.word === "québec")!;324 expect(quebec).toMatchObject({ start: src.start, end: src.end });325 });326});327