Intermediate 12 minDaily plan

Translate SRT or VTT subtitles with Ollama

BestLLMfor — Translate subtitles — SRT, VTT + Ollama

Translating subtitles with Ollama seems simple: you paste the file into the chat and ask it to "translate into French." That's the surest way to end up with shifted timestamps, merged cues, or a missing WebVTT header. This guide offers a safer method: a Python script splits the SRT or VTT file, sends only the cue text to the local model, copies the timestamps over unchanged, and then a second check compares the translation with the original. The script is provided as a starting point; it wasn't run on a real file while this guide was written, and human review remains essential.

By Mohamed Meguedmi·Update 2026-11-29·Tested on Windows, macOS, and Linux

#Why separate the text from the timestamps

A subtitle file mixes two very different kinds of content: timing data, which must stay accurate to the millisecond, and text meant for the viewer. An LLM is built for the second, not the first. If you hand it the whole file, nothing stops it from "fixing" a timestamp, merging two short lines into one, deleting a blank line that separates two blocks, or adding an introductory sentence before the content. Any of these changes can break the sync or even make the file unreadable for the video player.

So this guide follows a strict rule: the model never sees a timestamp. The script reads the file, sets aside everything that isn't cue text (SRT numbers, WebVTT identifiers and settings, NOTE, STYLE, and REGION blocks), sends the text in small numbered batches, then rebuilds the file by putting each translation back under its original timing line. A separate check then verifies that the structure is identical to the original's. Translating subtitles with Ollama then becomes a text task you can review, not a rewrite of the file where you don't know what was changed.

The benefit of a local model is the same as for transcription: the dialogue content never leaves your machine. This is useful for internal videos, training sessions, unpublished interviews, or meeting recordings. If your subtitles don't exist yet, the companion guide on Whisper and Ollama explains how to produce a local transcript before translating it.

#SRT and WebVTT: what you need to preserve

The complete kit for preparing your social media content.

Benefit from our experience and a guided path to prepare your videos and carousels with your local studio.

  • Lifetime online access
  • PDF + files
  • Refunded within 30 days

The two formats look alike but don't have the same status. WebVTT is defined by a W3C specification (https://www.w3.org/TR/webvtt1/, accessed October 30, 2026). SRT has no specification published by a standards body: it's a de facto format that originated with the SubRip software, and which variants are tolerated depends on the player. Here's a typical SRT block:

SRT example (fictional)
1
00:00:01,000 --> 00:00:03,500
Good morning, everyone.

2
00:00:04,000 --> 00:00:06,200
<i>Let's get started.</i>

And the WebVTT equivalent. Note the required header, the period (not a comma) before the milliseconds, the optional cue identifier, and the position settings placed after the end timestamp:

WebVTT example (fictional)
WEBVTT

NOTE Fichier d'exemple, à ne pas traduire

intro-1
00:01.000 --> 00:03.500 line:85% align:center
<v Alice>Good morning, everyone.

00:04.000 --> 00:06.200
<i>Let's get started.</i>
WEBVTT header
The specification requires the file to start with the string WEBVTT (optionally preceded by a byte order mark), followed by a space, a tab, or a line break. A file whose first line has been translated or deleted is no longer valid WebVTT.
Timing lines
Start, the --> arrow, end, then in WebVTT any cue settings (position, line, align, size, region, vertical). They must be copied byte for byte; the script doesn't interpret them, it just moves them.
Blank lines
A blank line ends a block in both formats. A blank line inserted in the middle of a translation splits the cue in two and shifts everything else in the file.
String -->
The WebVTT specification forbids this string in cue text, because it's used to recognize timing lines. A model that writes an arrow in its translation can confuse parsers.
Balises
WebVTT defines text tags: <i>, <b>, <u>, <c>, <v> for the speaker, <lang>, <ruby>, and inline timestamps for progressive display. Many SRT files also contain <i> or <font>, and sometimes curly-brace codes such as {\an8}. They must survive translation, in the same order.
NOTE, STYLE, REGION blocks
WebVTT comments, style sheets, and display regions. They aren't displayed as subtitles, and the script copies them over without sending them to the model.
Entities
In WebVTT, the & and < characters in text are written as &amp; and &lt;. If the model replaces an entity with the raw character, the tag check may miss it, so check for this during review.
i
Encodage
The WebVTT specification requires UTF-8. Older SRT files are sometimes in Windows-1252 or ISO-8859-1; the script reads and writes UTF-8 and will fail on any other encoding. First convert the original into a copy, for example with iconv -f WINDOWS-1252 -t UTF-8, then check the accented characters in an editor.

