Skip to content

Studio Translate: translate SRT and VTT subtitle files, accept video files - #18992

Merged
danielhanchen merged 2 commits into
mainfrom
translate-subtitles-18666
Nov 23, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
translate-subtitles-18666

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Related to #18666

Summary

Translate now handles subtitle files. Opening or dropping an .srt or .vtt file used to load it as plain text, so the model saw cue numbers and timestamps mixed into the dialogue and could rewrite or drop them. Now:

  • When the text in the source box is a whole SRT or WebVTT file, only the cue texts are translated. Cue numbers, VTT identifiers, timings, cue settings, the WEBVTT header, NOTE / STYLE blocks, line endings (LF or CRLF) and a BOM are kept byte for byte.
  • Cues go to the model in numbered batches sized like today's passages (TRANSLATE_CHUNK_CHARS). A reply that does not number exactly the cues it was given, in order, is discarded and that batch is translated again one cue at a time, so a model that merges or splits lines can never shift text onto the wrong timing. Blank lines are dropped from translated cue text so a cue cannot end early.
  • The output pane shows the translated file as today (it fills in batch by batch), and a Download subtitles action appears for a finished subtitle translation. It saves the same format as <name>.<target>.srt / .vtt (subtitles.<target>.srt for pasted text).
  • Video files (.mp4, .m4v, .webm, .mkv, .mov) are now accepted by the Translate picker and drop zone and go through the same Voice settings transcription as audio files. The STT endpoint already decodes any container PyAV reads via container.demux(audio=0), so no backend change was needed. The existing 25 MB audio limit applies.

It reuses the existing run path: the stream handling in runTranslation moved into one complete() helper that both the passage loop and the subtitle path call, so the model, prompt, sampling, download, load, cut-off and filter handling are shared. Text that does not parse as a complete subtitle file takes the passage loop exactly as before.

Scoped out

  • Audio or video to timed subtitles: segment timestamps come back only from audio.cpp models, through the OpenAI-style /audio/transcriptions route with verbose_json, which also refuses when no language is detected. The Whisper (whisper.cpp), llama.cpp (mtmd) and Transformers engines behind the default dictation path return text only, so adding segments everywhere would be a backend refactor across several sidecars. Audio and video therefore still produce a plain transcript.
  • Image overlay: the OCR path returns text without boxes.

Tests

  • node --experimental-strip-types --test tests/translate-*.test.ts: 81 pass, including the new tests/translate-subtitles.test.ts (SRT / VTT / CRLF / BOM / unnumbered SRT round trips, clipped last block, plain text and prose with a stray timestamp staying plain text, batch sizing, numbered reply parsing incl. 1、 / 2., a merged batch falling back cue by cue, an aligned batch as one request, download name, routing of non-subtitle text). tests/translate-audio-file.test.ts updated for the video extensions.
  • Full npm test: 16988 tests, 0 failures.
  • npm run typecheck: clean. npm run i18n:check:strict: all overlays pass (new key added to every locale).
  • eslint on the touched files: same findings as on main, none new; the new files are clean.
  • Video decode: mp4, m4v, mov (H.264 + AAC), mkv and webm (VP8 / H.264 + Opus) clips built with PyAV all decode through the backend's _decode_audio_bounded to about 1 s of 16 kHz audio.

Not verified here: a live Studio run with a real model (no GPU in this session), so how often a given model keeps the numbering, and with it how often the cue-by-cue fallback runs, is unmeasured.

Before / after

A six cue SRT translated into French with Hy-MT2 1.8B (CPU). Before, the whole file goes to the model as plain text (captured mid-run, the output so far is just "1"); after, every cue number and timing is kept, the cue texts are French, and the result has a Download subtitles action.

before and after

