Repository Public
1import type { Cue, WordTiming } from "../lib/contracts";2import type { AlignedWord } from "./align";34/** Sous-titres : répliques de 2 lignes au plus, ~42 caractères par ligne. Les temps sont en secondes sur la ligne de temps du film. */56const DEFAULT_MAX_CHARS = 42;7const SENTENCE_END = /[.!?…]["»”)]*$/;89/** Coupe un texte en au plus 2 lignes équilibrées de `maxChars` caractères (coupe de préférence après une ponctuation). */10export function wrapCue(text: string, maxChars = DEFAULT_MAX_CHARS): string {11 const t = text.replace(/\s+/g, " ").trim();12 if (t.length <= maxChars) return t;13 const words = t.split(" ");14 let best = -1, bestScore = Infinity;15 for (let i = 1; i < words.length; i++) {16 const a = words.slice(0, i).join(" "), b = words.slice(i).join(" ");17 if (/^[:;!?»%]/.test(b)) continue; // pas de ponctuation haute en tête de ligne18 const over = Math.max(0, a.length - maxChars) + Math.max(0, b.length - maxChars);19 const score = over * 100 + Math.abs(a.length - b.length) - (/[,;:.!?]$/.test(a) ? 6 : 0);20 if (score < bestScore) { bestScore = score; best = i; }21 }22 return best < 0 ? t : `${words.slice(0, best).join(" ")}\n${words.slice(best).join(" ")}`;23}2425/** Découpe un texte en morceaux d'au plus `limit` caractères : phrases d'abord, puis virgules, puis espaces. */26function chunkText(text: string, limit: number): string[] {27 const out: string[] = [];28 const sentences = text.replace(/\s+/g, " ").trim().split(/(?<=[.!?…]["»”)]?)\s+(?![:;!?»])/).filter(Boolean);29 for (const s of sentences) {30 if (s.length <= limit) { out.push(s); continue; }31 let cur = "";32 for (const part of s.split(/(?<=[,;:])\s+/)) {33 const words = part.split(" ");34 for (const [i, w] of words.entries()) {35 const sep = cur ? " " : "";36 const glue = /^[:;!?»%]/.test(w); // ne jamais détacher une ponctuation haute37 if (cur && !glue && (cur + sep + w).length > limit) { out.push(cur); cur = w; } else cur += sep + w;38 // coupe de préférence à la virgule quand le morceau est déjà bien rempli39 if (i === words.length - 1 && cur.length > limit * 0.6) { out.push(cur); cur = ""; }40 }41 }42 if (cur) out.push(cur);43 }44 return out;45}4647/**48 * Répliques à partir de mots alignés. Une réplique se termine à la fin d'une phrase, à une pause ≥ 0,7 s, quand elle atteindrait49 * 2 × `maxChars` caractères ou `maxSeconds` secondes. `maxChars` = longueur maximale d'UNE ligne (42 par défaut).50 */51export function cuesFromWords(words: WordTiming[], o?: { maxChars?: number; maxSeconds?: number }): Cue[] {52 const maxChars = o?.maxChars ?? DEFAULT_MAX_CHARS, maxSeconds = o?.maxSeconds ?? 6;53 const limit = maxChars * 2;54 const clean = words.map((w) => ({ ...w, word: w.word.trim() })).filter((w) => w.word && Number.isFinite(w.start) && Number.isFinite(w.end));55 const cues: Cue[] = [];56 let cur: WordTiming[] = [];57 const text = (ws: WordTiming[]) => ws.map((w) => w.word).join(" ").replace(/ ([,.])/g, "$1");58 const flush = () => {59 if (!cur.length) return;60 cues.push({ start: cur[0].start, end: Math.max(cur[cur.length - 1].end, cur[0].start + 0.3), text: wrapCue(text(cur), maxChars) });61 cur = [];62 };63 for (const w of clean) {64 const glue = /^[:;!?»%.,]/.test(w.word);65 if (cur.length && !glue) {66 const last = cur[cur.length - 1];67 if (w.start - last.end >= 0.7 || SENTENCE_END.test(last.word) || text([...cur, w]).length > limit || w.end - cur[0].start > maxSeconds) flush();68 }69 cur.push(w);70 }71 flush();72 // lisibilité : au moins 1 s à l'écran quand le blanc qui suit le permet ; jamais de chevauchement73 for (let i = 0; i < cues.length; i++) {74 const next = cues[i + 1]?.start ?? Infinity;75 cues[i].end = Math.min(Math.max(cues[i].end, cues[i].start + 1), Math.max(next - 0.04, cues[i].end));76 cues[i].start = round3(cues[i].start);77 cues[i].end = round3(cues[i].end);78 }79 return cues;80}8182/**83 * Regroupe des mots alignés sur le script en répliques, avec les mêmes limites que `cuesFromWords` (2 × `maxChars` caractères,84 * `maxSeconds` secondes, pause ≥ 0,7 s). Coupe d'abord aux fins de phrase ; quand une phrase déborde, coupe de préférence après la85 * dernière virgule (ou la dernière pause ≥ 0,25 s) qui laisse une réplique raisonnablement remplie, sinon au mot.86 */87function groupAligned(aligned: AlignedWord[], maxChars: number, maxSeconds: number): AlignedWord[][] {88 const limit = maxChars * 2;89 const clean = aligned.filter((w) => w.word.trim() && Number.isFinite(w.start) && Number.isFinite(w.end));90 const text = (ws: AlignedWord[]) => ws.map((w) => w.word).join(" ");91 const groups: AlignedWord[][] = [];92 let cur: AlignedWord[] = [];93 const flush = (n = cur.length) => { if (n > 0) { groups.push(cur.slice(0, n)); cur = cur.slice(n); } };94 const tooBig = (ws: AlignedWord[]) => text(ws).length > limit || ws[ws.length - 1].end - ws[0].start > maxSeconds;95 for (const w of clean) {96 const glue = /^[:;!?»%.,)\]]/.test(w.word) || (cur.length > 0 && /^[«(“\[]$/.test(cur[cur.length - 1].word)); // ponctuation jamais détachée97 if (cur.length && !glue) {98 const last = cur[cur.length - 1];99 if (w.sentence !== last.sentence || w.start - last.end >= 0.7) flush();100 else while (cur.length && tooBig([...cur, w])) {101 let cut = -1;102 for (let j = cur.length - 1; j >= 0; j--) {103 const next = cur[j + 1] ?? w;104 const soft = /[,;:]["»”)]*$/.test(cur[j].word) || next.start - cur[j].end >= 0.25;105 if (soft && !/^[:;!?»%.,)\]]/.test(next.word) && text(cur.slice(0, j + 1)).length >= limit * 0.4) { cut = j + 1; break; }106 }107 flush(cut > 0 ? cut : cur.length);108 }109 }110 cur.push(w);111 }112 flush();113 return groups;114}115/** Lisibilité, comme `cuesFromWords` : au moins 1 s à l'écran quand le blanc qui suit le permet ; jamais de chevauchement. */116function cueBounds(groups: AlignedWord[][]): { start: number; end: number }[] {117 const b = groups.map((g) => ({ start: g[0].start, end: Math.max(g[g.length - 1].end, g[0].start + 0.3) }));118 for (let i = 0; i < b.length; i++) {119 const next = b[i + 1]?.start ?? Infinity;120 b[i].end = round3(Math.min(Math.max(b[i].end, b[i].start + 1), Math.max(next - 0.04, b[i].end)));121 b[i].start = round3(b[i].start);122 }123 return b;124}125126/**127 * Répliques à partir du script aligné (`alignScript`) : le texte est celui du SCRIPT, les temps sont ceux des mots réellement128 * entendus. Mêmes conventions que `cuesFromWords` : `maxChars` = longueur maximale d'UNE ligne (42 par défaut), 2 lignes au plus.129 */130export function cuesFromAligned(aligned: AlignedWord[], o?: { maxChars?: number; maxSeconds?: number }): Cue[] {131 return karaokeCues(aligned, o).map(({ start, end, text }) => ({ start, end, text }));132}133134/** Réplique dont chaque mot garde ses temps, pour des sous-titres animés (mot en cours surligné). */135export interface KaraokeCue extends Cue { words: { start: number; end: number; text: string }[] }136137/**138 * Mêmes répliques que `cuesFromAligned` (même découpage, même texte sur 2 lignes), chacune avec les temps de ses mots. Les mots sont139 * dans l'ordre du texte ; `words.map(w => w.text).join(" ")` redonne le texte de la réplique, aux sauts de ligne près.140 */141export function karaokeCues(aligned: AlignedWord[], o?: { maxChars?: number; maxSeconds?: number }): KaraokeCue[] {142 const maxChars = o?.maxChars ?? DEFAULT_MAX_CHARS;143 const groups = groupAligned(aligned, maxChars, o?.maxSeconds ?? 6);144 const bounds = cueBounds(groups);145 return groups.map((g, i) => ({146 ...bounds[i],147 text: wrapCue(g.map((w) => w.word).join(" "), maxChars),148 words: g.map((w) => ({ start: round3(w.start), end: round3(w.end), text: w.word })),149 }));150}151152/**153 * Répliques sans alignement par mot : le texte est découpé en phrases (puis en morceaux de 2 lignes au plus) réparties sur la fenêtre154 * [start, end] au prorata du nombre de caractères. Approximation honnête : la synchronisation est au niveau de la phrase.155 */156export function cuesFromSentences(text: string, window: { start: number; end: number }, o?: { maxChars?: number }): Cue[] {157 const maxChars = o?.maxChars ?? DEFAULT_MAX_CHARS;158 const chunks = chunkText(text, maxChars * 2);159 const span = window.end - window.start;160 if (!chunks.length || !(span > 0)) return [];161 const total = chunks.reduce((a, c) => a + c.length, 0);162 let t = window.start;163 return chunks.map((c, i) => {164 const d = (c.length / total) * span;165 const cue = { start: round3(t), end: round3(i === chunks.length - 1 ? window.end : t + d), text: wrapCue(c, maxChars) };166 t += d;167 return cue;168 });169}170171const round3 = (n: number) => Math.round(n * 1000) / 1000;172function stamp(seconds: number, sep: "." | ","): string {173 const ms = Math.max(0, Math.round(seconds * 1000));174 const p = (n: number, l = 2) => String(n).padStart(l, "0");175 return `${p(Math.floor(ms / 3_600_000))}:${p(Math.floor(ms / 60_000) % 60)}:${p(Math.floor(ms / 1000) % 60)}${sep}${p(ms % 1000, 3)}`;176}177const usable = (cues: Cue[]) => cues.filter((c) => c.text.trim() && c.end > c.start).sort((a, b) => a.start - b.start);178179export function toVtt(cues: Cue[]): string {180 const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");181 return `WEBVTT\n\n${usable(cues).map((c, i) => `${i + 1}\n${stamp(c.start, ".")} --> ${stamp(c.end, ".")}\n${esc(c.text.trim())}\n`).join("\n")}`;182}183export function toSrt(cues: Cue[]): string {184 return usable(cues).map((c, i) => `${i + 1}\n${stamp(c.start, ",")} --> ${stamp(c.end, ",")}\n${c.text.trim()}\n`).join("\n");185}186