#Prerequisites

Ollama installed and started
By default, the server listens on http://localhost:11434. The guide "Install Ollama in 5 Minutes" covers Windows, macOS, and Linux.
A version of Ollama that accepts a JSON schema
The script passes a JSON schema in the format field of /api/chat to get a structured response. This feature doesn't exist in older versions: check the Ollama API documentation (https://github.com/ollama/ollama/blob/main/docs/api.md) for your version.
A multilingual model
A recent general-purpose model that covers both the source and target languages. No model is recommended here based on a single test: pick one from the catalog, try it on an excerpt, then compare. Q4_K_M ballpark figures: about 5 GB of VRAM for a 7B model, 9 GB for a 14B.
Python 3.8 or later
The script uses only the standard library (json, re, urllib): no dependencies to install.
A working copy
Put the original in a dedicated folder. The script refuses to overwrite an existing file, but a backup is still the best protection.
Terminal
ollama --version
ollama list
curl http://localhost:11434/api/tags

The last command returns the list of locally available models as JSON. Note the exact name of the one you'll use, as it appears in ollama list, including the tag.

#Step 1: The translation and verification script

The script fits in a single file, soustitres.py, with two commands: traduire and verifier. Parsing splits the file on blank lines. A block that contains a timing line becomes a cue (lines before the arrow, timing line, text lines), and everything else is kept as is. Only the cue text is sent to Ollama, in batches of 20, with a numeric ID for each cue. The response is constrained by a JSON schema, and the script requires the IDs to come back in exactly the same order. If they don't, it retries once, then stops without writing anything.

soustitres.py
#!/usr/bin/env python3
# soustitres.py : traduire le texte d’un fichier SRT ou WebVTT avec Ollama,
# sans jamais envoyer ni modifier les numéros, identifiants et horodatages.
import argparse, json, os, re, sys, urllib.request
from pathlib import Path

OLLAMA_URL = os.environ.get('OLLAMA_URL', 'http://localhost:11434')
BALISES = re.compile(r'<[^>]+>|\{\\[^}]*\}')
SRT_TEMPS = re.compile(r'^[0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} --> [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}')
VTT_TEMPS = re.compile(r'^(?:[0-9]{2,}:)?[0-9]{2}:[0-9]{2}\.[0-9]{3}[ \t]+-->[ \t]+(?:[0-9]{2,}:)?[0-9]{2}:[0-9]{2}\.[0-9]{3}')


def lire_blocs(chemin):
    brut = Path(chemin).read_text(encoding='utf-8-sig')
    brut = brut.replace('\r\n', '\n').replace('\r', '\n')
    blocs = []
    for bloc in re.split(r'\n(?:[ \t]*\n)+', brut.strip('\n')):
        lignes = bloc.split('\n')
        i = next((n for n, l in enumerate(lignes) if '-->' in l), None)
        if i is None or lignes[0].startswith(('WEBVTT', 'NOTE', 'STYLE', 'REGION')):
            blocs.append({'type': 'brut', 'lignes': lignes})
        else:
            blocs.append({'type': 'cue', 'avant': lignes[:i],
                          'temps': lignes[i], 'texte': lignes[i + 1:]})
    return blocs


def ecrire_blocs(blocs, chemin):
    parties = []
    for b in blocs:
        if b['type'] == 'brut':
            parties.append('\n'.join(b['lignes']))
        else:
            parties.append('\n'.join(b['avant'] + [b['temps']] + b['texte']))
    Path(chemin).write_text('\n\n'.join(parties) + '\n', encoding='utf-8')


SCHEMA = {
    'type': 'object',
    'properties': {'items': {'type': 'array', 'items': {
        'type': 'object',
        'properties': {'id': {'type': 'integer'}, 'text': {'type': 'string'}},
        'required': ['id', 'text']}}},
    'required': ['items'],
}

CONSIGNE = (
    'Tu traduis des sous-titres vers la langue suivante : {langue}. '
    'Tu reçois un objet JSON contenant une liste items. Pour chaque item, '
    'traduis seulement le champ text et renvoie le même id. Garde le même '
    'nombre d’items et le même ordre. Conserve à l’identique les balises '
    'entre chevrons ou accolades et les sauts de ligne. Ne fusionne pas et '
    'ne découpe pas les items. Aucun commentaire, aucune ligne vide.'
)


