SPB Git

Repository Public

captions.ts 6.2 KB 87 lines typescript

1/**2 * WebVTT validation for the studio, stricter than what the player needs: the header and timing syntax, cues3 * that end before they start or carry negative or absurd times, cues out of order or overlapping, empty4 * cues, cues running past the end of the video, reading speed, and the language tag. Errors refuse the file;5 * warnings are shown to the editor, who decides.6 */7import { z } from "zod";8import { Transcript } from "../modules/content-schema/schema";9import { parseVtt, type Cue } from "../modules/learning-engine/vtt";1011export interface CaptionReport { ok: boolean; cues: number; duration: number; errors: string[]; warnings: string[]; preview: Cue[] }1213/** BCP 47, reduced to what a caption track needs: language, optional script, optional region (fr, fr-CA, zh-Hant-TW). */14export const LANG = /^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|\d{3}))?$/;15export function normaliseLang(input: string): string | null {16  const parts = input.trim().replace(/_/g, "-").split("-");17  const out = parts.map((p, i) => (i === 0 ? p.toLowerCase() : p.length === 4 ? p[0]!.toUpperCase() + p.slice(1).toLowerCase() : p.toUpperCase())).join("-");18  return LANG.test(out) ? out : null;19}20export function langLabel(lang: string): string {21  try { const name = new Intl.DisplayNames(["fr-CA"], { type: "language" }).of(lang); return name ? name[0]!.toUpperCase() + name.slice(1) : lang; } catch { return lang; }22}2324const clock = (t: number) => { const s = Math.floor(t); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };2526export function validateCaptions(source: string, opts: { videoDuration?: number | null } = {}): CaptionReport {27  const errors: string[] = [], warnings: string[] = [];28  if (source.length > 5_000_000) return { ok: false, cues: 0, duration: 0, errors: ["Fichier de sous-titres trop volumineux (5 Mo au plus)."], warnings, preview: [] };29  if (source.includes("\0")) return { ok: false, cues: 0, duration: 0, errors: ["Le fichier contient des octets nuls : ce n'est pas du texte WebVTT."], warnings, preview: [] };30  // Timing lines that the lenient reader would skip silently are reported here.31  for (const line of source.replace(/\r\n?/g, "\n").split("\n")) {32    if (!line.includes("-->")) continue;33    if (/-\d/.test(line.split("-->")[0] ?? "") || /-->\s*-\d/.test(line)) errors.push(`temps négatif : « ${line.trim().slice(0, 60)} »`);34    else if (!/^\s*(?:\d{2,}:)?[0-5]\d:[0-5]\d\.\d{3}\s+-->\s+(?:\d{2,}:)?[0-5]\d:[0-5]\d\.\d{3}(?:\s+.*)?$/.test(line)) errors.push(`repère temporel mal formé : « ${line.trim().slice(0, 60)} » (attendu : mm:ss.mmm --> mm:ss.mmm)`);35  }36  const parsed = parseVtt(source);37  errors.push(...parsed.errors.filter((e) => !e.startsWith("repère temporel invalide") || !errors.some((x) => x.startsWith("repère temporel mal formé") || x.startsWith("temps négatif"))));38  const cues = parsed.cues;39  if (!cues.length && !errors.length) errors.push("aucune réplique dans le fichier");40  let overlaps = 0, fast = 0;41  cues.forEach((c, i) => {42    const prev = cues[i - 1];43    if (prev && c.start < prev.end - 0.001) { overlaps++; if (overlaps <= 5) errors.push(`chevauchement : la réplique de ${clock(c.start)} commence avant la fin de la précédente (${clock(prev.end)})`); }44    if (c.end - c.start > 20) warnings.push(`réplique très longue à ${clock(c.start)} (${Math.round(c.end - c.start)} s)`);45    if (c.end > c.start && c.text.length / (c.end - c.start) > 25) fast++;46    if (opts.videoDuration && c.start > opts.videoDuration + 0.5) errors.push(`la réplique de ${clock(c.start)} commence après la fin de la vidéo (${clock(opts.videoDuration)})`);47  });48  if (overlaps > 5) errors.push(`… et ${overlaps - 5} autres chevauchements`);49  if (fast) warnings.push(`${fast} réplique${fast > 1 ? "s" : ""} à plus de 25 caractères par seconde (lecture difficile)`);50  const duration = cues.length ? cues[cues.length - 1]!.end : 0;51  if (opts.videoDuration && cues.length) {52    if (duration > opts.videoDuration + 2) warnings.push(`la dernière réplique finit à ${clock(duration)}, après la fin de la vidéo (${clock(opts.videoDuration)})`);53    if (duration < opts.videoDuration * 0.5) warnings.push(`les sous-titres ne couvrent que ${Math.round((duration / opts.videoDuration) * 100)} % de la durée de la vidéo`);54  }55  const unique = [...new Set(errors)];56  return { ok: unique.length === 0, cues: cues.length, duration, errors: unique.slice(0, 40), warnings: [...new Set(warnings)].slice(0, 40), preview: cues.slice(0, 400) };57}5859const JsonTranscript = z.union([60  Transcript,61  z.array(z.object({ start: z.number().nonnegative(), end: z.number().positive(), text: z.string().min(1) })).min(1).transform((segments) => ({ lang: "", segments })),62]);6364/**65 * Converts a transcript given as WebVTT or as JSON ({ lang, segments } or a bare array of segments) into the66 * searchable format the player and the search index read. Consecutive caption cues are kept as they are:67 * one segment per cue, so a search hit lands on the right second.68 */69export function toTranscript(source: string, format: "vtt" | "json", lang: string): { transcript: Transcript; errors: string[] } {70  if (format === "vtt") {71    const r = validateCaptions(source);72    return { transcript: { lang, segments: r.ok ? parseVtt(source).cues.map((c) => ({ start: c.start, end: c.end, text: c.text })) : [] }, errors: r.errors };73  }74  let raw: unknown;75  try { raw = JSON.parse(source); } catch { return { transcript: { lang, segments: [] }, errors: ["JSON invalide"] }; }76  const p = JsonTranscript.safeParse(raw);77  if (!p.success) return { transcript: { lang, segments: [] }, errors: [`format inattendu : ${p.error.issues[0]?.path.join(".")} — ${p.error.issues[0]?.message}`] };78  const segments = p.data.segments.map((s) => ({ start: s.start, end: s.end, text: s.text.replace(/\s+/g, " ").trim() })).filter((s) => s.text);79  const errors: string[] = [];80  segments.forEach((s, i) => {81    if (s.end <= s.start) errors.push(`segment ${i + 1} : fin avant le début`);82    if (i > 0 && s.start < segments[i - 1]!.start) errors.push(`segment ${i + 1} : dans le désordre`);83  });84  if (!segments.length) errors.push("aucun segment");85  return { transcript: { lang: p.data.lang || lang, segments }, errors: errors.slice(0, 20) };86}87
Files main
Menu

Theme