Files
silo-server/internal/subtitles/ai/translator.go
a17529fd6f feat(config): live admin settings + truthful restart-required banner (#128)
* feat(nodeconfig): harden config watcher for integrated-mode use

- RequestReload(): non-blocking, coalescing reload nudge that runs on the
  poll goroutine, so concurrent requests can never swap a stale snapshot
  over a newer one (unlike ForceReload from request handlers)
- Skip OnChange callbacks when the reloaded config is deep-equal to the
  previous one, so the 60s poll doesn't fire rebuild/log callbacks on
  no-op reloads
- Add RedisURL to BootstrapOverrides; previously a reload clobbered an
  env-provided Redis URL in the live config
- Split reload into fetchSettings/applySettings and add unit tests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(config): hot-reload config watcher in integrated mode

Start nodeconfig.Watcher in integrated/api mode (previously only proxy/
transcode worker modes hot-reloaded). Expose the live config to the API
and jellycompat routers via func-typed LiveConfig/OnConfigChange fields
with nil fallbacks to the startup snapshot, and wire the admin settings
update hook to RequestReload so same-process changes apply immediately
even without Redis.

No consumer reads the live config yet — conversions land separately.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(admin): truthful restart-required banner for settings saves

The settings UI showed 'restart required' after every save regardless of
the key. The backend now classifies each key via a central registry
(internal/config/restart_keys.go) and PUT /admin/settings/{key} reports
restart_required per key; useSettingsForm only raises the banner when a
saved key actually needs a restart (and keeps it raised until restart).

The registry is conservative: every currently startup-frozen key is
marked restart-required; subsequent hot-reload conversions shrink it.
Settings read live from the settings repo (branding, overlays, markers,
download.*, ...) default to no-restart. DownloadSettings/OverlaySettings
drop their hardcoded restartRequired={false} special-casing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(logging): hot-reload server.log_level and server.log_quiet

Share one slog.LevelVar across the handler chain and make
logfilter.Handler's quiet-prefix list an atomic pointer shared with
WithAttrs/WithGroup clones (New previously returned the inner handler
unwrapped when the quiet list was empty, leaving nothing to update).
The integrated-mode config watcher now applies both settings live;
their keys leave the restart-required registry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(auth): hot-reload access/refresh token expiries

JWTService stores expiries as atomics with a SetExpiries hook; all three
instances (main API, ABS compat, jellycompat) re-apply them on config
reload. Applies to newly issued tokens; outstanding tokens keep their
original expiry. The JWT secret stays fixed for the process lifetime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(playback): read transcode config live at session start

The playback and stream handlers pull ffmpeg path / hwaccel / transcode
dir from the live config when starting a transcode or extracting
subtitles, instead of values frozen at router construction. Each session
snapshots the config once so its output dir and binary stay consistent.

Also fixes a real bug: playback.hw_device was parsed into the config but
never wired into the integrated-mode handler, so local transcodes always
ran with an empty HWDevice while transcode nodes honored it.

playback.transcode_dir leaves the restart-required registry (the handler
is its only consumer); ffmpeg_path/hw_accel stay restart-required until
scanner/chapterthumbs/audiobook consumers convert.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(jellycompat): read compat identity settings live per request

System/Auth handlers take a config provider instead of the startup
snapshot, so jellyfin_compat.public_url, .server_name, and
.emulated_server_version apply without restart. server_id stays
restart-required (generate-once, baked into the resource mapper), as do
the session-store TTLs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(scanner,metadata,mdblist): hot-reload worker pools and API key

scanner.workers, matcher.workers/batch_size, metadata.cache_images, and
mdblist.api_key convert to atomic fields with setters wired to the
config watcher. Worker counts apply on the next scan/match cycle (the
loops read them per cycle); the MDBList key applies to the next request.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(ai): hot-reload AI connection, models, toggles, and quotas

The shared llm.Client holds its config behind an atomic pointer
(UpdateConfig; each request snapshots once), and the subtitle/metadata
AI services gain UpdateConfig plus setters on the translator (batching)
and Whisper transcriber (ffmpeg path, chunk seconds). The router derives
their configs from shared helpers used both at construction and in
OnConfigChange callbacks, re-evaluating the chat-only-gateway transcribe
guard on each reload and warning only when it newly fires.

Everything on the AI Services page now applies without restart except
ai.max_concurrent_jobs (fixed-capacity dispatch semaphore).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(playback): wire transcode_enabled; remove dead playback/scanner knobs

playback.transcode_enabled was parsed into the config but the resolver
always received a hardcoded true — the admin toggle did nothing. It now
reads the live config per playback start, so disabling transcodes
applies without restart.

Remove settings that were wired to nothing so 'save + restart' stops
pretending: playback.allow_hevc_encoding (resolver field never
assigned), playback.transcode_ahead_segments and
playback.segment_duration (parsed, never consumed — segment duration is
per-session from the client), scanner.file_removal_grace (DeleteMissing
is never called). UI fields removed and the config struct fields pruned
so they don't resurrect; YAML import still tolerates the legacy keys.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 19:25:07 -04:00

138 lines
4.5 KiB
Go

package ai
import (
"context"
"fmt"
"strconv"
"strings"
"sync/atomic"
"github.com/Silo-Server/silo-server/internal/ai/llm"
aitranslate "github.com/Silo-Server/silo-server/internal/ai/translate"
)
// LLMTranslator translates subtitle cues with an OpenAI-compatible chat model
// via the shared aitranslate batch protocol. Only the text is sent to the
// model — timestamps never leave the server — so timing alignment is
// structurally guaranteed. A few preceding source cues are included as
// untranslated context so the model can keep scene continuity across batch
// boundaries.
type LLMTranslator struct {
client *llm.Client
// batching is atomic so admin settings changes apply to jobs started
// afterwards without rebuilding the translator.
batchSize atomic.Int32
contextNeighbors atomic.Int32
}
// NewLLMTranslator builds a translator. batchSize and contextNeighbors fall
// back to sane defaults when non-positive.
func NewLLMTranslator(client *llm.Client, batchSize, contextNeighbors int) *LLMTranslator {
t := &LLMTranslator{client: client}
t.SetBatching(batchSize, contextNeighbors)
return t
}
// SetBatching updates the translation batch size and context-neighbor count.
// Safe for concurrent use; jobs started afterwards pick the new values up.
// Non-positive batch sizes and negative neighbor counts fall back to the
// same defaults as construction.
func (t *LLMTranslator) SetBatching(batchSize, contextNeighbors int) {
if batchSize <= 0 {
batchSize = 40
}
if contextNeighbors < 0 {
contextNeighbors = 0
}
t.batchSize.Store(int32(batchSize))
t.contextNeighbors.Store(int32(contextNeighbors))
}
// Translate implements Translator.
func (t *LLMTranslator) Translate(ctx context.Context, req TranslateRequest, onBatch func(batch []SubtitleCue, done, total int)) ([]SubtitleCue, error) {
if t.client == nil {
return nil, fmt.Errorf("translator client is nil")
}
if strings.TrimSpace(req.TargetLanguage) == "" {
return nil, fmt.Errorf("target language is required")
}
total := len(req.Cues)
if total == 0 {
return nil, fmt.Errorf("no cues to translate")
}
// Preserve timing by copying input cues and only replacing Lines.
out := make([]SubtitleCue, total)
copy(out, req.Cues)
segments := make([]aitranslate.Segment, total)
for i, c := range req.Cues {
segments[i] = aitranslate.Segment{ID: strconv.Itoa(i + 1), Text: strings.Join(c.Lines, "\n")}
}
srcName := aitranslate.LanguageDisplayName(req.SourceLanguage)
tgtName := aitranslate.LanguageDisplayName(req.TargetLanguage)
chat := func(ctx context.Context, system, user string) (string, error) {
messages := []llm.Message{
{Role: "system", Content: system},
{Role: "user", Content: user},
}
return t.client.Chat(ctx, messages, true)
}
translated, err := aitranslate.Translate(ctx, chat, aitranslate.Request{
Segments: segments,
SystemPrompt: translationSystemPrompt(srcName, tgtName),
TargetName: tgtName,
EntryNoun: "cues",
BatchSize: int(t.batchSize.Load()),
ContextNeighbors: int(t.contextNeighbors.Load()),
}, func(batch []aitranslate.Segment, done, totalSegs int) {
// Batches are sequential ranges, so this batch covers [done-len, done).
start := done - len(batch)
for i, seg := range batch {
out[start+i].Lines = splitCueLines(seg.Text)
}
if onBatch != nil {
onBatch(out[start:done], done, totalSegs)
}
})
if err != nil {
return nil, err
}
// Map the full result too: covers callers without an onBatch callback.
for i, seg := range translated {
out[i].Lines = splitCueLines(seg.Text)
}
return out, nil
}
func translationSystemPrompt(srcName, tgtName string) string {
src := srcName
if src == "" {
src = "the source language"
}
return fmt.Sprintf(
"You are a professional subtitle translator. Translate subtitle cues from %s into %s. "+
"Produce natural, idiomatic %s that preserves meaning, tone, register, and proper nouns. "+
"You receive a JSON object whose keys are cue numbers and whose values are the source text. "+
"Respond with ONLY a JSON object using the exact same keys, where each value is the translation of that cue. "+
"Preserve line breaks within a cue as \\n. Do not add, remove, merge, split, reorder, or renumber cues, "+
"and do not output anything except the JSON object.",
src, tgtName, tgtName,
)
}
func splitCueLines(v string) []string {
lines := strings.Split(v, "\n")
for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
lines = lines[:len(lines)-1]
}
if len(lines) == 0 {
return []string{""}
}
return lines
}