def appeler_ollama(modele, langue, lot):
    charge = {
        'model': modele,
        'stream': False,
        'format': SCHEMA,
        'options': {'temperature': 0},
        'messages': [
            {'role': 'system', 'content': CONSIGNE.format(langue=langue)},
            {'role': 'user', 'content': json.dumps({'items': lot}, ensure_ascii=False)},
        ],
    }
    requete = urllib.request.Request(
        OLLAMA_URL + '/api/chat',
        data=json.dumps(charge).encode('utf-8'),
        headers={'Content-Type': 'application/json'},
    )
    with urllib.request.urlopen(requete, timeout=600) as r:
        reponse = json.load(r)
    return json.loads(reponse['message']['content'])['items']


def traduire(args):
    if not args.modele:
        sys.exit('Indiquez un modèle avec --modele ou la variable OLLAMA_MODEL.')
    sortie = Path(args.sortie)
    if sortie.exists():
        sys.exit('Le fichier de sortie existe déjà : choisissez un autre nom.')
    blocs = lire_blocs(args.entree)
    cues = [b for b in blocs if b['type'] == 'cue']
    for debut in range(0, len(cues), args.lot):
        tranche = cues[debut:debut + args.lot]
        lot = [{'id': debut + n, 'text': '\n'.join(c['texte'])}
               for n, c in enumerate(tranche)]
        attendus = [x['id'] for x in lot]
        for essai in range(2):
            items = appeler_ollama(args.modele, args.langue, lot)
            if [x.get('id') for x in items] == attendus:
                break
        else:
            sys.exit(f'Lot {debut} : identifiants différents après 2 essais, arrêt.')
        for c, x in zip(tranche, items):
            c['texte'] = x['text'].strip('\n').split('\n')
        print(f'{debut + len(tranche)}/{len(cues)} répliques', file=sys.stderr)
    ecrire_blocs(blocs, sortie)


def verifier(args):
    orig, trad = lire_blocs(args.original), lire_blocs(args.traduction)
    vtt = Path(args.original).suffix.lower() == '.vtt'
    motif = VTT_TEMPS if vtt else SRT_TEMPS
    erreurs, alertes = [], []
    if vtt:
        tete = trad[0]['lignes'][0] if trad and trad[0]['type'] == 'brut' else ''
        if not re.match(r'WEBVTT($|[ \t])', tete):
            erreurs.append('En-tête WEBVTT absent ou modifié.')
    if len(orig) != len(trad):
        erreurs.append(f'Nombre de blocs : {len(orig)} dans l’original, {len(trad)} dans la traduction.')
    for n, (a, b) in enumerate(zip(orig, trad), 1):
        if a['type'] != b['type']:
            erreurs.append(f'Bloc {n} : nature du bloc différente.')
            continue
        if a['type'] == 'brut':
            if a['lignes'] != b['lignes']:
                erreurs.append(f'Bloc {n} : bloc non traduisible modifié.')
            continue
        if a['avant'] != b['avant'] or a['temps'] != b['temps']:
            erreurs.append(f'Bloc {n} : numéro, identifiant ou horodatage modifié.')
        if not motif.match(b['temps']):
            alertes.append(f'Bloc {n} : ligne de temps hors du motif attendu.')
        source, texte = '\n'.join(a['texte']), '\n'.join(b['texte'])
        if not texte.strip():
            erreurs.append(f'Bloc {n} : texte vide.')
        if '-->' in texte:
            erreurs.append(f'Bloc {n} : la chaîne --> apparaît dans le texte.')
        if BALISES.findall(source) != BALISES.findall(texte):
            erreurs.append(f'Bloc {n} : balises différentes de l’original.')
        na, nb = len(a['texte']), len(b['texte'])
        if na != nb:
            alertes.append(f'Bloc {n} : {na} ligne(s) devenues {nb}.')
        for ligne in b['texte']:
            if len(ligne) > args.max_car:
                alertes.append(f'Bloc {n} : ligne de {len(ligne)} caractères.')
    for e in erreurs:
        print('ERREUR', e)
    for x in alertes:
        print('ALERTE', x)
    print(f'{len(erreurs)} erreur(s), {len(alertes)} alerte(s).')
    sys.exit(1 if erreurs else 0)


