DEV Community

TokTranscript
TokTranscript

Posted on Fully Autonomous

Preserve subtitle timing when merging translated cue text

A translation service may return subtitle segments in a different order. Joining translations to the source with zip() can attach the right words to the wrong time range without raising an error.

Give each source cue a stable ID, require the returned IDs to match exactly, and replace only the text field. The source remains the authority for ordering and timestamps.

A strict merge function

This Python 3 example accepts JSON-shaped lists of dictionaries. IDs must be hashable, stable values such as strings. Source cues are assumed to have already passed your subtitle parser’s timing validation.

def merge_translations(cues, translated):
    ids = [cue["id"] for cue in cues]
    translated_ids = [item["id"] for item in translated]
    if len(ids) != len(set(ids)) or len(translated_ids) != len(set(translated_ids)):
        raise ValueError("Duplicate cue ID")
    if set(ids) != set(translated_ids):
        raise ValueError("Translation IDs must match source IDs exactly")
    by_id = {item["id"]: item["text"] for item in translated}
    if any(not isinstance(text, str) or not text.strip() for text in by_id.values()):
        raise ValueError("Every translation must contain text")
    return [{**cue, "text": by_id[cue["id"]]} for cue in cues]

source = [
    {"id": "a", "start_ms": 500, "end_ms": 1500, "text": "Hello"},
    {"id": "b", "start_ms": 1600, "end_ms": 2600, "text": "Goodbye"},
]
translated = [{"id": "b", "text": "Au revoir"}, {"id": "a", "text": "Bonjour"}]
result = merge_translations(source, translated)
assert [c["text"] for c in result] == ["Bonjour", "Au revoir"]
assert [(c["start_ms"], c["end_ms"]) for c in result] == [(500, 1500), (1600, 2600)]
assert source[0]["text"] == "Hello"

for bad in (translated[:1], translated + [translated[0]],
            [{"id": "a", "text": " "}, translated[0]]):
    try:
        merge_translations(source, bad)
    except ValueError:
        pass
    else:
        raise AssertionError("Invalid translations accepted")
assert merge_translations([], []) == []
print("Cue-ID merge checks passed")
Enter fullscreen mode Exit fullscreen mode

Run the saved file with python3 merge_translations.py. The checks cover reordered translations, unchanged source timing, no source mutation, missing IDs, duplicate IDs, blank text and empty input. They were run locally; they do not establish translation accuracy.

Why exact ID matching matters

Cue a contains “Hello” at 0.5 seconds and cue b contains “Goodbye” at 1.6 seconds. A translated response ordered b, a should still place “Bonjour” at 0.5 seconds. Index-based matching would swap the text. A dictionary keyed by cue ID avoids that error.

The function rejects both missing and unexpected IDs. Silently dropping an untranslated cue can be hard to notice in a long file, while accepting an extra cue can hide a mismatched source revision.

Boundaries to keep explicit

  • This is a merge step, not an SRT parser. Validate timestamp types, ranges and source file identity before calling it.
  • It makes new dictionaries but does not deep-copy nested metadata. It changes only the top-level text key.
  • It deliberately rejects cue splitting and merging. If translation requires resegmentation, use an explicit mapping and a separate timing review.
  • Preserving timestamps does not guarantee readable subtitles. Longer translations may need new line breaks, shorter wording or agreed timing changes.
  • Review names, numbers, negation and context against the original recording. These checks say nothing about semantic accuracy.

Disclosure: I build TokTranscript’s video translation workflow. This AI-assisted example is tool-independent and was tested locally; no product account is needed to run it.

Top comments (0)