{"slug": "turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the", "title": "Turning YouTube caption files into clean text and SRT, and the four traps on the way 🧹", "summary": "A self-taught developer in Nairobi built an Apify Actor that converts YouTube caption files into clean transcript text and SRT subtitles for AI use cases like channel chatbots, summaries and search. The writeup details four parsing traps in YouTube's srv1 XML caption format, including double-encoded entities, styling tags and line breaks inside caption lines, and offers a decode-until-stable entity decoder capped at three passes plus a regex-based line parser.", "body_md": "*Quotes encoded twice, tags inside lines, two kinds of English, and subtitles that talk over each other.*\n\nHi! I'm Tim, a self-taught developer in Nairobi. I build small data tools that run as Apify Actors, serverless jobs that people pay for per result.\n\nOne of them turns YouTube videos into transcripts. Most people want those for AI tools: a chatbot over a channel, summaries, search. Some want subtitle files. Either way, the job ends with the same small problem: a caption file comes in, and clean text has to come out.\n\nThis post skips how you get the file and looks at what's inside it, because that's where the surprises are.\n\nYouTube serves captions in several formats. The simplest is an XML format called `srv1` (tools like yt-dlp can save captions in it too). It looks like this:\n\n```\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<transcript>\n  <text start=\"0.5\" dur=\"2.1\">It&amp;#39;s &amp;quot;fine&amp;quot; &amp;amp; good</text>\n  <text start=\"2.6\" dur=\"1.9\">line\nbreak <font color=\"#E5E5E5\">here</font></text>\n  <text start=\"4.5\" dur=\"1\">   </text>\n  <text start=\"5.5\" dur=\"2\">caf&#233; &#x2019;ok&#x2019;</text>\n</transcript>\n```\n\nOne `<text>` per caption line, with a start time and a duration in seconds. Simple enough to parse with one regex. That small example holds three of the four traps.\n\nLook at the first line again: `It&#39;s`. That's an apostrophe encoded as `'`, and then the `&` of that encoded again as `&`.\n\nDecode it once, the way any XML parser would, and you get:\n\n```\nIt&#39;s &quot;fine&quot; &amp; good\n```\n\nA parser that decodes once saves exactly that. It looks fine in a quick test, because most lines have no quotes, and then every \"it's\" and \"don't\" in a long transcript comes out as `'`.\n\nThe fix is to decode until the text stops changing:\n\n``` js\nconst NAMED = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\", nbsp: ' ' };\n\nfunction decodeOnce(s) {\n    return s.replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi, (m, e) => {\n        if (e[0] === '#') {\n            const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);\n            return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : m;\n        }\n        return NAMED[e.toLowerCase()] ?? m;\n    });\n}\n\n// Caption text is often encoded twice (&amp;#39;), so decode until it stops changing, at most 3 times.\nexport function decodeEntities(s) {\n    let out = String(s ?? '');\n    for (let i = 0; i < 3; i++) {\n        const next = decodeOnce(out);\n        if (next === out) break;\n        out = next;\n    }\n    return out;\n}\n```\n\nA few details that matter:\n\n`é` is decimal and `’` is hex. Both have to work, and `String.fromCodePoint` handles characters outside the basic range, which `fromCharCode` gets wrong.`&foo;` isn't a real entity, so it's left alone instead of becoming an empty string.`&amp;lt;` takes three passes to become `<`. Three is enough for what YouTube sends, and the cap stops a strange input from looping on.\nThere's a trade-off: if a caption genuinely contained the text `<`, it would be decoded too far. In speech captions that almost never happens, so I accepted it.\n\nThe second line has a line break in the middle and a `<font>` tag around one word. Caption text can carry styling like that, and none of it belongs in a transcript.\n\nThe whole line parser:\n\n``` js\nexport function parseSrv1(xml) {\n    const segments = [];\n    const re = /<text\\b([^>]*)>([\\s\\S]*?)<\\/text>|<text\\b([^>]*)\\/>/g;\n    let m;\n    while ((m = re.exec(String(xml ?? '')))) {\n        const attrs = m[1] ?? m[3] ?? '';\n        const start = Number((attrs.match(/\\bstart=\"([\\d.]+)\"/) || [])[1]);\n        const duration = Number((attrs.match(/\\bdur=\"([\\d.]+)\"/) || [])[1] ?? 0);\n        const text = decodeEntities(m[2] ?? '')\n            .replace(/<[^>]+>/g, '')   // drop styling tags\n            .replace(/\\s+/g, ' ')      // line breaks and runs of spaces become one space\n            .trim();\n        if (!Number.isFinite(start) || !text) continue;   // skip blank lines and broken ones\n        segments.push({ start: round(start), duration: round(Number.isFinite(duration) ? duration : 0), text });\n    }\n    return segments;\n}\n\nconst round = (n) => Math.round(n * 1000) / 1000;\n```\n\nThree things happen to every line:\n\n`<font color=\"#E5E5E5\">here</font>` becomes `here`.` line\\nbreak` becomes `line break`.`<text>` in the example is only spaces. Keeping it would put an empty cue in the subtitle file.\nThe regex also accepts a self-closing `<text ... />`, which is an empty line written the short way.\n\n**Order matters here.** Tags are stripped after decoding. That means an encoded `<` followed later by `>` in the same line would be decoded into something that looks like a tag and then removed. Captions of speech practically never contain that. If yours might, strip tags first and decode second.\n\nFrom the example, the parser returns:\n\n```\n[\n  { start: 0.5, duration: 2.1, text: 'It\\'s \"fine\" & good' },\n  { start: 2.6, duration: 1.9, text: 'line break here' },\n  { start: 5.5, duration: 2,   text: 'café ’ok’' },\n]\n```\n\nFor AI tools I join those into one block of text. A 15-minute speech comes out at about 2,300 words, small enough to hand to a model whole. The segments stay in the output too, because timestamps are what let you link an answer back to the second it was said.\n\nA video usually has several caption tracks. Each has a language code, and YouTube marks the ones its speech recognition made: `kind` is `\"asr\"`, or the track's `vssId` starts with `a.`.\n\nSo \"give me English\" isn't one question, it's three:\n\n`en` match `en-GB`?\nMy rules:\n\n``` js\nexport const isAuto = (track) => track?.kind === 'asr' || /^a\\./.test(track?.vssId ?? '');\nexport const baseLanguage = (code) => String(code ?? '').toLowerCase().split(/[-_]/)[0];\n\nexport function pickTrack(tracks, { languages = ['en'], preferManual = true, fallbackToAny = true } = {}) {\n    const list = (tracks ?? []).filter((t) => t?.baseUrl);\n    if (!list.length) return null;\n    for (const lang of languages) {\n        const exact = (t) => String(t.languageCode ?? '').toLowerCase() === lang;\n        const loose = (t) => baseLanguage(t.languageCode) === baseLanguage(lang);\n        const candidates = [...list.filter(exact), ...list.filter((t) => !exact(t) && loose(t))];\n        if (!candidates.length) continue;\n        const manual = candidates.find((t) => !isAuto(t));\n        const auto = candidates.find((t) => isAuto(t));\n        return { track: preferManual ? (manual ?? auto) : (auto ?? manual), matched: true };\n    }\n    if (!fallbackToAny) return null;\n    // Nothing matched: the automatic track is in the language actually spoken, so it's the best guess.\n    return { track: list.find(isAuto) ?? list[0], matched: false };\n}\n```\n\nMy favourite test case: a video has Arabic, automatic English, British English written by a person, and Spanish. Asked for `en`, which wins?\n\n``` js\n// T(code, auto) builds a fake track for the test\nconst tracks = [T('ar'), T('en', true), T('en-GB'), T('es')];\npickTrack(tracks, { languages: ['en'] }).track.languageCode;   // 'en-GB'\n```\n\nThe written `en-GB` beats the automatic `en`, even though `en` is the exact match. A person's captions have punctuation and fewer misheard words, and for a transcript that matters more than the region. If someone wants the automatic one, `preferManual: false` flips it.\n\nWhen nothing matches, I return `matched: false` and say so in the output. Quietly handing back Arabic to someone who asked for English would look like a bug.\n\nAn SRT file is the easy part, except for one thing. Each cue needs an end time, and `start + duration` doesn't always stop before the next line starts. When cues overlap, players show two lines stacked on top of each other.\n\nSo each end is clamped to the next start:\n\n``` js\nfunction srtTime(seconds) {\n    const ms = Math.max(0, Math.round(seconds * 1000));\n    const h = Math.floor(ms / 3_600_000);\n    const m = Math.floor((ms % 3_600_000) / 60_000);\n    const s = Math.floor((ms % 60_000) / 1000);\n    const pad = (n, w = 2) => String(n).padStart(w, '0');\n    return `${pad(h)}:${pad(m)}:${pad(s)},${pad(ms % 1000, 3)}`;\n}\n\nexport function toSrt(segments) {\n    return segments.map((s, i) => {\n        const next = segments[i + 1];\n        let end = s.start + (s.duration || 2);       // no duration: show it for 2 seconds\n        if (next && end > next.start) end = next.start;\n        return `${i + 1}\\n${srtTime(s.start)} --> ${srtTime(end)}\\n${s.text}\\n`;\n    }).join('\\n');\n}\n```\n\nThree cues, the first one too long, the second with no duration, the third an hour in:\n\n``` php\n1\n00:00:00,500 --> 00:00:03,000\na\n\n2\n00:00:03,000 --> 00:00:05,000\nb\n\n3\n01:01:01,250 --> 01:01:02,750\nc\n```\n\nThe first cue wanted to run until 5.5 seconds and was cut at 3.0, where the second starts. The second had no duration, so it got 2 seconds. And SRT wants a **comma** before the milliseconds, not a dot. A dot is WebVTT's style, and some players and editors won't read an SRT file that uses one.\n\nAll of these are pure functions with no network calls, so each one has a small unit test, the British English case included. Tests like that are cheap to write and they pin down the decisions, not just the parsing.", "url": "https://wpnews.pro/news/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the", "canonical_source": "https://dev.to/timmkal01/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the-way-3fdc", "published_at": "2026-11-26 03:59:09+00:00", "updated_at": "2026-11-26 04:13:50.131084+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "natural-language-processing"], "entities": ["YouTube", "Apify", "yt-dlp"], "also_reported_by": [], "takeaway": "YouTube srv1 captions are often double-encoded, so decode entities repeatedly until the text stops changing (capped at three passes) and strip inline styling tags and line breaks before treating each caption line as transcript text.", "recommendation": {"advice": "When ingesting YouTube srv1 captions, loop entity decoding until output is stable (max three passes) and strip tags and whitespace, since a single decode leaves apostrophes as &#39;.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the", "markdown": "https://wpnews.pro/news/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the.md", "text": "https://wpnews.pro/news/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the.txt", "jsonld": "https://wpnews.pro/news/turning-youtube-caption-files-into-clean-text-and-srt-and-the-four-traps-on-the.jsonld"}}