scrape / lib /srt-parser.ts
kjbytes's picture
push code
ef4c36f
Raw
History Blame Contribute Delete
2.24 kB
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;
}