Repository navigation
feat(ai): shared AI core — metadata translation, Whisper ASR, per-profile language, on-view translation - #127
Conversation
… ASR Co-Authored-By: Claude Fable 5 <[email protected]>
…ackages internal/ai/llm: OpenAI-compatible chat client moved out of subtitles/ai, plus /v1/audio/transcriptions (verbose_json) for the ASR work; one shared retry/backoff loop for both. internal/ai/translate: the batched indexed-JSON translation protocol generalized to text segments. internal/ai/jobrunner: dispatch/heartbeat/reaper/cancel lifecycle extracted behind a minimal store interface, with a semaphore shareable across job services. Co-Authored-By: Claude Fable 5 <[email protected]>
LLMTranslator becomes a thin cue<->segment adapter over aitranslate; the service delegates dispatch/heartbeat/reaper/cancel to jobrunner; the local OpenAI client is gone in favor of internal/ai/llm. Behavior (prompts, wire protocol, job rows, recovery semantics) is unchanged. NewService now takes the dispatch semaphore so all AI job services can share one bound. Co-Authored-By: Claude Fable 5 <[email protected]>
…ocalization provenance columns ai.* connection keys (chat + optional separate ASR endpoint) load with a fallback to the legacy subtitle_ai.* rows — those are never renamed in SQL because encrypted values are GCM-bound to their setting key. New toggles: subtitle_ai.transcribe_enabled, metadata_ai.enabled. Migration adds metadata_translation_jobs, per-field provenance (provider|ai|manual) on the localization tables, and media_folders.auto_translate_metadata. Co-Authored-By: Claude Fable 5 <[email protected]>
…precedence Provider upserts keep manual values and never blank a field with an empty incoming value; new UpsertAITranslation/UpsertAIOverview methods write AI fields only over empty or ai-sourced values (force adds provider, never manual) — all enforced in single-statement SQL. Serving now merges only non-empty localized fields onto the base item, since localization rows are legitimately partial (AI rows carry no titles/artwork). Co-Authored-By: Claude Fable 5 <[email protected]>
…min API internal/metadata/translation: job service over the shared AI core that expands an item to its season/episode overviews, skips already-localized fields (zero model calls on repeat runs), batches paragraphs through the generic translator, and persists per batch with provenance-aware upserts. MetadataService gains an AutoTranslator seam invoked after each refresh for libraries with auto_translate_metadata. Admin endpoints under the metadata curation guard: enqueue, list (poll), cancel; plus a status probe. Co-Authored-By: Claude Fable 5 <[email protected]>
New WhisperTranscriber: one ffmpeg pass extracts the audio track to 10-min 16kHz mono WAV chunks (temp dir cleaned on every exit path), each chunk goes to the OpenAI-compatible /v1/audio/transcriptions endpoint (verbose_json, per-request timeout sized to 3x chunk duration), segment timestamps are offset and built into wrapped cues. Chunks process playhead-first and stream live to the requesting session. The transcript is stored as an ordinary downloaded subtitle (provider 'transcribed'); transcribe_translate chains the existing translator and stores the translated track as the job result. Enqueue accepts an optional kind; status reports transcribe_enabled. Co-Authored-By: Claude Fable 5 <[email protected]>
…uto-translate, generate-from-audio New AI Services admin page hosts the shared endpoint config (reads fall back to legacy subtitle_ai.* values, writes target ai.*) and the three feature toggles; the AI card moves out of Subtitles settings. The metadata editor gains a Translate-with-AI panel with job polling and force/re-translate. The library form gains the auto-translate toggle (threaded through the libraries API). The player translate modal gains a From-audio mode that lists audio tracks and submits transcribe / transcribe_translate jobs. Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…cription translation
user_profiles.preferred_metadata_language threads through the access scope
into catalog serving: presentation language now resolves explicit param ->
profile preference -> library metadata language (native API and jellycompat).
ItemDetail gains pending_translation_language when the viewer's language is
missing a localized overview. New metadata_ai.on_view setting (off|button|
auto) gates POST /items/{id}/translate-description: any profile with item
access may request its language, with in-flight dedup and a 15-minute
failure cooldown so page views never hammer a broken endpoint.
Co-Authored-By: Claude Fable 5 <[email protected]>
…language Profile playback settings gain a Metadata language picker (library default inherit). Detail pages: when the server reports pending_translation_language and metadata_ai.on_view is 'auto', the description translates on view with a pulse animation until the refetched detail comes back localized (45s timeout); in 'button' mode a small Translate chip triggers the same flow. Co-Authored-By: Claude Fable 5 <[email protected]>
The on-view translation mode had no UI control, so it could only ever be 'off' — viewers got neither the auto translation nor the fallback button. Adds the off/button/auto selector to the Features card, and the config loader now warns and falls back to 'off' on a bad row instead of refusing to start. Co-Authored-By: Claude Fable 5 <[email protected]>
…chat-only A blank Transcription base URL falls back to the chat endpoint; chat-only gateways reject the multipart upload with an opaque 400 that reads like a pipeline bug. 400/404/405 transcription failures now carry a hint to set a Whisper-compatible endpoint in AI Services. Co-Authored-By: Claude Fable 5 <[email protected]>
Arabic/Cyrillic/Greek text is 2+ bytes per character in UTF-8, so byte-based wrapping broke lines at roughly half the intended visual width. Co-Authored-By: Claude Fable 5 <[email protected]>
…ways Co-Authored-By: Claude Fable 5 <[email protected]>
…esets llm.IsChatOnlyGateway (OpenRouter et al — no timestamped transcription API) is enforced in three layers: the settings API rejects ai.asr_base_url values pointing at one, the router disables ASR with a warning when the blank-URL fallback would land on one, and llm.Transcribe refuses outright. The AI Services page gains one-click transcription presets (Groq turbo/accurate, OpenAI, self-hosted speaches) plus the mirrored client-side check, and the settings API now also validates metadata_ai.on_view. Co-Authored-By: Claude Fable 5 <[email protected]>
Three systematic timing-error sources addressed: cue offsets now use the segment muxer's exact per-chunk start times (segment_list CSV) instead of assuming index*chunk_seconds; the audio stream's start delay relative to the container timeline (common in TS remuxes) is probed via ffprobe and added to every cue; and the chunk length is now operator-tunable via subtitle_ai.asr_chunk_seconds (60-600s, default 600) since shorter chunks bound Whisper's within-chunk timestamp drift. Playhead-first ordering now pivots on real chunk starts, and a beyond-end playhead starts at the final chunk instead of restarting from zero. Co-Authored-By: Claude Fable 5 <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds shared AI runtime (LLM client, jobrunner, batched translator), provenance-aware metadata translation service and repository, Whisper ASR transcriber and audio-extract helpers, router/handler/config wiring, DB migrations, and frontend/admin/player UI integrations. ChangesAI translation and ASR
Sequence Diagram(s)sequenceDiagram
participant Client
participant Router
participant TranslationService
participant JobRunner
participant LLMClient
Client->>Router: POST /items/{id}/translate-description (enqueue)
Router->>TranslationService: RequestOnView / Enqueue job
TranslationService->>JobRunner: Dispatch(jobID, run)
JobRunner->>TranslationService: acquire slot / start heartbeat
TranslationService->>LLMClient: aitranslate.Translate/chat calls (batched)
LLMClient->>TranslationService: translated JSON responses
TranslationService->>CatalogLocalizationRepo: UpsertAI (per-batch persistence)
JobRunner->>TranslationService: Cancel/heartbeat events (optional)
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
docs/superpowers/specs/2026-06-10-ai-translation-and-asr-design.md (1)
67-67: ⚡ Quick winAdd language specifier to fenced code block.
The code fence should specify a language for proper syntax highlighting.
📝 Suggested fix
-``` +```text internal/ai/llm Client: OpenAI-compatible /v1/chat/completions (moved from🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/superpowers/specs/2026-06-10-ai-translation-and-asr-design.md` at line 67, The fenced code block at the shown snippet lacks a language specifier; update the opening triple-backtick to include a language (e.g., ```text) so syntax highlighting works for the block containing "internal/ai/llm Client: OpenAI-compatible /v1/chat/completions (moved from". Ensure the fence is changed consistently (opening only) and that no other formatting is altered.Source: Linters/SAST tools
internal/config/config.go (1)
272-276: ⚡ Quick winConsider validating ASRChunkSeconds range.
The comment on lines 272-274 documents a valid range of 60-600 seconds, but there's no validation enforcing this constraint in
db_loader.go. Out-of-range values could cause unexpected behavior (very short chunks → excessive requests; very long chunks → timestamp drift).🛡️ Validation logic to add in db_loader.go
After line 472 in
db_loader.go:cfg.SubtitleAI.ASRChunkSeconds = subtitleAIChunkSeconds +if cfg.SubtitleAI.ASRChunkSeconds < 60 || cfg.SubtitleAI.ASRChunkSeconds > 600 { + return nil, fmt.Errorf("invalid value for %q: must be between 60 and 600", "subtitle_ai.asr_chunk_seconds") +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/config/config.go` around lines 272 - 276, The ASRChunkSeconds config value (config.ASRChunkSeconds) isn't validated before use in db_loader.go, so add a validation step in the DB loader initialization path where the config is read/used (the function that sets up ASR/transcription chunking in db_loader.go): check that cfg.ASRChunkSeconds is within [60,600]; if it's out of range either clamp it to the nearest bound and log a warning via the existing logger or return an error to stop initialization (choose the project convention used elsewhere), and include the field name ASRChunkSeconds in the log/error so it's clear what was corrected/refused.internal/metadata/translation/service.go (1)
315-349: 💤 Low valueConsider synchronizing the
donecounter with the same mutex.The
persistErrvariable is protected bypersistMu, butdone(incremented at line 345, read at line 362) relies on callbacks being invoked sequentially. While this is likely true for batched translation, the asymmetric synchronization is fragile—if the callback invocation model ever changes, this becomes a data race. Protectingdoneunder the same mutex would make the code robust without measurable overhead.♻️ Suggested change
for _, seg := range batch { f, ok := byID[seg.ID] if !ok { continue } if err := s.persistField(storeCtx, job, f, seg.Text); err != nil { persistMu.Lock() if persistErr == nil { persistErr = err } persistMu.Unlock() cancelPersist() return } + persistMu.Lock() done++ + persistMu.Unlock() }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/metadata/translation/service.go` around lines 315 - 349, The done counter is incremented in the Translate callback without synchronization while persistErr is protected by persistMu; to avoid a potential data race, guard all accesses to done with the same persistMu used for persistErr: acquire persistMu before incrementing done (where done++ occurs in the Translate batch loop) and also acquire persistMu when reading done to pass into s.repo.UpdateProgress; keep the existing cancelPersist and error handling logic unchanged and ensure locks are held only for the minimal duration (or copy done into a local variable under the lock before calling s.repo.UpdateProgress) so you don't hold persistMu across external calls like s.persistField or s.repo.UpdateProgress.internal/api/handlers/profiles.go (1)
51-51: 💤 Low valueConsider validating ISO 639-1 format for preferred_metadata_language.
The
PreferredMetadataLanguagefield accepts any string without validation. While empty string is valid (meaning "inherit library metadata language"), invalid codes like"invalid"or"eng"(ISO 639-2, not 639-1) would be stored without error. This could lead to subtle bugs downstream if metadata resolution expects valid ISO 639-1 codes.✅ Optional validation helper
Add a validation helper at the package level:
// isValidLanguageCode validates ISO 639-1 two-letter codes or empty string. func isValidLanguageCode(code string) bool { if code == "" { return true } // Basic check: ISO 639-1 is always 2 lowercase letters if len(code) != 2 { return false } for _, r := range code { if r < 'a' || r > 'z' { return false } } return true }Then validate in the create handler after line 277:
if req.Name == "" { writeError(w, http.StatusBadRequest, "bad_request", "Profile name is required") return } + if !isValidLanguageCode(req.PreferredMetadataLanguage) { + writeError(w, http.StatusBadRequest, "bad_request", "Invalid preferred_metadata_language (must be ISO 639-1 or empty)") + return + }Apply similar validation in the update handler if
req.PreferredMetadataLanguageis non-nil.Also applies to: 362-362
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/profiles.go` at line 51, Add an ISO 639-1 validator and enforce it for PreferredMetadataLanguage: implement a package-level helper function (e.g., isValidLanguageCode(code string) bool) that returns true for empty string or two lowercase ASCII letters only, then call it in the profile create handler (after parsing the request in CreateProfile/CreateProfileHandler) to reject invalid codes with a 400 error and in the update handler (e.g., UpdateProfile/UpdateProfileHandler) when req.PreferredMetadataLanguage is non-nil; reference the PreferredMetadataLanguage struct field to locate where to read/validate the value and ensure both handlers return a clear validation error when the helper fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/hooks/useOnViewTranslation.ts`:
- Around line 44-49: The catch block in the API call inside useOnViewTranslation
silently clears translating via setTranslating(false) which provides no user
feedback for user-initiated translations; modify the error handling in the POST
to /items/${encodeURIComponent(contentId)}/translate-description so that when
mode === "button" it displays an error toast (use the app's toast utility or
existing pattern from items.ts:250) and then sets translating(false); ensure
auto mode remains silent while button mode surfaces the error to the user.
---
Nitpick comments:
In `@docs/superpowers/specs/2026-06-10-ai-translation-and-asr-design.md`:
- Line 67: The fenced code block at the shown snippet lacks a language
specifier; update the opening triple-backtick to include a language (e.g.,
```text) so syntax highlighting works for the block containing "internal/ai/llm
Client: OpenAI-compatible /v1/chat/completions (moved from". Ensure the fence is
changed consistently (opening only) and that no other formatting is altered.
In `@internal/api/handlers/profiles.go`:
- Line 51: Add an ISO 639-1 validator and enforce it for
PreferredMetadataLanguage: implement a package-level helper function (e.g.,
isValidLanguageCode(code string) bool) that returns true for empty string or two
lowercase ASCII letters only, then call it in the profile create handler (after
parsing the request in CreateProfile/CreateProfileHandler) to reject invalid
codes with a 400 error and in the update handler (e.g.,
UpdateProfile/UpdateProfileHandler) when req.PreferredMetadataLanguage is
non-nil; reference the PreferredMetadataLanguage struct field to locate where to
read/validate the value and ensure both handlers return a clear validation error
when the helper fails.
In `@internal/config/config.go`:
- Around line 272-276: The ASRChunkSeconds config value (config.ASRChunkSeconds)
isn't validated before use in db_loader.go, so add a validation step in the DB
loader initialization path where the config is read/used (the function that sets
up ASR/transcription chunking in db_loader.go): check that cfg.ASRChunkSeconds
is within [60,600]; if it's out of range either clamp it to the nearest bound
and log a warning via the existing logger or return an error to stop
initialization (choose the project convention used elsewhere), and include the
field name ASRChunkSeconds in the log/error so it's clear what was
corrected/refused.
In `@internal/metadata/translation/service.go`:
- Around line 315-349: The done counter is incremented in the Translate callback
without synchronization while persistErr is protected by persistMu; to avoid a
potential data race, guard all accesses to done with the same persistMu used for
persistErr: acquire persistMu before incrementing done (where done++ occurs in
the Translate batch loop) and also acquire persistMu when reading done to pass
into s.repo.UpdateProgress; keep the existing cancelPersist and error handling
logic unchanged and ensure locks are held only for the minimal duration (or copy
done into a local variable under the lock before calling s.repo.UpdateProgress)
so you don't hold persistMu across external calls like s.persistField or
s.repo.UpdateProgress.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 41f453db-9c27-49c5-8fdc-f63cf9c71b43
📒 Files selected for processing (71)
docs/superpowers/plans/2026-06-10-ai-translation-and-asr.mddocs/superpowers/specs/2026-06-10-ai-translation-and-asr-design.mddocs/superpowers/specs/2026-06-10-on-view-description-translation-design.mdinternal/access/resolver.gointernal/access/types.gointernal/ai/jobrunner/runner.gointernal/ai/jobrunner/runner_test.gointernal/ai/jobrunner/status.gointernal/ai/llm/client.gointernal/ai/llm/client_test.gointernal/ai/llm/transcribe.gointernal/ai/translate/languages.gointernal/ai/translate/translate.gointernal/ai/translate/translate_test.gointernal/api/handlers/admin.gointernal/api/handlers/items.gointernal/api/handlers/libraries.gointernal/api/handlers/metadata_ai.gointernal/api/handlers/profiles.gointernal/api/handlers/subtitle_ai.gointernal/api/router.gointernal/catalog/access_filter.gointernal/catalog/detail.gointernal/catalog/encrypted_settings_repo.gointernal/catalog/folder_repo.gointernal/catalog/localization_repo.gointernal/catalog/localize.gointernal/catalog/localize_test.gointernal/config/config.gointernal/config/db_loader.gointernal/jellycompat/access_filter.gointernal/metadata/service.gointernal/metadata/translation/job.gointernal/metadata/translation/pgrepo.gointernal/metadata/translation/prompt.gointernal/metadata/translation/service.gointernal/metadata/translation/service_test.gointernal/metadata/translation/store.gointernal/models/media.gointernal/playback/audio_extract.gointernal/subtitles/ai/client.gointernal/subtitles/ai/config.gointernal/subtitles/ai/job.gointernal/subtitles/ai/service.gointernal/subtitles/ai/service_test.gointernal/subtitles/ai/transcriber.gointernal/subtitles/ai/transcriber_test.gointernal/subtitles/ai/translator.gointernal/userstore/pgstore/profiles.gointernal/userstore/types.gomigrations/sql/20260610143224_ai_metadata_translation_and_asr.sqlmigrations/sql/20260610153638_profile_preferred_metadata_language.sqlweb/src/api/types.tsweb/src/components/EditMetadataDialog.tsxweb/src/components/MetadataTranslatePanel.tsxweb/src/components/admin/libraries/LibraryFormSections.tsxweb/src/components/admin/libraries/useLibraryForm.tsweb/src/hooks/queries/items.tsweb/src/hooks/useOnViewTranslation.tsweb/src/pages/ItemDetail/DetailHero.tsxweb/src/pages/ItemDetail/MovieContent.test.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/SeriesContent.test.tsxweb/src/pages/ItemDetail/SeriesContent.tsxweb/src/pages/admin-settings/AIServicesSettings.tsxweb/src/pages/admin-settings/AdminSettingsLayout.tsxweb/src/pages/admin-settings/SubtitlesSettings.tsxweb/src/pages/settings/PlaybackSettings.tsxweb/src/player/components/PlayerControls.tsxweb/src/player/components/SubtitleMenu.tsxweb/src/player/components/SubtitleTranslateModal.tsx
💤 Files with no reviewable changes (1)
- internal/subtitles/ai/client.go
| api(`/items/${encodeURIComponent(contentId)}/translate-description`, { | ||
| method: "POST", | ||
| body: JSON.stringify({ target_language: pendingLanguage }), | ||
| }).catch(() => { | ||
| setTranslating(false); | ||
| }); |
There was a problem hiding this comment.
Consider adding error feedback for button mode.
The catch block silently sets translating to false without user notification. In "button" mode, users explicitly request translation and expect feedback. Compare with other mutations in this codebase (e.g., items.ts:250) that show error toasts. While silent failure may be acceptable for "auto" mode background operations, button mode should inform users when translation fails.
💬 Suggested improvement
api(`/items/${encodeURIComponent(contentId)}/translate-description`, {
method: "POST",
body: JSON.stringify({ target_language: pendingLanguage }),
- }).catch(() => {
+ }).catch((err) => {
+ if (mode === "button") {
+ toast.error(err instanceof Error ? err.message : "Translation failed");
+ }
setTranslating(false);
});🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/hooks/useOnViewTranslation.ts` around lines 44 - 49, The catch block
in the API call inside useOnViewTranslation silently clears translating via
setTranslating(false) which provides no user feedback for user-initiated
translations; modify the error handling in the POST to
/items/${encodeURIComponent(contentId)}/translate-description so that when mode
=== "button" it displays an error toast (use the app's toast utility or existing
pattern from items.ts:250) and then sets translating(false); ensure auto mode
remains silent while button mode surfaces the error to the user.
Providers like DeepInfra expose their OpenAI-compatible API under a base that contains the version segment (api.deepinfra.com/v1/openai); always appending /v1/... mangled those. endpointURL now appends bare paths when the base already carries /v1. Co-Authored-By: Claude Fable 5 <[email protected]>
Preset order becomes self-hosted (recommended) -> Groq turbo -> Groq large-v3 -> OpenAI, and the settings hint plus the job-error hint lead with the self-hosted option. The self-hosted preset now fills the turbo CT2 model to match the recommended speaches setup. Co-Authored-By: Claude Fable 5 <[email protected]>
Without vad_filter, faster-whisper servers report wall-to-wall segment times: cues linger on screen through silence (verified up to 91s) and paragraph-length segments become single 400+ char cues. Request vad_filter=true (skipped for hosted providers that reject non-OpenAI fields and run VAD server-side) plus timestamp_granularities word+segment, and rebuild cues from word timings: split at speech pauses, sentence ends, text capacity, and a 7s max duration; cap word-less segments instead of trusting their reported end; stretch sub-second cues to a readable minimum. Co-Authored-By: Claude Fable 5 <[email protected]>
…file language, on-view translation (#127) * docs: design + plan for shared AI core, metadata translation, Whisper ASR Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(ai): shared LLM client, segment translator, and job runner packages internal/ai/llm: OpenAI-compatible chat client moved out of subtitles/ai, plus /v1/audio/transcriptions (verbose_json) for the ASR work; one shared retry/backoff loop for both. internal/ai/translate: the batched indexed-JSON translation protocol generalized to text segments. internal/ai/jobrunner: dispatch/heartbeat/reaper/cancel lifecycle extracted behind a minimal store interface, with a semaphore shareable across job services. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(subtitles): consume shared AI core LLMTranslator becomes a thin cue<->segment adapter over aitranslate; the service delegates dispatch/heartbeat/reaper/cancel to jobrunner; the local OpenAI client is gone in favor of internal/ai/llm. Behavior (prompts, wire protocol, job rows, recovery semantics) is unchanged. NewService now takes the dispatch semaphore so all AI job services can share one bound. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(config): shared ai.* settings, metadata translation job table, localization provenance columns ai.* connection keys (chat + optional separate ASR endpoint) load with a fallback to the legacy subtitle_ai.* rows — those are never renamed in SQL because encrypted values are GCM-bound to their setting key. New toggles: subtitle_ai.transcribe_enabled, metadata_ai.enabled. Migration adds metadata_translation_jobs, per-field provenance (provider|ai|manual) on the localization tables, and media_folders.auto_translate_metadata. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(catalog): localization field provenance with provider/ai/manual precedence Provider upserts keep manual values and never blank a field with an empty incoming value; new UpsertAITranslation/UpsertAIOverview methods write AI fields only over empty or ai-sourced values (force adds provider, never manual) — all enforced in single-statement SQL. Serving now merges only non-empty localized fields onto the base item, since localization rows are legitimately partial (AI rows carry no titles/artwork). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(metadata): AI translation service, refresh auto-fallback, and admin API internal/metadata/translation: job service over the shared AI core that expands an item to its season/episode overviews, skips already-localized fields (zero model calls on repeat runs), batches paragraphs through the generic translator, and persists per batch with provenance-aware upserts. MetadataService gains an AutoTranslator seam invoked after each refresh for libraries with auto_translate_metadata. Admin endpoints under the metadata curation guard: enqueue, list (poll), cancel; plus a status probe. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(subtitles): Whisper ASR transcribe and transcribe_translate jobs New WhisperTranscriber: one ffmpeg pass extracts the audio track to 10-min 16kHz mono WAV chunks (temp dir cleaned on every exit path), each chunk goes to the OpenAI-compatible /v1/audio/transcriptions endpoint (verbose_json, per-request timeout sized to 3x chunk duration), segment timestamps are offset and built into wrapped cues. Chunks process playhead-first and stream live to the requesting session. The transcript is stored as an ordinary downloaded subtitle (provider 'transcribed'); transcribe_translate chains the existing translator and stores the translated track as the job result. Enqueue accepts an optional kind; status reports transcribe_enabled. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): AI services settings, metadata translate action, library auto-translate, generate-from-audio New AI Services admin page hosts the shared endpoint config (reads fall back to legacy subtitle_ai.* values, writes target ai.*) and the three feature toggles; the AI card moves out of Subtitles settings. The metadata editor gains a Translate-with-AI panel with job polling and force/re-translate. The library form gains the auto-translate toggle (threaded through the libraries API). The player translate modal gains a From-audio mode that lists audio tracks and submits transcribe / transcribe_translate jobs. Co-Authored-By: Claude Fable 5 <[email protected]> * style: gofmt import grouping in router and translation tests Co-Authored-By: Claude Fable 5 <[email protected]> * feat(catalog): per-profile metadata language and viewer-triggered description translation user_profiles.preferred_metadata_language threads through the access scope into catalog serving: presentation language now resolves explicit param -> profile preference -> library metadata language (native API and jellycompat). ItemDetail gains pending_translation_language when the viewer's language is missing a localized overview. New metadata_ai.on_view setting (off|button| auto) gates POST /items/{id}/translate-description: any profile with item access may request its language, with in-flight dedup and a 15-minute failure cooldown so page views never hammer a broken endpoint. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): on-view description translation with per-profile metadata language Profile playback settings gain a Metadata language picker (library default inherit). Detail pages: when the server reports pending_translation_language and metadata_ai.on_view is 'auto', the description translates on view with a pulse animation until the refetched detail comes back localized (45s timeout); in 'button' mode a small Translate chip triggers the same flow. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): expose metadata_ai.on_view in AI Services settings The on-view translation mode had no UI control, so it could only ever be 'off' — viewers got neither the auto translation nor the fallback button. Adds the off/button/auto selector to the Features card, and the config loader now warns and falls back to 'off' on a bad row instead of refusing to start. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(ai): clear configuration hint when the transcription endpoint is chat-only A blank Transcription base URL falls back to the chat endpoint; chat-only gateways reject the multipart upload with an opaque 400 that reads like a pipeline bug. 400/404/405 transcription failures now carry a hint to set a Whisper-compatible endpoint in AI Services. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): wrap ASR cue text by rune count, not bytes Arabic/Cyrillic/Greek text is 2+ bytes per character in UTF-8, so byte-based wrapping broke lines at roughly half the intended visual width. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(web): steer transcription base URL hint away from chat-only gateways Co-Authored-By: Claude Fable 5 <[email protected]> * feat(ai): block chat-only gateways for transcription, add endpoint presets llm.IsChatOnlyGateway (OpenRouter et al — no timestamped transcription API) is enforced in three layers: the settings API rejects ai.asr_base_url values pointing at one, the router disables ASR with a warning when the blank-URL fallback would land on one, and llm.Transcribe refuses outright. The AI Services page gains one-click transcription presets (Groq turbo/accurate, OpenAI, self-hosted speaches) plus the mirrored client-side check, and the settings API now also validates metadata_ai.on_view. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): tighten ASR subtitle sync Three systematic timing-error sources addressed: cue offsets now use the segment muxer's exact per-chunk start times (segment_list CSV) instead of assuming index*chunk_seconds; the audio stream's start delay relative to the container timeline (common in TS remuxes) is probed via ffprobe and added to every cue; and the chunk length is now operator-tunable via subtitle_ai.asr_chunk_seconds (60-600s, default 600) since shorter chunks bound Whisper's within-chunk timestamp drift. Playhead-first ordering now pivots on real chunk starts, and a beyond-end playhead starts at the final chunk instead of restarting from zero. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(ai): tolerate base URLs that already include the /v1 segment Providers like DeepInfra expose their OpenAI-compatible API under a base that contains the version segment (api.deepinfra.com/v1/openai); always appending /v1/... mangled those. endpointURL now appends bare paths when the base already carries /v1. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): prefer self-hosted transcription in presets and hints Preset order becomes self-hosted (recommended) -> Groq turbo -> Groq large-v3 -> OpenAI, and the settings hint plus the job-error hint lead with the self-hosted option. The self-hosted preset now fills the turbo CT2 model to match the recommended speaches setup. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): request VAD and word timestamps for ASR cue accuracy Without vad_filter, faster-whisper servers report wall-to-wall segment times: cues linger on screen through silence (verified up to 91s) and paragraph-length segments become single 400+ char cues. Request vad_filter=true (skipped for hosted providers that reject non-OpenAI fields and run VAD server-side) plus timestamp_granularities word+segment, and rebuild cues from word timings: split at speech pauses, sentence ends, text capacity, and a 7s max duration; cap word-less segments instead of trusting their reported end; stretch sub-second cues to a readable minimum. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
…file language, on-view translation (#127) * docs: design + plan for shared AI core, metadata translation, Whisper ASR Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(ai): shared LLM client, segment translator, and job runner packages internal/ai/llm: OpenAI-compatible chat client moved out of subtitles/ai, plus /v1/audio/transcriptions (verbose_json) for the ASR work; one shared retry/backoff loop for both. internal/ai/translate: the batched indexed-JSON translation protocol generalized to text segments. internal/ai/jobrunner: dispatch/heartbeat/reaper/cancel lifecycle extracted behind a minimal store interface, with a semaphore shareable across job services. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(subtitles): consume shared AI core LLMTranslator becomes a thin cue<->segment adapter over aitranslate; the service delegates dispatch/heartbeat/reaper/cancel to jobrunner; the local OpenAI client is gone in favor of internal/ai/llm. Behavior (prompts, wire protocol, job rows, recovery semantics) is unchanged. NewService now takes the dispatch semaphore so all AI job services can share one bound. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(config): shared ai.* settings, metadata translation job table, localization provenance columns ai.* connection keys (chat + optional separate ASR endpoint) load with a fallback to the legacy subtitle_ai.* rows — those are never renamed in SQL because encrypted values are GCM-bound to their setting key. New toggles: subtitle_ai.transcribe_enabled, metadata_ai.enabled. Migration adds metadata_translation_jobs, per-field provenance (provider|ai|manual) on the localization tables, and media_folders.auto_translate_metadata. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(catalog): localization field provenance with provider/ai/manual precedence Provider upserts keep manual values and never blank a field with an empty incoming value; new UpsertAITranslation/UpsertAIOverview methods write AI fields only over empty or ai-sourced values (force adds provider, never manual) — all enforced in single-statement SQL. Serving now merges only non-empty localized fields onto the base item, since localization rows are legitimately partial (AI rows carry no titles/artwork). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(metadata): AI translation service, refresh auto-fallback, and admin API internal/metadata/translation: job service over the shared AI core that expands an item to its season/episode overviews, skips already-localized fields (zero model calls on repeat runs), batches paragraphs through the generic translator, and persists per batch with provenance-aware upserts. MetadataService gains an AutoTranslator seam invoked after each refresh for libraries with auto_translate_metadata. Admin endpoints under the metadata curation guard: enqueue, list (poll), cancel; plus a status probe. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(subtitles): Whisper ASR transcribe and transcribe_translate jobs New WhisperTranscriber: one ffmpeg pass extracts the audio track to 10-min 16kHz mono WAV chunks (temp dir cleaned on every exit path), each chunk goes to the OpenAI-compatible /v1/audio/transcriptions endpoint (verbose_json, per-request timeout sized to 3x chunk duration), segment timestamps are offset and built into wrapped cues. Chunks process playhead-first and stream live to the requesting session. The transcript is stored as an ordinary downloaded subtitle (provider 'transcribed'); transcribe_translate chains the existing translator and stores the translated track as the job result. Enqueue accepts an optional kind; status reports transcribe_enabled. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): AI services settings, metadata translate action, library auto-translate, generate-from-audio New AI Services admin page hosts the shared endpoint config (reads fall back to legacy subtitle_ai.* values, writes target ai.*) and the three feature toggles; the AI card moves out of Subtitles settings. The metadata editor gains a Translate-with-AI panel with job polling and force/re-translate. The library form gains the auto-translate toggle (threaded through the libraries API). The player translate modal gains a From-audio mode that lists audio tracks and submits transcribe / transcribe_translate jobs. Co-Authored-By: Claude Fable 5 <[email protected]> * style: gofmt import grouping in router and translation tests Co-Authored-By: Claude Fable 5 <[email protected]> * feat(catalog): per-profile metadata language and viewer-triggered description translation user_profiles.preferred_metadata_language threads through the access scope into catalog serving: presentation language now resolves explicit param -> profile preference -> library metadata language (native API and jellycompat). ItemDetail gains pending_translation_language when the viewer's language is missing a localized overview. New metadata_ai.on_view setting (off|button| auto) gates POST /items/{id}/translate-description: any profile with item access may request its language, with in-flight dedup and a 15-minute failure cooldown so page views never hammer a broken endpoint. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): on-view description translation with per-profile metadata language Profile playback settings gain a Metadata language picker (library default inherit). Detail pages: when the server reports pending_translation_language and metadata_ai.on_view is 'auto', the description translates on view with a pulse animation until the refetched detail comes back localized (45s timeout); in 'button' mode a small Translate chip triggers the same flow. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): expose metadata_ai.on_view in AI Services settings The on-view translation mode had no UI control, so it could only ever be 'off' — viewers got neither the auto translation nor the fallback button. Adds the off/button/auto selector to the Features card, and the config loader now warns and falls back to 'off' on a bad row instead of refusing to start. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(ai): clear configuration hint when the transcription endpoint is chat-only A blank Transcription base URL falls back to the chat endpoint; chat-only gateways reject the multipart upload with an opaque 400 that reads like a pipeline bug. 400/404/405 transcription failures now carry a hint to set a Whisper-compatible endpoint in AI Services. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): wrap ASR cue text by rune count, not bytes Arabic/Cyrillic/Greek text is 2+ bytes per character in UTF-8, so byte-based wrapping broke lines at roughly half the intended visual width. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(web): steer transcription base URL hint away from chat-only gateways Co-Authored-By: Claude Fable 5 <[email protected]> * feat(ai): block chat-only gateways for transcription, add endpoint presets llm.IsChatOnlyGateway (OpenRouter et al — no timestamped transcription API) is enforced in three layers: the settings API rejects ai.asr_base_url values pointing at one, the router disables ASR with a warning when the blank-URL fallback would land on one, and llm.Transcribe refuses outright. The AI Services page gains one-click transcription presets (Groq turbo/accurate, OpenAI, self-hosted speaches) plus the mirrored client-side check, and the settings API now also validates metadata_ai.on_view. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): tighten ASR subtitle sync Three systematic timing-error sources addressed: cue offsets now use the segment muxer's exact per-chunk start times (segment_list CSV) instead of assuming index*chunk_seconds; the audio stream's start delay relative to the container timeline (common in TS remuxes) is probed via ffprobe and added to every cue; and the chunk length is now operator-tunable via subtitle_ai.asr_chunk_seconds (60-600s, default 600) since shorter chunks bound Whisper's within-chunk timestamp drift. Playhead-first ordering now pivots on real chunk starts, and a beyond-end playhead starts at the final chunk instead of restarting from zero. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(ai): tolerate base URLs that already include the /v1 segment Providers like DeepInfra expose their OpenAI-compatible API under a base that contains the version segment (api.deepinfra.com/v1/openai); always appending /v1/... mangled those. endpointURL now appends bare paths when the base already carries /v1. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(web): prefer self-hosted transcription in presets and hints Preset order becomes self-hosted (recommended) -> Groq turbo -> Groq large-v3 -> OpenAI, and the settings hint plus the job-error hint lead with the self-hosted option. The self-hosted preset now fills the turbo CT2 model to match the recommended speaches setup. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(subtitles): request VAD and word timestamps for ASR cue accuracy Without vad_filter, faster-whisper servers report wall-to-wall segment times: cues linger on screen through silence (verified up to 91s) and paragraph-length segments become single 400+ char cues. Request vad_filter=true (skipped for hosted providers that reject non-OpenAI fields and run VAD server-side) plus timestamp_granularities word+segment, and rebuild cues from word timings: split at speech pauses, sentence ends, text capacity, and a 7s max duration; cap word-less segments instead of trusting their reported end; stretch sub-second cues to a readable minimum. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Problem
The AI subtitle translator's plumbing (OpenAI-compatible client, batch translation protocol, job lifecycle) was buried in
internal/subtitles/ai, so nothing else could use it — while libraries whose language the metadata providers can't serve had no way to get localized descriptions, and media without usable text subtitles had no AI path to a subtitle track.What changed
Shared AI core (
internal/ai/): the OpenAI-compatible chat client moved out ofsubtitles/aiand gained/v1/audio/transcriptionssupport; the batched indexed-JSON translation protocol became a generic segment translator; the job lifecycle (idempotency, heartbeat-while-queued, stale reaper, cancel registry) became a sharedjobrunner. One semaphore (ai.max_concurrent_jobs) bounds all AI jobs across services. Settings move toai.*keys with loader fallback to legacysubtitle_ai.*rows — never renamed in SQL because encrypted values are GCM-bound to their key.Metadata (description) translation (
internal/metadata/translation): translates overviews/taglines into the existing localization tables with per-field provenance (manual>provider>ai— a provider refresh overwrites AI text, never the reverse). Triggers: admin metadata-editor action, per-library auto-translate on refresh, and viewer-facing on-view translation (below). Skip-if-filled makes repeat runs cost zero LLM calls; serving now merges only non-empty localized fields over base (deliberate behavior change — AI rows carry no titles/artwork, and partial provider rows previously blanked posters/taglines).Whisper ASR (
transcribe/transcribe_translatejob kinds): one ffmpeg pass extracts the audio track to 16 kHz mono WAV chunks, each transcribed via verbose_json; the transcript is stored as an ordinary downloaded subtitle (and doubles as a cache for later translations); the chained kind feeds the transcript through the existing translator. Chunks process playhead-first with live cue streaming. Sync hardening: exact muxer-reported chunk starts (not index×length), ffprobe-probed audio/container start delta, and a tunable chunk length (subtitle_ai.asr_chunk_seconds) to bound Whisper drift. Chat-only gateways (OpenRouter — no timestamped transcription API) are rejected at the settings API, disabled with a warning at startup, and refused by the client.Per-profile metadata language + on-view translation:
user_profiles.preferred_metadata_languagefeeds presentation-language resolution (explicit param → profile preference → library language) in both the native API and jellycompat — all clients get profile-localized metadata server-side with zero client changes. Detail responses reportpending_translation_language;metadata_ai.on_view(off/button/auto) gatesPOST /items/{id}/translate-description(any profile with item access; in-flight dedup plus a 15-minute failure cooldown). The web detail page auto-translates with a pulse animation, or shows a Translate chip.Web: AI Services settings page (endpoint config, feature toggles, transcription presets for Groq/OpenAI/self-hosted), metadata-editor translate panel, library auto-translate toggle, player "From audio" mode, profile metadata-language picker, detail-page shimmer/button.
Design docs
docs/superpowers/specs/2026-06-10-ai-translation-and-asr-design.mddocs/superpowers/specs/2026-06-10-on-view-description-translation-design.mddocs/superpowers/plans/2026-06-10-ai-translation-and-asr.mdMigrations
Three Goose migrations:
metadata_translation_jobs+ provenance columns +media_folders.auto_translate_metadata;user_profiles.preferred_metadata_language. Runmake migrate-upon deploy.Risks / follow-ups
whisper-1, Groq, faster-whisper/speaches — notgpt-4o-transcribe, not OpenRouter).go test ./..., ESLint/prettier/tsc, and all 1011 web tests pass.golangci-lintwas not available locally. No UI screenshots attached — happy to add on request.AI-use disclosure
Implemented by Claude Code (Fable 5) pair-programmed with @Quick: design reviewed and approved before implementation, behavior verified against a live deployment during development.
Summary by CodeRabbit