export interface SubtitleEntry { id: number; startTime: string; endTime: string; text: string; translatedText?: string; } export function parseSRT(content: string): SubtitleEntry[] { const entries: SubtitleEntry[] = []; const blocks = content.trim().replace(/\r\n/g, '\n').split(/\n\n+/); for (const block of blocks) { const lines = block.trim().split('\n'); if (lines.length < 3) continue; const id = parseInt(lines[0], 10); if (isNaN(id)) continue; const timeLine = lines[1]; const timeMatch = timeLine.match( /(\d{2}:\d{2}:\d{2}[,\.]\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2}[,\.]\d{3})/ ); if (!timeMatch) continue; const text = lines.slice(2).join('\n'); entries.push({ id, startTime: timeMatch[1], endTime: timeMatch[2], text, }); } return entries; } export function parseVTT(content: string): SubtitleEntry[] { const entries: SubtitleEntry[] = []; // Remove WEBVTT header and any metadata const cleaned = content.replace(/^WEBVTT[^\n]*\n/, '').replace(/^NOTE[^\n]*\n(?:[^\n]+\n)*/gm, ''); const blocks = cleaned.trim().replace(/\r\n/g, '\n').split(/\n\n+/); let idCounter = 1; for (const block of blocks) { const lines = block.trim().split('\n'); if (lines.length < 2) continue; let timeLineIndex = 0; // Check if first line is a cue identifier (no -->) if (!lines[0].includes('-->')) { timeLineIndex = 1; } const timeLine = lines[timeLineIndex]; if (!timeLine) continue; const timeMatch = timeLine.match( /(\d{2}:\d{2}:\d{2}[,\.]\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2}[,\.]\d{3})/ ); if (!timeMatch) continue; const text = lines.slice(timeLineIndex + 1).join('\n'); entries.push({ id: idCounter++, startTime: timeMatch[1], endTime: timeMatch[2], text, }); } return entries; } export function parseSubtitleFile(content: string, filename: string): SubtitleEntry[] { const ext = filename.toLowerCase().split('.').pop(); if (ext === 'vtt') { return parseVTT(content); } return parseSRT(content); } export function entriesToSRT(entries: SubtitleEntry[]): string { return entries .map((entry) => { const text = entry.translatedText || entry.text; return `${entry.id}\n${entry.startTime} --> ${entry.endTime}\n${text}`; }) .join('\n\n'); } export function entriesToVTT(entries: SubtitleEntry[]): string { const lines = ['WEBVTT', '']; for (const entry of entries) { const text = entry.translatedText || entry.text; lines.push(`${entry.startTime} --> ${entry.endTime}`); lines.push(text); lines.push(''); } return lines.join('\n'); }