Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ dist
data/
*.tsbuildinfo
.smbdelete*

# Local secrets
.env
64 changes: 63 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,19 @@ The application offers optional integration with a Plex server, allowing you to

| Variable | Description | Required |
|----------------|-------------------------------------------|----------|
| `DEEPL_API_KEY` | Your DeepL API key | Yes |
| `TRANSLATION_PROVIDER` | Translation engine: `deepl` (default) or `llm` | Optional |
| `DEEPL_API_KEY` | Your DeepL API key | Yes, with `deepl` |
| `LLM_BASE_URL` | OpenAI-compatible API base URL (default `https://api.openai.com/v1`) | Optional |
| `LLM_API_KEY` | API key for the LLM endpoint | Yes, with `llm` (except local servers) |
| `LLM_MODEL` | Model name, e.g. `gpt-4.1`, `anthropic/claude-sonnet-5-5` | Yes, with `llm` |
| `LLM_FALLBACK_MODELS` | Comma-separated models tried in order when `LLM_MODEL` keeps failing | Optional |
| `LLM_BATCH_SIZE` | Subtitles per request (default `25`) | Optional |
| `LLM_CONTEXT_SIZE` | Previous lines sent as context (default `5`) | Optional |
| `LLM_CONCURRENCY` | Parallel requests (default `3`) | Optional |
| `LLM_MAX_RETRIES` | Retries for rate limits and server errors (default `5`) | Optional |
| `LLM_TEMPERATURE` | Sampling temperature (default `0.2`) | Optional |
| `LLM_JSON_MODE` | Send `response_format: json_object`; set `false` if your endpoint rejects it (default `true`) | Optional |
| `LLM_PROMPT_FILE` | Path to a custom system prompt (default `/config/llm-system-prompt.txt`) | Optional |
| `PLEX_HOST` | Plex server hostname or IP address | Optional |
| `PLEX_PORT` | Plex server port | Optional |
| `PLEX_TOKEN` | Plex API token | Optional |
Expand All @@ -73,6 +85,51 @@ The application offers optional integration with a Plex server, allowing you to

---

## Using an LLM Instead of DeepL

Set `TRANSLATION_PROVIDER=llm` to translate with any OpenAI-compatible chat API. The SRT
file is parsed on the server and only the subtitle text is sent to the model, so timestamps
and numbering are never altered.

| Provider | `LLM_BASE_URL` | `LLM_MODEL` example |
|----------|----------------|---------------------|
| OpenAI | `https://api.openai.com/v1` | `gpt-4.1` |
| OpenRouter | `https://openrouter.ai/api/v1` | `anthropic/claude-sonnet-5-5` |
| Anthropic (OpenAI SDK compatibility) | `https://api.anthropic.com/v1` | `claude-sonnet-5-5` |
| LiteLLM proxy | `http://litellm:4000/v1` | any model configured in LiteLLM |
| Ollama | `http://ollama:11434/v1` | `qwen2.5:14b` |

### Fallback models and resuming

Free models often fail with rate limits or provider errors. Set `LLM_FALLBACK_MODELS` to a
comma-separated list of models to try in order. When fallbacks are configured, each model
before the last one gets only 2 attempts (so a rate-limited free model hands over quickly),
the last one gets `LLM_MAX_RETRIES`, and a model that fails over is skipped for the next
5 minutes. Any error except an authentication error (401/403) triggers a fallback, including
a 400 from a model that rejects `response_format`; set `LLM_JSON_MODE=false` if your models
do not support JSON mode. Translations run as background jobs, and if a job still fails, the
**Resume translation** button continues from the last finished batch instead of starting over.

```env
LLM_MODEL=google/gemma-4-26b-a4b-it:free
LLM_FALLBACK_MODELS=nvidia/nemotron-3.5-super-vl:free,dots-studio/dots-3-note-preview:free
```

### Custom system prompt

