基于 ChatGPT 或任何与 OpenAI 兼容的 LLM 聊天完成 API 的高效翻译工具
基于 ChatGPT 或任何与 OpenAI 兼容的 LLM 聊天完成 API 的高效翻译工具
Large language models (LLMs), such as ChatGPT, have demonstrated their capabilities as a robust translator, capable of handling common natural languages with contextual understanding, as well as unconventional forms of writing like word scrambling. However, it may not always produce a deterministic output or adhere to line-to-line correlation, potentially disrupting the timing of subtitles, even when instructed to follow precise instructions and with the model temperature parameter set to 0.
This utility uses the OpenAI ChatGPT API to translate text, with a specific focus on line-based translation, especially for SRT subtitles. The translator optimizes token usage by removing SRT overhead and grouping text into batches, resulting in arbitrary length translations without excessive token consumption while ensuring a one-to-one match between line input and output.
-c, --context (CLI only)--use-moderator (CLI only)Reference:
>= 20 required. This README assumes bash shell environmentgit clone https://github.com/Cerlancism/chatgpt-subtitle-translatorcd chatgpt-subtitle-translatornpm installchmod +x cli/translator.mjs.example.env to .envcp .env.example .env.env filecli/translator.mjs --helpUsage: translator [options]
Translation tool based on ChatGPT API
Options:
--from
Source language (default: "")
--to
Target language (default: "English")
-s, --system-instruction
Override the prompt system instruction template Translate ${from} to ${to} with this text, ignoring --from and --to options
-i, --input
Input source text with the content of this file, in .srt format or plain text
-o, --output
Output file name, defaults to be based on input file name
-r, --structured
Structured response format mode. (default: array, choices: array, object, timestamp, agent, none)
array Structures the input and output into an array format.object Structures the input and output as a keyed object.timestamp Provides the model with entry timings alongside each entry's text (a batch start offset plus per-entry offset/length in milliseconds), allowing it to merge adjacent entries into one. A batch is only retried when the output time span boundaries don't match the input - unlike other modes which retry on any line count mismatch - significantly reducing token wastage from retries. Uses more tokens per batch due to timestamps in input and output. Output entry count may differ from input, so progress file resumption is not supported.agent Alias for the agent subcommand with default options. Use the dedicated subcommand for full configuration. See Agent Mode.none Legacy compatibility mode, disables structured output.-c, --context
Include translation history up to a token budget to work well with prompt caching. Default: 2000. Set to 0 to include history without a token limit check.
Recommended value: set `` to ~50% of the model's max context length to leave room for the current batch and system prompts. For example, for a 128K context model: --context 64000. When --batch-sizes is omitted, the batch size is derived from this budget as well.
-b, --batch-sizes
Batch sizes of increasing order for translation prompt slices in JSON Array
The number of lines to include in each translation prompt, provided that they are estimated to be within the token limit.
In case of mismatched output line quantities, this number will be decreased step by step according to the values in the array, ultimately reaching one.
Larger batch sizes generally lead to more efficient token utilization and potentially better contextual translation.
However, mismatched output line quantities or exceeding the token limit will cause token wastage, requiring resubmission of the batch with a smaller batch size.
When omitted, batch size is determined automatically per batch from the --context token budget: each batch is sized so that several batches of history fit in the portion of the context window freed by a trim, keeping the prompt cache warm in between. The history cost per input token is measured from the translated batches. The size is spread evenly across the remaining lines. On failure, the size is reduced and retried; once it reaches the minimum, translation falls back to single-entry mode. After a reduction, the size eases back up stepwise following consecutive successful batches.
-g, --guard-repetition
Minimum number of pattern repeats before aborting a streaming response (default: 10). When the model falls into a repetition loop during streaming, the response is aborted and retried with a smaller batch. Set to 0 to disable repetition detection.
--initial-prompts
Initial prompts for the translation in JSON (default: "[]")
--use-moderator
Use the OpenAI Moderation tool
--moderation-model
(default: "omni-moderation-latest") https://developers.openai.com/api/docs/models
--no-prefix-number
Don't prefix lines with numerical indices. Ignored in -r, --structured array|object|timestamp - prefix numbers are always disabled there.
--no-line-matching
Don't enforce one-to-one line quantity input output matching. Ignored in -r, --structured timestamp - line matching is always disabled there since entries may be merged.
-p, --plain-text
Input source text with this plain text argument. Not supported in -r, --structured timestamp mode, or when using the agent subcommand with -r timestamp.
--no-stream
Disable stream progress output to terminal (streaming is on by default)
--log-level
Log level (default: debug, choices: trace, debug, info, warn, error, silent)
--silent
Same as --log-level silent
--quiet
Same as --log-level silent
Additional Options for GPT: https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create
-m, --model
(default: "gpt-4o-mini") https://developers.openai.com/api/docs/models--reasoning_effort
Constrains effort on reasoning for reasoning models. Accepted values depend on the model (e.g. "low", "medium", "high"), follows the model's default when not set. "none" disables reasoning/thinking entirely (supported by OpenAI o-series/GPT-5+ and open models via Ollama such as Qwen3).-t, --temperature
Sampling temperature to use, should set a low value such as 0 to be more deterministic for translation (default: 0)--top_p
Nucleus sampling parameter, top_p probability mass--presence_penalty
Penalty for new tokens based on their presence in the text so far--frequency_penalty
Penalty for new tokens based on their frequency in the text so far--logit_bias
Modify the likelihood of specified tokens appearing in the completionSubcommand for multi-pass agentic translation. Accepts all standard translation options.
cli/translator.mjs agent --helpAgent mode runs multiple passes before translating:
Overview - Samples the file to produce a content overview (file identity, duration, genre/tone, character names) and detects the source language.
Planning - Scans the file in token-bounded windows. Each window produces a batch summary (characters, locations, events, tone). Summaries are consolidated and used to generate a refined translation instruction.
Translation - Translates using the enriched instruction. After the first batch, a sample of the output is checked to confirm the target language before proceeding.
Structured mode defaults to array, pass --structured timestamp to use timestamp mode instead.
# Default (array delegate)
cli/translator.mjs agent --input subtitles.srt --from Japanese --to English
# Timestamp delegate
cli/translator.mjs agent --input subtitles.srt --structured timestamp --from Japanese --to English--no-refine--no-fitting--context-summary cli/translator.mjs --plain-text "你好"Standard Output
Hello.cli/translator.mjs --to "Emojis" --plain-text "Chuck Norris can walk with the animals, talk with the animals; grunt and squeak and squawk with the animals... and the animals, without fail, always say 'yessir Mr. Norris'."Standard Output
♂️️️❗️==.cli/translator.mjs --system-instruction "Scramble characters of words while only keeping the start and end letter" --no-prefix-number --no-line-matching --plain-text "Chuck Norris can walk with the animals, talk with the animals;"Standard Output
Cuhck Nroris can wakl wtih the aiamnls, talk wtih the aiamnls;cli/translator.mjs --system-instruction "Unscramble characters back to English" --no-prefix-number --no-line-matching --plain-text "Cuhck Nroris can wakl wtih the aiamnls, talk wtih the aiamnls;"Standard Output
Chuck Norris can walk with the animals, talk with the animals;cli/translator.mjs --input test/data/test_cn.txtInput file: test/data/test_cn.txt
你好。
拜拜!Standard Output
Hello.
Goodbye!cli/translator.mjs --input test/data/test_ja_small.srtInput file: test/data/test_ja_small.srt
1暂无开放 Issues,或尚未同步最近议题。