Download lib/srt-parser.ts from d3evil4/scrape: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/d3evil4/scrape/resolve/main/lib/srt-parser.ts
- Command line
-
hf download hf://spaces/d3evil4/scrape/lib/srt-parser.ts
-
curl -L -o srt-parser.ts https://huggingface.co/spaces/d3evil4/scrape/resolve/main/lib/srt-parser.ts
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; | |
| } | |