SRT in, SRT out: a timing-safe workflow for machine subtitling

APIFreeKeyOpenAI · Updated 2026-11-24 · 8 min read

A projector beam on a blank screen with index cards nearby
Translation works on the words; timing stays exactly where it was.

Media server users regularly ask for one more feature in their subtitle tools: plug in an API key and let a model create or translate subtitles. Speech-to-text for creating subtitles from audio is one half of that wish. The other half, translating and cleaning subtitle files that already exist, is pure text work that any chat completions API can do well.

This how-to is for people who manage a media library, translate fan subtitles or localize video for a small channel. It shows how to parse an SRT file, send the dialogue to a model in safe batches, keep every timestamp exactly as it was, and write a valid file back. The script works with any OpenAI-compatible endpoint.

We use the free free-ai endpoint in the examples. It is text only, so it cannot transcribe audio; pair it with a separate speech-to-text tool if you need subtitles from scratch. This site is not affiliated with OpenAI.

Frequently asked questions

What is an SRT file?

SRT is a plain text subtitle format. Each cue has a number, a start and end timestamp, and one or more lines of text, separated from the next cue by a blank line. Its simplicity makes it easy to parse and safe to rebuild.

How does translating subtitles differ from translating prose?

Subtitles are short, split across cues, and must fit on screen while matching speech timing. A good subtitle translation keeps lines brief and preserves the cue structure. Sending the whole file as prose and hoping the model keeps the format intact usually fails.

Can free-ai create subtitles from audio?

No. It accepts text only. Generate a transcript with a speech-to-text tool first, local or hosted, then use the model to translate, fix punctuation or shorten lines.

Which is better for subtitles, a machine translation service or an LLM?

Dedicated translation services are fast, cheap and consistent for straightforward dialogue. An LLM handles context better: slang, jokes, names that recur across cues, and tone. Many people use an LLM when context matters and a translation service for bulk volume.

How do I keep timestamps from being changed?

Never send timestamps to the model. Parse the file, send only numbered text lines, and reassemble the output using the original timing. The model cannot break what it never sees.

How long does a full film take?

A feature film typically has around a thousand to two thousand cues. In batches of forty to sixty cues, that is a few dozen requests. On the free endpoint, with about one request per second and generation time per batch, expect several minutes.

Does the model handle song lyrics and sound descriptions?

It can translate them, but you may want to skip cues in brackets or with music symbols, or tell the model to leave them untouched. Decide based on your audience and the conventions of the target language.

Can I use this for other formats like ASS or VTT?

Yes, with a different parser. The principle is the same: extract the text, translate it by index, and write it back into the original structure. Styling tags in ASS files need extra care so they are not translated.

Step by step

  1. Get a text subtitle file — Start from an existing SRT, or create one with a speech-to-text tool, since the model itself accepts only text.
  2. Parse cues — Split the file into cues and keep each timing line untouched; only the text goes to the model.
  3. Prepare context — Write a short note with the target language, tone, and a glossary of names and recurring terms.
  4. Translate in batches — Send about fifty cues at a time as a numbered JSON object and verify the same numbers come back.
  5. Rebuild and review — Write the translated cues back with the original timing, run length checks, and watch a few scenes.

Why structure matters more than wording

The tempting approach is to paste an entire SRT file into a chat and ask for a translation. It sometimes works for a short clip. For a full episode it falls apart: the model merges cues, drops numbers, rewrites timestamps or stops halfway because the output is too long.

The robust approach treats the file as data. A short script separates timing from text, sends the text in numbered batches, checks that every number comes back, and rebuilds the file. The model only ever does what it is good at, which is language.

Small batches beat one big request

Batches of a few dozen cues fit comfortably in the context window, finish quickly and are easy to retry when something goes wrong.

Context across batches

Include a short note about the show, the main characters' names and the desired register in every request. That keeps translations of names and terms consistent.

Reading speed matters

Viewers need time to read each line before it disappears. Translations into languages that use more words than the source can overflow the available time. Ask the model to prefer concise phrasing, and accept small losses of nuance in exchange for subtitles people can actually read at normal playback speed without pausing the video.

