Technology
Turning YouTube caption files into clean text and SRT, and the four traps on the way 🧹
Source: Dev Community|
6 min read
Quotes encoded twice, tags inside lines, two kinds of English, and subtitles that talk over each other. Hi! 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. One 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. This post skips how you get the file and looks at what's inside it, because that's where the surprises are. 📄 The format YouTube 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: start="0.5" dur="2.1">It's "fine" & good start="2.6" dur="1.9">line break color="#E5E5E5">here start="4.5" dur="1"> start="5.5" dur="2">café ’ok’ One 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. 🪤 Trap 1: the text is encoded twice Look at the first line again: It's. That's an apostrophe encoded as ', and then the & of that encoded again as &. Decode it once, the way any XML parser would, and you get: A 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 '. The fix is to decode until the text stops changing: export A few details that matter: Numbers come in two forms. é is decimal and ’ is hex. Both have to work, and String.fromCodePoint handles characters outside the basic range, which fromCharCode gets wrong. Unknown names stay as they are. &foo; isn't a real entity, so it's left alone instead of becoming an empty string. The loop has a cap. < takes three passes to become <. Three is enough for what YouTube sends, and the cap stops a strange input from looping on. There'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. 🪤 Trap 2: tags and line breaks inside a line The second line has a line break in the middle and a tag around one word. Caption text can carry styling like that, and none of it belongs in a transcript. The whole line parser: Three things happen to every line: Tags go, so here becomes here. Whitespace collapses, so line break becomes line break. Empty lines are dropped. The third in the example is only spaces. Keeping it would put an empty cue in the subtitle file. The regex also accepts a self-closing , which is an empty line written the short way. 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. From the example, the parser returns: [ { start: 0.5, duration: 2.1, text: 'It's "fine" & good' }, { start: 2.6, duration: 1.9, text: 'line break here' }, { start: 5.5, duration: 2, text: 'café ’ok’' }, ] For 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. 🪤 Trap 3: there's more than one English A 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.. So "give me English" isn't one question, it's three: Which of the languages I asked for, in my order? Does en match en-GB? Should a written track beat an automatic one? My rules: My favourite test case: a video has Arabic, automatic English, British English written by a person, and Spanish. Asked for en, which wins? pickTrack(tracks, { languages: ['en'] }).track.languageCode; // 'en-GB' The 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. When 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. 🪤 Trap 4: subtitles that talk over each other An 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. So each end is clamped to the next start: export function toSrt(segments) { return segments.map((s, i) => { // no duration: show it for 2 seconds return `${i + 1} ${srtTime(s.start)} --> ${srtTime(end)} ${s.text} `; }).join(' '); } Three cues, the first one too long, the second with no duration, the third an hour in: 1 00:00:00,500 --> 00:00:03,000 a 2 00:00:03,000 --> 00:00:05,000 b 3 01:01:01,250 --> 01:01:02,750 c The 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. ✅ What I'd tell myself before starting Test with a line that has an apostrophe in it. Double encoding hides until then. Decode, strip tags, collapse whitespace, drop empties, and decide on purpose which order the first two go in. Treat "which language" as a rule you write down, including what happens when nothing matches, and say so in the output. Clamp subtitle end times to the next start, and use the comma. All 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.