Checked separately against the real Hy-MT2 1.8B on a 30 cue file into French, Spanish, German and Japanese: every numbered batch came back aligned (no cue-by-cue fallback needed) and all 30 timings were kept.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T03:20:58.906222Z b690959 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Nov 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 03ca7ddf6f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +144 to +147
} else if (items.length === 0) {
return null;
} else {
items[items.length - 1].push(line);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject unexpected numbered markers instead of appending them

When a reply contains a duplicate or out-of-order numbered marker, this branch treats it as continuation text, so the final item-count check can accept a misaligned batch instead of triggering cue-by-cue fallback. This also corrupts valid subtitles even when the model returns its input unchanged: if cue 1 contains Shopping list:\n2. apples and cue 2 contains Bananas, the numbered batch becomes 1. Shopping list:\n2. apples\n2. Bananas; the parser accepts two items and moves apples onto cue 2's timing. Reject unexpected markers so ambiguous batches take the existing fallback path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b690959: a repeated or out-of-order marker now rejects the batch (cue-by-cue fallback), and a batch whose own cue lines already read like markers goes one cue at a time, so your shopping list example keeps each line on its own timing (both covered by tests).

A repeated or skipped number in the reply now rejects the batch, and a batch
whose own cue lines read like markers ("2. apples") goes one cue at a time,
so text can never shift onto another cue's timing.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b6909593eb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
@danielhanchen
danielhanchen merged commit f01588b into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the translate-subtitles-18666 branch November 23, 2026 04:47
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 23, 2026
Related to unslothai#18666

## Summary

A video file dropped on the Translate page now becomes a timed subtitle
file when the Voice settings speech model reports segment timings. The
transcript is turned into an SRT, which then goes through the subtitle
path from unslothai#18992, so every cue keeps its timing and the Download
subtitles action appears (`trip.mp4` translated into French saves as
`trip.fr.srt`). Audio files and every other flow are unchanged.

### Backend (opt-in, default byte-identical)

- `POST /api/inference/audio/transcribe/raw` takes a new optional
`timestamps` query flag (default `false`).
- With the flag, the whisper.cpp engine asks whisper-server for
`response_format=verbose_json` (plus `no_language_probabilities=true`,
so it does not run a second language detection pass) and the result
gains `segments: [{start, end, text}]` in seconds. The `text` field is
built exactly as before.
- Without the flag the request to whisper-server and the JSON response
are unchanged.
- The flag is ignored by the other engines. audio.cpp models that always
time their text (Parakeet-TDT and the like) already return `segments` on
this route today.

### Frontend

- `transcribeAudioBlob` gets an optional `onSegments` callback. Only
when it is passed does the request carry `timestamps=true`, and the
callback only fires when the engine actually returned segments.
- Translate passes it for video files only. With segments,
`segmentsToSrt` builds an SRT (dictation dictionary applied per cue) and
the page loads it with the file name, so the existing subtitle
detection, batching and download take over. With no segments the plain
transcript loads, as today.
- `subtitleFileName` also strips video extensions.

## Scoped out, and why

- **Transformers engine** (custom HF repos, and the fallback when
whisper-server is missing): Studio does not use the `pipeline`. It calls
`model.generate` in a worker subprocess, and the worker sends back
`{"type": "text", "text", "consumed"}` per 30 s window
(`stt_transformers_worker.py` `transcribe_window`, decoded with
`skip_special_tokens=True`). Returning segments would mean changing that
worker protocol for the subprocess, in-process and MLX engines, which is
more than a small opt-in change. These models keep today's plain
transcript.
- **llama.cpp (mtmd) Qwen3-ASR**, the default Voice model: the runtime
returns text only, so there are no timings to read. A video falls back
to the plain transcript.
- **audio.cpp Qwen3-ASR**: it times text only with a separate 1.1 GB
forced aligner (`ON_REQUEST_TIMESTAMPS`). This change does not start
that download for a Translate drop.
- **Audio files** keep producing a plain transcript, as asked, so
nothing changes for people already using audio on Translate.
- The Audio page's capability table (`stt_capabilities`) still reports
whisper.cpp as having no timestamps, so the Transcribe page is
unchanged.

## Tests

- Backend (CPU, a fake whisper-server over HTTP, no model downloads):
- `tests/test_stt_ggml_sidecar.py`: the flag sends `verbose_json` +
`no_language_probabilities`, segments are normalised (blank and untimed
ones dropped), and the default request sends `json` and returns the same
four keys as before.
- `tests/test_stt_raw_timestamps.py`: the route passes `timestamps=True`
only to whisper.cpp; the default response is unchanged for gguf, mtmd,
transformers and audiocpp.
- With the functional hunks reverted, the 3 new timestamp tests fail and
the default-shape tests pass.
- `pytest tests/test_stt_raw_timestamps.py
tests/test_stt_ggml_sidecar.py tests/test_stt_context_settings.py
tests/test_stt_transcription_cancellation.py
tests/test_stt_broken_runtime_falls_back.py
tests/test_stt_ggml_request_path.py`: 128 passed.
- Frontend: `segmentsToSrt` output parses as SRT with the expected cues,
timings, rounding past one hour and empty-input handling; video naming;
the page asks for timings only for video files. Translate tests 88/88,
full `npm test` 17057 passed, 0 failed. `npm run typecheck` clean;
eslint on the touched files reports the same findings as `main`, nothing
new.

## Not verified here

- An end-to-end run against a real whisper-server binary and a Whisper
model (this host has no GPU and the check would need a model download).
The verbose_json response shape follows `examples/server/server.cpp` in
`unslothai/whisper.cpp` (segments carry `start`/`end` in seconds when
timestamps are on, which Studio never turns off).



### Before / after

A 23 second MP4 of speech dropped on Translate in a real Studio (CPU),
with Whisper tiny on whisper.cpp as the Voice model, translated into
French with Hy-MT2 1.8B. Before, the video becomes one plain paragraph;
after, it becomes 8 timed cues, translated with every timing kept, and
the result has a Download subtitles action:

![before and
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/19029/pr19029_before_after-1c92b69ceba5.png)

Also checked the backend change directly against a real whisper-server
with ggml base.en on WAV and MP4 input: the default response is
unchanged and `timestamps=true` adds segments with real timings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant