SPB Git

Repository Public

align.ts 20.6 KB 352 lines typescript

1import type { WordTiming } from "../lib/contracts";23/**4 * Alignement forcé « script ↔ mots entendus » (TypeScript pur, aucune E/S).5 *6 * Whisper rend les mots qu'il ENTEND (nombres et sigles normalisés, élisions parfois scindées, mots manqués ou inventés). Les7 * sous-titres et les repères d'animation, eux, doivent porter les mots du SCRIPT. `alignScript` aligne les deux suites par8 * programmation dynamique (Needleman–Wunsch) et donne à chaque mot du script un intervalle de temps :9 *  - `matched`      : le mot a été retrouvé dans l'audio, ses temps viennent de Whisper ;10 *  - `interpolated` : le mot n'a pas été retrouvé, ses temps sont estimés entre ses voisins retrouvés (au prorata des caractères).11 * Rien n'est inventé au-delà de cette estimation, et `alignmentQuality` dit quelle part des mots repose sur de vrais temps.12 */1314export interface AlignedWord {15  /** Mot du script, tel qu'affiché (ponctuation attachée). */16  word: string;17  start: number;18  end: number;19  /** Rang du mot dans le script (0, 1, 2…). */20  index: number;21  /** Rang de la phrase dans le script (les phrases se terminent sur . ! ? …). */22  sentence: number;23  confidence: "matched" | "interpolated";24}2526/** Durée minimale d'un mot (secondes). Réduite seulement si la fenêtre est trop courte pour loger tous les mots. */27const MIN_WORD = 0.04;28const SENTENCE_END = /[.!?…]["»”)\]]*$/;29/** Un mot « prononçable » contient une lettre, un chiffre ou un symbole qui se lit ($, %, €, £). */30const SPEAKABLE = /[\p{L}\p{N}$%€£]/u;3132/** Symboles qui se lisent : remplacés par un mot avant la normalisation. */33const SYMBOLS: Record<string, string> = { $: " dollars ", "€": " euros ", "£": " livres ", "%": " pourcent ", "&": " et " };3435/** Valeur des mots-nombres simples (français et anglais) : « trois » et « 3 » sont alors une correspondance exacte. */36const NUMBER_VALUES: Record<string, number> = {37  zero: 0, un: 1, une: 1, deux: 2, trois: 3, quatre: 4, cinq: 5, six: 6, sept: 7, huit: 8, neuf: 9, dix: 10, onze: 11, douze: 12, treize: 13,38  quatorze: 14, quinze: 15, seize: 16, vingt: 20, trente: 30, quarante: 40, cinquante: 50, soixante: 60, cent: 100, mille: 1000,39  one: 1, two: 2, three: 3, four: 4, five: 5, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14,40  fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70,41  eighty: 80, ninety: 90, hundred: 100, thousand: 1000,42};43/**44 * Vocabulaire des nombres et des montants : deux unités de cette classe peuvent se correspondre « à peu près » (« 157 » ↔ « 1157 »,45 * « $ » ↔ « dollars », « 94 » ↔ « quatorze »). « un », « une », « one » en sont exclus : ce sont d'abord des articles.46 */47const NUMBER_WORDS = new Set([48  ...Object.keys(NUMBER_VALUES).filter((w) => !["un", "une", "one"].includes(w)),49  "cents", "vingts", "septante", "octante", "nonante", "million", "millions", "milliard", "milliards", "billion", "billions", "trillion", "trillions",50  "hundreds", "thousands", "dollar", "dollars", "euro", "euros", "livres", "pourcent", "percent", "cent", "cents", "virgule", "point",51]);5253/** Minuscules, sans accents ni ligatures. */54function fold(s: string): string {55  return s.toLowerCase().replace(/œ/g, "oe").replace(/æ/g, "ae").normalize("NFD").replace(/[̀-ͯ]/g, "");56}57/**58 * Unités comparables d'un mot : « l'argent » → [l, argent] ; « quatre-vingt-quatorze » → [quatre, vingt, quatorze] ;59 * « 157,63 » → [157, 63] ; « $ » → [dollars] ; « — » → [].60 */61export function normalizeToken(token: string): string[] {62  const spelled = token.replace(/[$€£%&]/g, (c) => SYMBOLS[c] ?? " ");63  return fold(spelled).split(/[^a-z0-9]+/).filter(Boolean);64}65const isDigits = (u: string) => /^\d+$/.test(u);66const isNumeric = (u: string) => isDigits(u) || NUMBER_WORDS.has(u);67function numberValue(u: string): number | null {68  if (isDigits(u)) return Number(u);69  return u in NUMBER_VALUES ? NUMBER_VALUES[u] : null;70}7172/** Distance d'édition bornée (Levenshtein) : assez pour reconnaître « Anthropic » dans « Antropic ». */73function editDistance(a: string, b: string): number {74  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);75  for (let i = 1; i <= a.length; i++) {76    const cur = [i];77    for (let j = 1; j <= b.length; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));78    prev = cur;79  }80  return prev[b.length];81}8283/** Score d'une correspondance entre une unité du script et une unité entendue ; ≤ 0 = pas de correspondance. */84function matchScore(a: string, b: string): number {85  if (a === b) return 3;86  const va = numberValue(a), vb = numberValue(b);87  if (va !== null && vb !== null && va === vb) return 3;                       // « 3 » ↔ « trois »88  if (isNumeric(a) && isNumeric(b)) return 1;                                  // nombres différents : correspondance lâche89  if (isDigits(a) || isDigits(b)) return 0;90  const longest = Math.max(a.length, b.length);91  if (longest >= 4 && editDistance(a, b) <= Math.floor(longest / 4)) return 2; // orthographe voisine (pluriel, nom propre)92  return 0;93}9495interface Unit { text: string; parent: number }9697/**98 * Needleman–Wunsch sur les unités : renvoie, pour chaque unité du script, l'indice de l'unité entendue appariée (ou -1).99 * Un trou coûte 1 de chaque côté ; deux unités qui ne se ressemblent pas ne sont jamais appariées (deux trous à la place).100 */101function alignUnits(script: Unit[], heard: Unit[]): Int32Array {102  const n = script.length, m = heard.length, W = m + 1, GAP = -1;103  const score = new Float32Array((n + 1) * W);104  const move = new Uint8Array((n + 1) * W);                                    // 1 = diagonale, 2 = haut (mot du script sauté), 3 = gauche105  for (let i = 1; i <= n; i++) { score[i * W] = i * GAP; move[i * W] = 2; }106  for (let j = 1; j <= m; j++) { score[j] = j * GAP; move[j] = 3; }107  for (let i = 1; i <= n; i++) {108    for (let j = 1; j <= m; j++) {109      const s = matchScore(script[i - 1].text, heard[j - 1].text);110      let best = score[(i - 1) * W + j] + GAP, mv = 2;111      const left = score[i * W + j - 1] + GAP;112      if (left > best) { best = left; mv = 3; }113      if (s > 0) { const diag = score[(i - 1) * W + j - 1] + s; if (diag >= best) { best = diag; mv = 1; } }114      score[i * W + j] = best; move[i * W + j] = mv;115    }116  }117  const pairs = new Int32Array(n).fill(-1);118  for (let i = n, j = m; i > 0 || j > 0;) {119    const mv = move[i * W + j];120    if (mv === 1) { pairs[i - 1] = j - 1; i--; j--; } else if (mv === 2) i--; else j--;121  }122  return pairs;123}124125/** Poids d'un mot dans une répartition : son nombre de caractères ; un signe isolé (« ? », « » ») ne prend pas de temps de parole. */126const weight = (word: string) => (SPEAKABLE.test(word) ? word.length : 0);127/** Répartit [start, end] entre des mots au prorata de leur nombre de caractères (les signes isolés se rangent sans durée, `settle` leur donne le minimum). */128function spread(out: AlignedWord[], from: number, to: number, start: number, end: number): void {129  const weights = [];130  for (let i = from; i <= to; i++) weights.push(weight(out[i].word));131  const total = weights.reduce((a, b) => a + b, 0), span = Math.max(0, end - start);132  if (!total) { for (let i = from; i <= to; i++) out[i].start = out[i].end = start; return; }133  let t = start;134  for (let i = from; i <= to; i++) {135    const d = (weights[i - from] / total) * span;136    out[i].start = t; out[i].end = i === to ? end : t + d;137    t += d;138  }139}140141/** Dernière passe : dans la fenêtre, sans chevauchement, croissant, aucun mot plus court que la durée minimale. */142function settle(out: AlignedWord[], window: { start: number; end: number }): void {143  if (!out.length) return;144  const span = Math.max(0, window.end - window.start);145  const min = Math.min(MIN_WORD, span / out.length);146  const clamp = (t: number) => Math.min(window.end, Math.max(window.start, Number.isFinite(t) ? t : window.start));147  let prevEnd = window.start;148  for (const w of out) {149    w.start = Math.max(clamp(w.start), prevEnd);150    w.end = Math.max(clamp(w.end), w.start + min);151    prevEnd = w.end;152  }153  let nextStart = window.end;154  for (let i = out.length - 1; i >= 0; i--) {155    const w = out[i];156    w.end = Math.min(w.end, nextStart);157    w.start = Math.max(window.start, Math.min(w.start, w.end - min));158    nextStart = w.start;159  }160  // arrondi au millième, sans sortir de la fenêtre, sans créer de chevauchement ni de mot vide161  for (const [i, w] of out.entries()) {162    w.start = Math.max(clamp(round3(w.start)), i ? out[i - 1].end : window.start);163    w.end = clamp(round3(w.end));164    if (w.end <= w.start) w.end = Math.min(window.end, w.start + Math.max(min, 0.001));165  }166}167const round3 = (n: number) => Math.round(n * 1000) / 1000;168169/**170 * Aligne le script sur les mots entendus. Une entrée par mot du script (séparé par des espaces), dans l'ordre du script.171 *172 * 1. Normalisation en unités (minuscules, sans accents ni ponctuation, élisions et traits d'union scindés, symboles épelés).173 * 2. Alignement global des unités ; un mot du script est `matched` dès qu'une de ses unités est appariée.174 * 3. Nombres : une suite de mots numériques du script (« 1 157,63 $ ») partage le temps des mots entendus qui lui correspondent175 *    (« 1157,63 », « dollars », ou le nombre épelé), au prorata des caractères ; de même quand un seul mot entendu couvre plusieurs176 *    mots du script.177 * 4. Mots non retrouvés : interpolés entre leurs voisins retrouvés. Si Whisper n'a laissé aucun blanc entre ces voisins (il a fondu178 *    le mot manqué dans les mots d'à côté), l'intervalle des voisins est repartagé avec eux. En tête et en fin de script, la durée179 *    estimée est plafonnée par le débit mesuré, pour ne pas étirer un mot sur un long silence.180 * 5. Tout est ramené dans `window`, croissant, sans chevauchement, 40 ms au moins par mot (moins seulement si la fenêtre est trop181 *    courte pour tous les mots).182 * Sans mots entendus : répartition au prorata des caractères sur `window`, tout en `interpolated`.183 */184export function alignScript(script: string, heard: WordTiming[], window: { start: number; end: number }): AlignedWord[] {185  const tokens = script.trim().split(/\s+/).filter(Boolean);186  if (!tokens.length) return [];187  const win = { start: Number.isFinite(window.start) ? window.start : 0, end: Number.isFinite(window.end) ? window.end : 0 };188  if (win.end < win.start) win.end = win.start;189190  let sentence = 0;191  const out: AlignedWord[] = tokens.map((word, index) => {192    const w: AlignedWord = { word, start: NaN, end: NaN, index, sentence, confidence: "interpolated" };193    if (SENTENCE_END.test(word)) sentence++;194    return w;195  });196197  const heardOk = heard198    .filter((h) => h && typeof h.word === "string" && h.word.trim() && Number.isFinite(h.start) && Number.isFinite(h.end))199    .map((h) => ({ word: h.word, start: Math.min(h.start, h.end), end: Math.max(h.start, h.end) }));200  const scriptUnits: Unit[] = tokens.flatMap((t, parent) => normalizeToken(t).map((text) => ({ text, parent })));201  const heardUnits: Unit[] = heardOk.flatMap((h, parent) => normalizeToken(h.word).map((text) => ({ text, parent })));202  if (!heardUnits.length || !scriptUnits.length) {203    spread(out, 0, out.length - 1, win.start, win.end);204    settle(out, win);205    return out;206  }207208  // 2. alignement des unités → pour chaque mot du script, les mots entendus appariés209  const pairs = alignUnits(scriptUnits, heardUnits);210  const hits: number[][] = tokens.map(() => []);211  const heardUsed = new Uint8Array(heardOk.length);212  pairs.forEach((j, i) => {213    if (j < 0) return;214    const h = heardUnits[j].parent;215    hits[scriptUnits[i].parent].push(h);216    heardUsed[h] = 1;217  });218  const numericToken = tokens.map((t) => { const u = normalizeToken(t); return u.length > 0 && u.every(isNumeric); });219  const numericHeard = heardOk.map((h) => { const u = normalizeToken(h.word); return u.length > 0 && u.every(isNumeric); });220221  // 3. groupes d'ancrage : mots du script consécutifs qui partagent un même intervalle entendu222  for (let i = 0; i < tokens.length;) {223    if (!hits[i].length && !numericToken[i]) { i++; continue; }224    let to = i, lo = Infinity, hi = -Infinity;225    const take = (k: number) => { for (const h of hits[k]) { lo = Math.min(lo, h); hi = Math.max(hi, h); } };226    take(i);227    for (let k = i + 1; k < tokens.length; k++) {228      const sameHeard = hits[k].length > 0 && hi >= 0 && Math.min(...hits[k]) <= hi;       // un mot entendu couvre plusieurs mots du script229      const numberRun = numericToken[k] && numericToken[k - 1];                            // suite numérique du script230      if (!sameHeard && !numberRun) break;231      take(k); to = k;232    }233    if (hi < 0) { i = to + 1; continue; }                                                  // suite numérique jamais entendue : interpolation234    if (to > i && numericToken.slice(i, to + 1).some(Boolean)) {235      // le nombre a pu être épelé ou regroupé autrement : on annexe les mots numériques entendus voisins restés sans correspondance236      while (lo > 0 && !heardUsed[lo - 1] && numericHeard[lo - 1]) lo--;237      while (hi < heardOk.length - 1 && !heardUsed[hi + 1] && numericHeard[hi + 1]) hi++;238    }239    const start = heardOk[lo].start, end = Math.max(heardOk[hi].end, start);240    if (to === i) { out[i].start = start; out[i].end = end; } else spread(out, i, to, start, end);241    for (let k = i; k <= to; k++) if (hits[k].length) out[k].confidence = "matched";242    i = to + 1;243  }244245  // 4. interpolation des mots sans temps, entre voisins ancrés246  const anchored = out.filter((w) => Number.isFinite(w.start));247  const chars = (from: number, to: number) => { let c = 0; for (let k = from; k <= to; k++) c += weight(out[k].word); return c; };248  const rates = anchored.filter((w) => w.end > w.start).map((w) => (w.end - w.start) / Math.max(1, w.word.length)).sort((a, b) => a - b);249  const rate = rates.length ? rates[Math.floor(rates.length / 2)] : 0.07;                  // secondes par caractère (médiane mesurée)250  for (let i = 0; i < out.length;) {251    if (Number.isFinite(out[i].start)) { i++; continue; }252    let to = i;253    while (to + 1 < out.length && !Number.isFinite(out[to + 1].start)) to++;254    const L = i > 0 ? out[i - 1] : null, R = to + 1 < out.length ? out[to + 1] : null;255    const expected = chars(i, to) * rate;256    let a = L ? L.end : win.start, b = R ? R.start : win.end;257    if (!L && R) a = Math.max(a, b - expected * 1.5);                                      // tête : collé au premier mot retrouvé258    if (L && !R) b = Math.min(b, a + expected * 1.5);                                      // fin : collé au dernier mot retrouvé259    if (!expected) spread(out, i, to, a, a);                                               // signes isolés : rangés après le mot précédent260    else if (b - a >= expected * 0.5 || (!L && !R)) spread(out, i, to, a, b);261    else {262      // pas de place : Whisper a fondu ces mots dans leurs voisins → on repartage l'intervalle des voisins avec eux263      const from = L ? i - 1 : i, until = R ? to + 1 : to;264      spread(out, from, until, L ? L.start : a, R ? Math.max(R.end, a) : b);265    }266    i = to + 1;267  }268269  settle(out, win);270  return out;271}272273/**274 * Part des mots prononçables du script retrouvés dans l'audio. Les signes isolés (« — », « ? », « » ») ne comptent pas dans `total` :275 * ils ne se prononcent pas et ne peuvent donc jamais être retrouvés. `ratio` vaut 0 quand il n'y a aucun mot.276 */277export function alignmentQuality(aligned: AlignedWord[]): { matched: number; total: number; ratio: number } {278  const spoken = aligned.filter((w) => SPEAKABLE.test(w.word));279  const matched = spoken.filter((w) => w.confidence === "matched").length;280  return { matched, total: spoken.length, ratio: spoken.length ? matched / spoken.length : 0 };281}282283/** Une réplique par phrase du script, bornée par les temps réels de son premier et de son dernier mot. */284export function sentenceCues(aligned: AlignedWord[]): { start: number; end: number; text: string; sentence: number }[] {285  const cues: { start: number; end: number; text: string; sentence: number }[] = [];286  for (const w of aligned) {287    const last = cues[cues.length - 1];288    if (last && last.sentence === w.sentence) { last.end = Math.max(last.end, w.end); last.text += ` ${w.word}`; }289    else cues.push({ start: w.start, end: w.end, text: w.word, sentence: w.sentence });290  }291  return cues;292}293294/**295 * Silences entre deux mots consécutifs (≥ `minGap` secondes) : `at` = début du silence, `afterIndex` = rang du mot qui le précède.296 * Whisper étire souvent la fin d'un mot jusqu'au mot suivant : seuls les silences qu'il a laissés visibles ressortent ici.297 */298export function pauses(aligned: AlignedWord[], minGap = 0.25): { at: number; seconds: number; afterIndex: number }[] {299  const out: { at: number; seconds: number; afterIndex: number }[] = [];300  for (let i = 0; i + 1 < aligned.length; i++) {301    const gap = aligned[i + 1].start - aligned[i].end;302    if (gap >= minGap) out.push({ at: aligned[i].end, seconds: round3(gap), afterIndex: aligned[i].index });303  }304  return out;305}306307const STOPWORDS: Record<"fr" | "en", Set<string>> = {308  fr: new Set(("a au aux avec ce ces cet cette c ca car comme d dans de des du donc elle elles en est et etre il ils j je l la le les leur leurs lui "309    + "m ma mais me mes mon n ne ni nos notre nous on ont or ou par pas plus pour qu que qui s sa se ses si son sont sur t ta te tes ton tres tu un une "310    + "vos votre vous y ete etait avait fait faire tout tous toute toutes aussi alors puis cela ceci dont ou voici voila").split(" ")),311  en: new Set(("a about after all also an and are as at be been but by can could did do does for from had has have he her his how i if in into is it its "312    + "just more most no not of on one or our out she so some than that the their them then there these they this to up was we were what when which who "313    + "will with would you your").split(" ")),314};315316/**317 * Indices (`index`) des mots qui méritent une emphase visuelle. Heuristiques simples et déterministes — une liste d'indices à318 * proposer, pas une vérité :319 *  1. nombres, pourcentages et montants (chiffres, $, %, €, mots-nombres sauf « un », « une », « one ») ;320 *  2. noms propres : majuscule initiale ailleurs qu'en début de phrase, ou sigle tout en majuscules (≥ 2 lettres) ;321 *  3. mots prononcés lentement : mot retrouvé d'au moins 4 lettres dont la durée par caractère dépasse 1,6 × la médiane ;322 *  4. mot de contenu qui suit une pause d'au moins 0,25 s À L'INTÉRIEUR d'une phrase (y compris après un mot-outil : « … et | surtout »).323 * Les mots-outils de la langue (articles, prépositions, auxiliaires) ne sont jamais retenus, sauf s'ils sont un nombre.324 */325export function emphasisCandidates(aligned: AlignedWord[], lang: "fr" | "en"): number[] {326  const stop = STOPWORDS[lang];327  const picked = new Set<number>();328  const units = aligned.map((w) => normalizeToken(w.word));329  const content = (i: number) => units[i].length > 0 && units[i].some((u) => !stop.has(u) && u.length > 1);330  const perChar = (w: AlignedWord) => (w.end - w.start) / Math.max(1, w.word.replace(/[^\p{L}\p{N}]/gu, "").length);331  const measured = aligned.filter((w) => w.confidence === "matched" && w.end > w.start).map(perChar).sort((a, b) => a - b);332  const median = measured.length >= 4 ? measured[Math.floor(measured.length / 2)] : null;333  let pausedBefore = false;334  for (const [i, w] of aligned.entries()) {335    const prev = aligned[i - 1];336    if (prev && prev.sentence !== w.sentence) pausedBefore = false;                        // la respiration entre deux phrases n'est pas une emphase337    else if (prev && w.start - prev.end >= 0.25) pausedBefore = true;338    const letters = w.word.replace(/^[^\p{L}\p{N}$€£]+|[^\p{L}\p{N}%$€£]+$/gu, "");339    const number = /\d/.test(w.word) || /[$%€£]/.test(w.word) || (units[i].length > 0 && units[i].every(isNumeric));340    if (number) { picked.add(w.index); pausedBefore = false; continue; }341    if (!content(i)) continue;                                                             // un mot-outil ne consomme pas la pause342    const sentenceStart = !prev || prev.sentence !== w.sentence;343    const bare = letters.replace(/^[\p{L}]['’]/u, "");                                     // « l'Ontario » → « Ontario »344    const acronym = /^[\p{Lu}\d]{2,}s?$/u.test(bare) && /\p{Lu}/u.test(bare);345    const proper = /^\p{Lu}/u.test(bare) && !sentenceStart;346    const slow = median !== null && w.confidence === "matched" && bare.length >= 4 && perChar(w) > median * 1.6;347    if (acronym || proper || slow || pausedBefore) picked.add(w.index);348    pausedBefore = false;349  }350  return [...picked].sort((a, b) => a - b);351}352
Files main
Menu

Theme