File size: 2,239 Bytes
ef4c36f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { v4 as uuidv4 } from "uuid";
import type { Caption } from "@/types";

function parseTimestamp(value: string): number {
  const match = value.trim().match(/(\d{2}):(\d{2}):(\d{2})[,.](\d{3})/);
  if (!match) return 0;
  const [, hours, minutes, seconds, millis] = match;
  return (
    Number(hours) * 3600000 +
    Number(minutes) * 60000 +
    Number(seconds) * 1000 +
    Number(millis)
  );
}

export function parseWordSrt(content: string): Caption[] {
  const blocks = content.trim().split(/\n\s*\n/);
  const captions: Caption[] = [];

  for (const block of blocks) {
    const lines = block.split("\n").map((l) => l.trim()).filter(Boolean);
    if (lines.length < 2) continue;

    const timingLine = lines.find((l) => l.includes("-->"));
    if (!timingLine) continue;

    const [startRaw, endRaw] = timingLine.split("-->").map((s) => s.trim());
    const textLines = lines.slice(lines.indexOf(timingLine) + 1);
    const text = textLines.join(" ").trim();
    if (!text) continue;

    captions.push({
      id: uuidv4(),
      text,
      startMs: parseTimestamp(startRaw),
      endMs: parseTimestamp(endRaw),
    });
  }

  return captions;
}

export function parseSrt(content: string): Caption[] {
  const blocks = content.trim().split(/\n\s*\n/);
  const captions: Caption[] = [];

  for (const block of blocks) {
    const lines = block.split("\n").map((l) => l.trim()).filter(Boolean);
    if (lines.length < 2) continue;

    const timingLine = lines.find((l) => l.includes("-->"));
    if (!timingLine) continue;

    const [startRaw, endRaw] = timingLine.split("-->").map((s) => s.trim());
    const textLines = lines.slice(lines.indexOf(timingLine) + 1);
    const text = textLines.join(" ").trim();
    if (!text) continue;

    const words = text.split(/\s+/).filter(Boolean);
    const startMs = parseTimestamp(startRaw);
    const endMs = parseTimestamp(endRaw);
    const totalDuration = Math.max(endMs - startMs, 1);
    const perWord = totalDuration / words.length;

    words.forEach((word, index) => {
      captions.push({
        id: uuidv4(),
        text: word,
        startMs: startMs + index * perWord,
        endMs: startMs + (index + 1) * perWord,
      });
    });
  }

  return captions;
}