Merging consecutive subtitle cues from one speaker: a small Python function and the gap rule it depends on

Merging consecutive subtitle cues from one speaker: a small Python function and the gap rule it depends on

SRT2Word

A subtitle file breaks speech into short cues for the screen, not for reading. If you want a transcript, a line like "Hello" followed by "and welcome." should usually become one sentence. This post shows a function that merges neighbouring cues from the same speaker, and explains the one parameter that decides whether the output is readable.

The idea

Merge two cues when two things hold: the speaker is the same, and the pause between them is short. The pause is the start of the next cue minus the end of the previous one. A long pause usually means a new thought, so keep the cues apart.

The code

This version assumes speaker labels appear at the start of a cue in the form - Name: text. Many files do not have labels at all, in which case every cue has speaker None and the function merges purely on the gap.

import re

def merge(cues, gap=1.5):
    """cues: list of (start_seconds, end_seconds, text)."""
    out = []
    for start, end, text in cues:
        m = re.match(r"^[-\u2013]\s*([A-Z][A-Za-z ]{0,20}):\s*(.*)", text)
        speaker, body = (m.group(1), m.group(2)) if m else (None, text)
        if out and out[-1]["speaker"] == speaker and start - out[-1]["end"] <= gap:
            out[-1]["text"] += " " + body
            out[-1]["end"] = end
        else:
            out.append(dict(speaker=speaker, start=start, end=end, text=body))
    return out

A run on four cues

I fed it four cues: Ana at 0.0 to 1.5 ("Hello"), Ana at 1.6 to 3.0 ("and welcome."), Ben at 3.2 to 4.0 ("Thanks."), and Ben again at 9.0 to 10.0 ("Later."). The output was three entries: Ana from 0.0 to 3.0 saying "Hello and welcome.", Ben from 3.2 to 4.0, and a separate Ben entry at 9.0. The last one stayed apart because the pause was five seconds, longer than the 1.5 second default.

Choosing the gap

The default of 1.5 seconds is a starting guess, not a rule. Fast conversation wants a smaller gap, because speakers answer within a second. A lecture with one speaker can use a larger one. Try a few values on one file and read the result before applying it to a batch.

What it does not do

It does not detect a speaker change when the file has no labels, and the label pattern above only matches names that start with a capital letter and are short. It also keeps no timing inside a merged block beyond the first start and last end.

If you only need the document

SRT2Word has a speaker-merge option in the browser: paste or drop an SRT, VTT, ASS, or Zoom transcript and download a Word file. See SRT to Word for the steps.

Report Page