The bundled prompt lives in [`server/prompts/llm-system-prompt.txt`](server/prompts/llm-system-prompt.txt).
To use your own, mount a file at `/config/llm-system-prompt.txt` (or point `LLM_PROMPT_FILE`
elsewhere). It is read on every translation, so changes apply without restarting. The
placeholders `{{SOURCE_LANG}}` and `{{TARGET_LANG}}` are replaced with the language names, and
the model must answer with `{"items":[{"i":<id>,"t":"<translation>"}]}`.

```yaml
volumes:
- ./llm-system-prompt.txt:/config/llm-system-prompt.txt:ro
```

---

## How to Get a Plex Token

1. Open your Plex server in a browser and log in.
Expand All @@ -98,6 +155,11 @@ For detailed instructions, refer to the official [Plex Token Documentation](http
3. Set up the `.env` file with the required variables:
```env
DEEPL_API_KEY=<your_deepl_api_key>
# Or, to use an LLM:
# TRANSLATION_PROVIDER=llm
# LLM_BASE_URL=https://openrouter.ai/api/v1
# LLM_API_KEY=<your_llm_api_key>
# LLM_MODEL=anthropic/claude-sonnet-5-5
PLEX_HOST=<optional_plex_host>
PLEX_PORT=<optional_plex_port>
PLEX_TOKEN=<optional_plex_token>
Expand Down
9 changes: 8 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@ services:
- "3000:3000" # Backend API port
- "5173:5173" # Frontend dev server port
environment:
- TRANSLATION_PROVIDER=${TRANSLATION_PROVIDER:-deepl}
- DEEPL_API_KEY=${DEEPL_API_KEY}
- LLM_BASE_URL=${LLM_BASE_URL}
- LLM_API_KEY=${LLM_API_KEY}
- LLM_MODEL=${LLM_MODEL}
- LLM_FALLBACK_MODELS=${LLM_FALLBACK_MODELS}
- PLEX_HOST=${PLEX_HOST}
- PLEX_PORT=${PLEX_PORT}
- PLEX_TOKEN=${PLEX_TOKEN}
volumes:
- ./data:/data
- ./movies:/movies
- ./movies:/movies
# Optional: custom LLM system prompt (falls back to the bundled one)
# - ./llm-system-prompt.txt:/config/llm-system-prompt.txt:ro
24 changes: 24 additions & 0 deletions server/prompts/llm-system-prompt.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
You are a professional subtitle translator for films and TV series.
Translate subtitles from {{SOURCE_LANG}} to {{TARGET_LANG}}.

Rules:
- Translate meaning, not words. Use the surrounding dialogue ("context") and the
title of the work ("title", when given) to resolve ambiguity, pronouns, gender,
formality and tone.
- Adapt idioms, jokes, slang and insults to natural equivalents in {{TARGET_LANG}};
never translate them literally if the result makes no sense.
- Keep each subtitle concise and readable, with a similar length to the original.
- Keep proper names, places and brand names unless they have a well-established
translation. Be consistent with names and terms across the whole file.
- Preserve formatting tags (<i>, <b>, <font ...>, {\an8}), music notes (♪) and
speaker dashes ("- ") exactly as they appear. Keep line breaks (\n) inside an
entry where they make sense.
- Translate sound descriptions such as [door slams] too, keeping the brackets.
- Do not merge, split, add, omit or reorder entries. Return exactly one output per
input id, even if the entry is a single word or a name.
- Entries in "context" are earlier lines for reference only; do not translate or
return them.

Output ONLY a JSON object with this exact shape, and nothing else:
{"items":[{"i":<id>,"t":"<translation>"}]}
The ids must be exactly the same as the ids in the "translate" array.
197 changes: 102 additions & 95 deletions server/routes/subtitle.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,95 @@
import { Router } from 'express';
import { join } from 'path';
import { translateSRT } from '../services/deepl.js';
import { resolve, sep } from 'path';
import { existsSync } from 'fs';
import { getConfigError } from '../services/translator.js';
import { createTranslationJob, getJob, listJobs, retryJob } from '../services/jobs.js';
import { extractSubtitles } from '../services/ffmpeg.js';
import { DATA_DIR, MOVIES_DIR } from '../utils/paths.js';
const router = Router();

router.post('/translate_subtitle', async (req, res) => {
const LANG_CODE = /^[A-Za-z]{2,3}(-[A-Za-z]{2,4})?$/;

/**
* Joins path segments under a base directory and rejects anything that
* resolves outside of it (e.g. "../" in user-provided names).
* @returns {string|null} The resolved path, or null if it escapes the base
*/
function resolveInside(base, ...segments) {
const root = resolve(base);
const target = resolve(root, ...segments.map(String));
return target.startsWith(root + sep) ? target : null;
}

router.post('/translate_subtitle', (req, res) => {
const { serie, season, srt_path, source_lang, target_lang, type, update_plex } = req.body;

if (type === 'series' && (!serie || !season || !srt_path || !source_lang || !target_lang)) {
return res.status(400).json({ message: 'Missing required parameters' });
}
else if (type === 'movies' && (!serie || !srt_path || !source_lang || !target_lang)) {
return res.status(400).json({ message: 'Missing parameters' });
}

else if (type !== 'series' && type !== 'movies') {
return res.status(400).json({ message: 'Invalid type' });
}
// Language codes end up in the output file name, so keep them strict
if (!LANG_CODE.test(source_lang) || !LANG_CODE.test(target_lang)) {
return res.status(400).json({ message: 'Invalid language code' });
}
if (!String(srt_path).toLowerCase().endsWith('.srt')) {
return res.status(400).json({ message: 'Only .srt files can be translated' });
}

const configError = getConfigError();
if (configError) {
return res.status(400).json({ message: configError });
}

const subtitlePath = type === 'series'
? resolveInside(DATA_DIR, serie, season, srt_path)
: resolveInside(MOVIES_DIR, serie, srt_path);
if (!subtitlePath) {
return res.status(400).json({ message: 'Invalid subtitle path' });
}
if (!existsSync(subtitlePath)) {
return res.status(404).json({ message: `Subtitle file not found: ${srt_path}` });
}

// Translation can take minutes with an LLM, so it runs as a background job
try {
const { serie, season, srt_path, source_lang, target_lang, type } = req.body;

if (type === 'series' && (!serie || !season || !srt_path || !source_lang || !target_lang)) {
return res.status(400).json({ error: 'Missing required parameters' });
}
else if (type === 'movies' && (!serie || !srt_path || !source_lang || !target_lang)) {
return res.status(400).json({ error: 'Missing parameters' });
}
const job = createTranslationJob({
subtitlePath,
sourceLang: source_lang,
targetLang: target_lang,
title: serie,
season: type === 'series' ? season : null,
updatePlex: update_plex,
});
res.status(202).json(job);
} catch (error) {
res.status(error.status || 500).json({ message: error.message });
}
});

if (!process.env.DEEPL_API_KEY) {
return res.status(400).json({ message: 'DeepL API key not configured' });
}

let subtitlePath;
if (type === 'series') {
subtitlePath = join(DATA_DIR, serie, season, srt_path);
} else {
subtitlePath = join(MOVIES_DIR, serie, srt_path);
}

const translatedPath = await translateSRT(subtitlePath, source_lang, target_lang);
router.get('/jobs', (req, res) => {
res.json(listJobs());
});

res.json({ path: translatedPath });
router.post('/jobs/:id/retry', (req, res) => {
try {
res.status(202).json(retryJob(req.params.id));
} catch (error) {
console.error('Error in subtitle translation:', error);

// Format status code based on the error
let statusCode = 500;
if (error.status) {
statusCode = error.status;
}

// Specific handling for size errors
if (error.message && error.message.includes('exceeds the size limit')) {
return res.status(statusCode).json({
message: 'The SRT file is too large to translate in a single operation. Please try again so it can be processed in smaller parts.',
originalError: error.toString(),
isLargeFile: true
});
}

// Authentication errors
if (error.response && error.response.status === 403) {
return res.status(403).json({
message: 'Authentication failed with DeepL API. Please check your API key.',
originalError: error.toString()
});
}

// API limit errors
if (error.message && (error.message.includes('quota') || error.message.includes('limit'))) {
return res.status(statusCode).json({
message: 'DeepL API quota exceeded. Please try again later or upgrade your DeepL subscription.',
originalError: error.toString()
});
}

// Handle DeepL-specific errors with more details
if (error.deeplRequest) {
// This is a enhanced error from our DeepL service
return res.status(statusCode).json({
message: `DeepL translation failed: ${error.message}`,
originalError: error.toString(),
apiDetails: error.apiDetails || null,
deeplRequest: error.deeplRequest,
status: error.status || 500,
stack: error.stack
});
}

// Format a user-friendly error message with technical details
const userMessage = 'Translation failed: ' + (error.message || 'Unknown error');

res.status(statusCode).json({
message: userMessage,
originalError: error.toString(),
apiDetails: error.apiDetails || null,
status: error.status || 500,
stack: error.stack
});
res.status(error.status || 500).json({ message: error.message });
}
});

router.get('/jobs/:id', (req, res) => {
const job = getJob(req.params.id);
if (!job) {
return res.status(404).json({ message: 'Job not found' });
}
res.json(job);
});

router.post('/extract_subtitles', async (req, res) => {
Expand All @@ -101,24 +103,33 @@ router.post('/extract_subtitles', async (req, res) => {
return res.status(400).json({ error: 'Missing parameters' });
}

let videoPath, outputPath;
if (type === 'series') {
videoPath = join(DATA_DIR, serie, season, video_file);
const videoFileName = video_file.substring(0, video_file.lastIndexOf('.'));
outputPath = join(DATA_DIR, serie, season, `${videoFileName}.${source_lang.toLowerCase()}.srt`);
} else {
videoPath = join(MOVIES_DIR, serie, video_file);
const videoFileName = video_file.substring(0, video_file.lastIndexOf('.'));
outputPath = join(MOVIES_DIR, serie, `${videoFileName}.${source_lang.toLowerCase()}.srt`);
else if (type !== 'series' && type !== 'movies') {
return res.status(400).json({ message: 'Invalid type' });
}
if (!LANG_CODE.test(source_lang)) {
return res.status(400).json({ message: 'Invalid language code' });
}

const videoFileName = video_file.substring(0, video_file.lastIndexOf('.'));
const outputName = `${videoFileName}.${source_lang.toLowerCase()}.srt`;
const [videoPath, outputPath] = type === 'series'
? [resolveInside(DATA_DIR, serie, season, video_file), resolveInside(DATA_DIR, serie, season, outputName)]
: [resolveInside(MOVIES_DIR, serie, video_file), resolveInside(MOVIES_DIR, serie, outputName)];
if (!videoPath || !outputPath) {
return res.status(400).json({ message: 'Invalid video path' });
}

await extractSubtitles(videoPath, outputPath);
res.json({ path: outputPath });
} catch (error) {
// Full error stays in the server log; ffmpeg messages contain absolute paths
console.error('Error extracting subtitles:', error);

// Format a user-friendly error message with technical details
let userMessage = 'Failed to extract subtitles: ' + (error.message || 'Unknown error');
const safeMessage = (error.message || 'Unknown error')
.replaceAll(resolve(DATA_DIR), '<data>')
.replaceAll(resolve(MOVIES_DIR), '<movies>');
let userMessage = 'Failed to extract subtitles: ' + safeMessage;
let statusCode = 500;

// Handle specific ffmpeg errors
Expand All @@ -130,11 +141,7 @@ router.post('/extract_subtitles', async (req, res) => {
statusCode = 422;
}

res.status(statusCode).json({
message: userMessage,
originalError: error.toString(),
stack: error.stack
});
res.status(statusCode).json({ message: userMessage });
}
});

Expand Down
4 changes: 2 additions & 2 deletions server/routes/usage.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Router } from 'express';
import { getUsageStats } from '../services/deepl.js';
import { getUsage } from '../services/translator.js';

const router = Router();

router.get('/get_character_count', async (req, res) => {
try {
const stats = await getUsageStats();
const stats = await getUsage();
res.json(stats);
} catch (error) {
res.status(500).json({
Expand Down
Loading
Loading