Parsing the SRT file

SRT parsing is simple enough to write by hand. Split the file on blank lines, then read the index, the timing line and the remaining text lines of each block. Keep the original timing string exactly; you will write it back unchanged.

Watch for files with Windows line endings, byte order marks or stray blank lines inside cues. Normalizing line endings first avoids most parsing surprises.

Renumber on output

Writing cue numbers fresh from one upward fixes files whose original numbering had gaps or duplicates, which some players dislike.

import re

def parse_srt(path: str) -> list[dict]:
    raw = open(path, encoding="utf-8-sig").read().replace("\r\n", "\n")
    cues = []
    for block in re.split(r"\n\s*\n", raw.strip()):
        lines = block.split("\n")
        if len(lines) >= 2 and "-->" in lines[1]:
            cues.append({"timing": lines[1].strip(), "text": "\n".join(lines[2:])})
    return cues

def write_srt(cues: list[dict], path: str) -> None:
    with open(path, "w", encoding="utf-8") as f:
        for i, c in enumerate(cues, 1):
            f.write(f"{i}\n{c['timing']}\n{c['text']}\n\n")
A film strip on a light table with tweezers and a loupe
Parse each cue and keep its timing untouched.

Translating in numbered batches

Send each batch as a JSON object mapping cue numbers to text, and ask for the same keys back with translated values. JSON makes it trivial to check that every cue returned and to match translations to timing.

Ask the model to keep line breaks within a cue where possible and to keep each line short. A useful guideline for readability is to stay near the length of the original line.

Verify keys every time

The check that returned keys match sent keys is the single most important line. It catches merged, skipped or invented cues before they corrupt your file.

Pace the requests

The short pause between batches keeps you inside the free endpoint's rate of roughly one request per second per IP. With the openai SDK, 429 and 503 responses are also retried automatically a couple of times.

# parse_srt and write_srt come from the previous snippet
import json, time
from openai import OpenAI

client = OpenAI(base_url="https://api.apifreekeyopenai.com/v1", api_key="not-needed")

SYSTEM = (
    "You translate film subtitles into {lang}. Input is a JSON object of cue number to text. "
    "Return a JSON object with exactly the same keys and translated values. Keep lines short, "
    "keep line breaks, keep names unchanged. Reply with JSON only. Context: {note}"
)

def translate_batch(batch: dict, lang: str, note: str) -> dict:
    for attempt in range(3):
        r = client.chat.completions.create(
            model="free-ai",
            messages=[{"role": "system", "content": SYSTEM.format(lang=lang, note=note)},
                      {"role": "user", "content": json.dumps(batch, ensure_ascii=False)}],
            temperature=0.3,
            max_tokens=4000,
        )
        raw = r.choices[0].message.content.strip().strip("`").removeprefix("json").strip()
        try:
            out = json.loads(raw)
            if set(out) == set(batch):
                return out
        except json.JSONDecodeError:
            pass
        time.sleep(2)
    raise RuntimeError("batch failed after retries")

def translate_cues(cues, lang, note, size=50):
    for start in range(0, len(cues), size):
        part = {str(i): cues[i]["text"] for i in range(start, min(start + size, len(cues)))}
        result = translate_batch(part, lang, note)
        for k, v in result.items():
            cues[int(k)]["text"] = v
        time.sleep(1)
    return cues

cues = parse_srt("episode.en.srt")
write_srt(translate_cues(cues, "Spanish", "Comedy series, casual tone"), "episode.es.srt")

Cleaning machine-generated transcripts

Subtitles produced by speech-to-text tools often need cleanup before or instead of translation: missing punctuation, run-on lines, filler words and lines too long to read in time. The same batch approach works with a different instruction, asking the model to fix punctuation and split long lines without changing meaning.

Be explicit that the model must not add content. Transcripts sometimes contain fragments that look incomplete, and a model eager to help might finish sentences that the speaker never finished.

Do cleanup before translation