def main():
    p = argparse.ArgumentParser(description='Traduire et vérifier des sous-titres SRT ou WebVTT.')
    sub = p.add_subparsers(dest='commande', required=True)
    t = sub.add_parser('traduire')
    t.add_argument('entree')
    t.add_argument('sortie')
    t.add_argument('--modele', default=os.environ.get('OLLAMA_MODEL'))
    t.add_argument('--langue', default='français')
    t.add_argument('--lot', type=int, default=20)
    t.set_defaults(fonction=traduire)
    v = sub.add_parser('verifier')
    v.add_argument('original')
    v.add_argument('traduction')
    v.add_argument('--max-car', type=int, default=42)
    v.set_defaults(fonction=verifier)
    args = p.parse_args()
    args.fonction(args)


if __name__ == '__main__':
    main()

Three choices deserve an explanation. A temperature of 0 reduces variability from one run to the next, without guaranteeing identical output. Batches of 20 cues give the model a bit of context (who's speaking, about what) without producing overly long responses; you can adjust this with --lot. Finally, the script normalizes line endings to LF and multiple separators to a single blank line: the content doesn't change, but a byte-by-byte diff against the original will show these differences.

#Step 2: Translate the subtitles with Ollama

  1. 01
    Prepare the folder
    Copy the original into a working folder and keep its original name, for example film.en.srt. The translated file will have a different name, film.fr.srt, so the original is never modified.
  2. 02
    Choose the model
    Export the OLLAMA_MODEL variable with an exact name shown by ollama list. If you're torn between several models, translate the same excerpt of 30 to 50 lines with each one and compare them during review rather than going on a general impression.
  3. 03
    Run on an excerpt
    Start with a trimmed-down file (the first few cues copied into a new file). You'll quickly see whether the model follows the instructions, whether the tags survive, and whether the tone is right, without waiting for a full-length movie to finish.
  4. 04
    Run on the full file
    The script shows its progress on standard error. It writes the translated file only at the end: if it stops, no partial file is produced.
Terminal
export OLLAMA_MODEL="nom-du-modele"   # nom exact affiché par ollama list

# Fichier SRT
python3 soustitres.py traduire film.en.srt film.fr.srt --langue "français"

# Fichier WebVTT, lots plus petits
python3 soustitres.py traduire cours.en.vtt cours.fr.vtt --langue "français" --lot 10
→
Keep the original extension
The check in the next step picks the timestamp pattern based on the original's extension: .vtt for WebVTT, anything else for SRT. The script doesn't convert one format into the other; if you need a VTT from an SRT, do the conversion with a dedicated tool before or after, then check it separately.

#Step 3: strictly check the format

The verifier command rereads both files with the same parser and compares them block by block. It separates errors, which make the file unusable or out of sync, from warnings, which call for a quick look. The exit code is 1 if at least one error remains, so you can use it in a script to halt the next steps.

Terminal
python3 soustitres.py verifier film.en.srt film.fr.srt
python3 soustitres.py verifier cours.en.vtt cours.fr.vtt --max-car 42
Error: block count
A blank line was introduced into a translation, or a block went missing. Subsequent errors are often knock-on effects of the first one: fix the first flagged block, then run it again.
Error: timestamp modified
This shouldn't happen with this script, since the timing lines are copied over verbatim. If it does, the translated file was edited by hand or by another tool.
Error: tags differ
A tag was translated (<v Alice> became <v Alicia>), deleted, or moved. Restore it from the original.
Error: string -->
The model wrote an arrow in the text. Replace it with another symbol or rephrase.
Warning: line count
The translation spreads the cue over a different number of lines. This isn't invalid, but you should check it on screen.
Warning: line length
The default 42-character limit is an arbitrary starting point, not a rule from the WebVTT specification. Adjust it to your broadcaster's or platform's guidelines.

This check doesn't replace validation with a second parser. If ffmpeg is installed, ffprobe can read both files and count the cues it recognizes: two identical counts don't prove compliance, but a mismatch points to a problem the script missed. Finally, open the video with the translated file in your usual player and skim the beginning, middle, and end.

Terminal
ffprobe -v error -show_entries packet=pts_time -of csv=p=0 film.en.srt | wc -l
ffprobe -v error -show_entries packet=pts_time -of csv=p=0 film.fr.srt | wc -l

#Step 4: review the translation

A file that passes the check is structurally correct; that says nothing about whether it's well translated. Local models, whichever ones you use, can produce mistranslations, omissions, or additions, and a subtitle is read in a few seconds with no way to go back. So review the translation side by side with the original, ideally while watching the video.

Split sentences
A sentence spread across two cues is translated in two pieces. The model sees the whole batch, but it may rearrange the word order inconsistently between the two blocks.
Informal and formal address (tu and vous)
From English to French, the choice between tu and vous must stay consistent for each pair of characters. The model doesn't have that information from one batch to the next.
Names, technical terms, acronyms
Check that they are neither mistranslated nor spelled inconsistently from one line to the next. For domain-specific vocabulary, add a short glossary to the CONSIGNE constant.
Reading speed
French is often longer than English. If a line becomes too long for its display time, you have to condense it by hand; the script never touches timings.
Humor, wordplay, songs
Passages where a literal translation doesn't work call for an editorial choice, not a correction.
Typographie
Spaces before two-part punctuation marks, quotation marks, ellipses: make them consistent with your house style.
!
Don't present the output as a validated translation
Keep the original next to the translated version, note the model and date used, and clearly state that it's a machine translation until it has been reviewed. For public or professional use (accessibility subtitles, legal or medical content), have it reviewed by someone fluent in both languages.

#Troubleshooting

Connection refused
The Ollama server isn't running or isn't listening on localhost:11434. Check with curl http://localhost:11434/api/tags; if Ollama runs on another machine, set OLLAMA_URL.
model not found
The name passed in OLLAMA_MODEL doesn't match any local model. Copy it from ollama list, including the tag, or download it with ollama pull.
IDs still differ after 2 attempts
The model merged, skipped, or reordered cues. Reduce the batch size (--lot 5), try another model, or check that the batch in question doesn't contain an unusual cue (very long, or made up entirely of tags).
JSONDecodeError
The response isn't valid JSON: either your Ollama version doesn't support a schema in format, or the response was truncated. Update Ollama and reduce the batch size.
Timed out
The model overflows VRAM and runs partly on the CPU. Choose a smaller model or a lighter quantization, or increase the timeout in appeler_ollama.
UnicodeDecodeError on read
The original isn't in UTF-8. Convert a copy before running again.
Reasoning text in the translation
Depending on the Ollama version, some reasoning models may mix their reasoning into the response. If that happens, look up the API's think option in the documentation for your version, or use a model without a reasoning mode.

#Limitations of the method

This guide describes a method and a script, not a measured result. No tests of translation quality, speed, or error rate were run while writing it, and no such figures are given. Quality depends on the model, its quantization, the language pair, the register, and the quality of the source file; only a comparison on your own reviewed excerpts will tell you what works.

Deliberately simple parser
Splitting on blank lines and detecting the arrow handles common files. This is not a complete implementation of the W3C WebVTT parsing algorithm; unusual files (poorly separated blocks, extended headers) may be misclassified.
Limited context
The model only sees the current batch: it has no knowledge of what comes before or after, which can lead to inconsistencies in terminology or in formal vs. informal address.
No resyncing
The original display durations are preserved. If the translation is noticeably longer, condense the text rather than changing the timings.
No format conversion
An SRT stays an SRT and a VTT stays a VTT.
Partial entity check
The check compares tags, not entities such as &amp; or &nbsp;. For WebVTT files that contain them, verify these during review.

#Go further

If you're starting from a recording without subtitles, the full pipeline is: local transcription with Whisper, checking the transcript, then translation using the method in this guide. Keep a review at every step, because transcription errors carry over unchanged into the translation.

Whisper + Ollama locally
Producing the transcript and original subtitles without an online service: /guide/whisper-ollama-transcription-locale
Integrating Ollama via the REST API
Understand the /api/chat calls the script uses and adapt them to your tools: /guide/ollama-api-rest-integration-python
Choose your quantization
Find the trade-off between quality and memory for the translation model: /guide/choisir-quantification-q4-q5-q8

Primary sources: W3C WebVTT specification (https://www.w3.org/TR/webvtt1/), accessed 30/10/2026; QuelLLM guide “Whisper + Ollama en local” (https://quelllm.fr/guide/whisper-ollama-transcription-locale), accessed 30/10/2026. The SRT format has no equivalent official specification. The script was not run while this guide was written: test it on a sample clip and review its output before using it.

Did this guide help you?

Feedback, an error, or a clarification? Let us know—it improves the guide for everyone.