A clean source produces a much better translation. Running cleanup and translation as two separate passes is slower but gives you a reviewable intermediate file.

  • Fix capitalization and punctuation.
  • Remove obvious filler like repeated words, if your style allows.
  • Split lines longer than your target length at natural pauses.
  • Never invent dialogue to complete fragments.
Numbered wooden tokens moved between two trays
Send cues by number and check every number comes back.

Handling names, terms and tone

Consistency is where LLMs shine over simple machine translation, but only if you help. Provide a short glossary in the system prompt: character names, recurring places, invented terms and how each should appear in the target language. Mention whether characters use formal or informal address with each other.

For series, keep one glossary file per show and reuse it across episodes. Over a season, that small effort makes the difference between subtitles that feel coherent and ones that drift.

Jokes and wordplay

Literal translations of puns rarely work. Tell the model it may adapt jokes to land in the target language while keeping roughly the same length. Review those cues by hand.

Profanity and mature content

The model refuses less often than commercial assistants, so it generally translates rough dialogue faithfully rather than softening it. Decide your own policy on toning down language for your audience.

Reviewing the result

Machine translation of subtitles is a draft, not a final product. Open the result in a subtitle editor or simply play the video with the new file and watch a few scenes in full. Look for lines that are too long to read in time, mistranslated idioms and inconsistent names.

Automated checks catch the mechanical problems. Count characters per line, flag cues where the translation is much longer than the original, and confirm the file has the same number of cues as the source.

Spot-check, do not skip

Even a few minutes of watching catches problems no script can, such as a line that is technically correct but sounds wrong in context.

def review(src: list[dict], dst: list[dict], max_line: int = 42) -> list[str]:
    issues = []
    if len(src) != len(dst):
        issues.append(f"cue count differs: {len(src)} vs {len(dst)}")
    for i, (a, b) in enumerate(zip(src, dst), 1):
        for line in b["text"].split("\n"):
            if len(line) > max_line:
                issues.append(f"cue {i}: line too long ({len(line)} chars)")
        if len(b["text"]) > 1.6 * max(1, len(a["text"])):
            issues.append(f"cue {i}: much longer than source")
    return issues
A notebook glossary beside coffee and headphones
A small glossary keeps names consistent across a season.

Scaling to a whole library

Once one episode works, wrap the script in a loop over a folder. Skip files that already have a translated version, write logs of failures, and run it overnight. Keep within daily limits: on the free endpoint that is 10,000 requests or 10 million tokens per IP, reset at 00:00 UTC, which covers a lot of subtitles but not an unlimited archive.

For larger volumes or guaranteed turnaround, a paid provider is the better fit. Because the script uses the standard client, switching is a matter of changing the base URL and model name. If an unattended job could run away, add the guardrails described in stopping runaway loops.

Resume after interruptions

Save translated batches as you go. If the job stops, it can pick up from the last completed batch instead of starting the episode again.

Compare against the original audio

Where you understand the spoken language, listening to a scene while reading the translation reveals errors that comparing two text files never will: a line attributed to the wrong speaker, a sarcastic remark translated literally, or a joke that relies on something shown on screen. Spot checks of a few scenes per episode are usually enough to catch patterns.

Respecting rights and conventions

Translate subtitles you have the right to use: your own videos, content with an open license, or personal copies where local law allows. Distributing translated subtitles for commercial releases may raise copyright questions depending on where you live.

Conventions also differ by language and platform: maximum characters per line, reading speed, how to mark songs or off-screen speech. If you publish subtitles, follow the guidelines of the platform or community you publish to. For a broader look at structured outputs that make tasks like this reliable, see reliable JSON output.

Credit machine assistance

Many subtitle communities appreciate a note that a translation was machine-assisted and human-reviewed. It sets expectations and invites corrections.

A shelf of video cassettes and film reels in a cozy room
Scale to a library, but stay inside the daily limits.
Try the free API

Send a prompt to the keyless free-ai endpoint from the home page and see a reply in seconds, no sign-up needed.

Read also