VoiceStudio is the open-source, fully-local ElevenLabs alternative — voice cloning, voice design, video dubbing, dictation, transcription & audiobook creation in 646 languages.
Python aiaudiobookcudadubbingelevenlabs-alternativehuggingfacelocal-firstmlxomnivoice-studiospeech-to-texttext-to-speechtranscriptiontranslatettsvoice-aivoice-cloningvoice-generationvoicestudioworkflow
fix(generate): name the real cause of generation failures
velixio53e749966cbc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abbe0d4ad..1f3b8cb78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,11 @@ metadata and the backend fallback mirror it.- Preview iOS and Android companion apps: drive your own VoiceStudio from your phone (speak, voices and cloning, dubbing, dictation) after pairing by QR code; build from source for now ([guide](docs/mobile.md)) (#2965)+### Fixed++- Generation errors now name the real cause (missing engine package, missing speech-to-text model, GPU or system memory, proxy timeout, unknown route) with a translated next step, and bug reports record the backend error class and failure topic (#PRNUM)+- Picking a long reference clip's best passage no longer counts against the 300 s generate limit (#PRNUM)+### Docs- Contributor guides and the pull request template explain how to sign the CLA before opening a first pull request (#2676)diff --git a/backend/api/routers/generation.py b/backend/api/routers/generation.pyindex c7d645c16..b2674d586 100644--- a/backend/api/routers/generation.py+++ b/backend/api/routers/generation.py@@ -2013,6 +2013,32 @@ async def generate_speech(if ref_text and persist_ref_text_profile_id:_persist_profile_ref_text(persist_ref_text_profile_id, ref_text)+ # #2764: choosing the best 15 s window of a long reference runs the+ # installed recognizer over several windows — minutes on a CPU. Inside the+ # engine call that time was billed to the generate budget and the job was+ # abandoned ("exceeded 300s") before synthesis began. Do it here, on its own+ # floor-scaled budget; the engine then recalls the remembered choice. Best+ # effort: a timeout leaves the engine to rank inline exactly as before.+ if ref_audio_path and ref_picks_own_passage and backend_cls is OmniVoiceBackend:+ from services.tts_backend import prepare_reference_passage++ try:+ from omnivoice.utils.audio import CLONE_REF_MAX_WINDOWS++ await _run_with_reference_lease(+ ref_lease,+ lambda release: run_on_gpu_pool_guarded(+ functools.partial(prepare_reference_passage, ref_audio_path),+ what="Reference passage selection",+ timeout=CLONE_REF_MAX_WINDOWS * _generate_timeout_s(+ "", execution_device=_routing["effective_device"]+ ),+ on_abandon=release,+ )+ )+ except TimeoutError as e:+ logger.warning("reference passage selection hung (%s); engine will rank inline", e)+# #526: materialize a concrete seed when none was supplied (and no profile# pinned one) so the take is reproducible and we can hand it back via the# X-Seed header for the "keep this seed" control. An explicit request seed@@ -2554,6 +2580,14 @@ async def generate_speech(_topic = classify(str(e))_owned = public_hint_for_topic(_topic) if _topic else ""+ if _topic == "REFERENCE_STT_MISSING" and _owned:+ # Structured so the client can show its localized copy (#2929/#2678)+ # instead of the English sentence, and so the topic reaches the+ # bug report.+ raise HTTPException(+ status_code=400,+ detail={"docs_topic": _topic, "message": _owned, "hint": _owned},+ ) from eraise HTTPException(status_code=400, detail=_owned or str(e)) from eexcept Exception as e:tb = traceback.format_exc()diff --git a/backend/core/failure.py b/backend/core/failure.pyindex 90abd4156..074d7b7aa 100644--- a/backend/core/failure.py+++ b/backend/core/failure.py@@ -189,6 +189,12 @@ _HINTS: dict[str, str] = {# page showed verbatim and which read as a disk/permission problem."NO_AUDIO_TRACK": "Check that the file plays with sound in a media player. If its audio is in a separate file, choose that file instead, or merge the audio into the video first.","INVALID_MEDIA_FILE": "Check the source in a media player. If it cannot play, wait for the download or copy to finish, free disk space if needed, then download a fresh copy and upload it again.",+ # #2929/#2678: the voice has no transcript and no speech-to-text model is+ # installed to produce one, so the only advice that works is one of those two.+ "REFERENCE_STT_MISSING": "This voice has no transcript, and no speech-to-text model is installed to write one. Type what the reference clip says into the transcript box (clips up to 20 seconds), or install a speech-to-text model in Model Catalogue (Whisper is a good default), select it, then generate again.",+ # A Python package the engine imports is absent from VoiceStudio's+ # environment. Not memory, not the GPU, not the network.+ "ENGINE_DEPENDENCY_MISSING": "A Python package this engine needs is not installed in VoiceStudio's environment, so the engine could not start. Open Model Catalogue, select the engine and use Install / Repair, then restart VoiceStudio. If it still fails, switch to another engine and include the engine name in your report.",# HF_MIRROR_UNREACHABLE has a DYNAMIC hint (it names the configured mirror)# — see hf_mirror_hint(); build_failure special-cases it.}@@ -458,6 +464,11 @@ _CONTEXT_FREE_HINT_CLASSES = frozenset({# Triggered by a VoiceStudio-authored sentence or ffmpeg's own no-stream# wording; it reaches the user through an upload's error response."NO_AUDIO_TRACK",+ # Each is matched on wording only that failure produces: a Python+ # ModuleNotFoundError sentence and VoiceStudio's own reference-transcript+ # sentence.+ "ENGINE_DEPENDENCY_MISSING",+ "REFERENCE_STT_MISSING",})@@ -475,6 +486,10 @@ _TERMINAL_FAILURE_CLASSES = frozenset({"WINDOWS_APP_CONTROL_BLOCKED",# The same file has no audio on every retry."NO_AUDIO_TRACK",+ # A missing package or a missing transcript model does not appear between+ # two renders of the same request.+ "ENGINE_DEPENDENCY_MISSING",+ "REFERENCE_STT_MISSING",})@@ -924,6 +939,14 @@ def classify(reason: BaseException | str) -> str:# quote keeps a legitimately-named `omnivoice_*` helper from matching.if "no module named 'omnivoice'" in low:return "BROKEN_VENV"+ # The reference clip has no transcript and no speech-to-text model exists to+ # write one (omnivoice.models.omnivoice._ReferenceAsrNotInstalled).+ if "automatic reference transcription needs an installed speech-to-text" in low:+ return "REFERENCE_STT_MISSING"+ # Last and narrowest-by-type: an engine imported a package that is not+ # installed. Every earlier no-module rule (encodings, omnivoice) wins first.+ if "no module named '" in low:+ return "ENGINE_DEPENDENCY_MISSING"return ""diff --git a/backend/main.py b/backend/main.pyindex d17f0a667..eabdbd4b0 100644--- a/backend/main.py+++ b/backend/main.py@@ -1632,6 +1632,12 @@ async def global_exception_handler(request: Request, exc: Exception):fallback="VoiceStudio hit an internal error; check the backend log for details.",)content["error_class"] = _entry.get("error_class")+ # The Python exception TYPE rides along with the taxonomy class. The class+ # is "UNKNOWN" for most failures, which made every such 500 render the same+ # fixed sentence AND the same report (#2917/#2916/#2688); the type name is+ # VoiceStudio-safe (a type, never user text) and is what tells a+ # RuntimeError from a KeyError. No substring of the message is copied.+ content["error_type"] = type(exc).__name__return JSONResponse(content,status_code=500,diff --git a/backend/services/tts_backend.py b/backend/services/tts_backend.pyindex bab75f4c3..1fcaf67cf 100644--- a/backend/services/tts_backend.py+++ b/backend/services/tts_backend.py@@ -1231,6 +1231,41 @@ def _reuse_or_rank_passage(ref_audio: str) -> Optional[tuple[str, str]]:return _omnivoice_installed_passage(ref_audio)+def prepare_reference_passage(ref_audio) -> bool:+ """Rank a long reference's best 15 s window NOW, off the generate clock.++ Picking the window runs the installed recognizer over up to five 15 s+ windows. On a CPU that is minutes, and when it ran inside the engine call+ it was charged to the generate budget: the job was then abandoned with+ "TTS generate exceeded 300s" before a single sample was synthesized+ (#2764's log shows a CPU Whisper large-v3 transcribing the voice just+ before). The choice is remembered per recognizer and file version+ (``_recall_passage``), so the engine call that follows recalls it for free.++ Returns True when a passage was chosen or remembered. Never raises, and a+ clip that needs no window (<= the transcript limit) is a no-op.+ """+ if not isinstance(ref_audio, str):+ return False+ try:+ from omnivoice.utils.audio import CLONE_REF_TEXT_MAX_SECONDS++ duration = reference_duration_s(ref_audio)+ if duration is None or duration <= CLONE_REF_TEXT_MAX_SECONDS:+ return False+ selected = _reuse_or_rank_passage(ref_audio)+ except Exception: # noqa: BLE001 — the engine ranks inline as before+ logger.debug("reference passage pre-ranking failed", exc_info=True)+ return False+ if selected is None:+ return False+ try:+ os.remove(selected[0])+ except OSError:+ logger.debug("failed to remove reference window")+ return True++def omnivoice_inline_reference(ref_audio, ref_text):"""``(ref_audio, ref_text, owned_path)`` for a direct ``model.generate()``.diff --git a/docs/install/troubleshooting.md b/docs/install/troubleshooting.mdindex a11e1cc23..4d6ff33d1 100644--- a/docs/install/troubleshooting.md+++ b/docs/install/troubleshooting.md@@ -103,8 +103,18 @@ receive a stable `docs_topic` and a safe fallback message, never private excepti| `HOST_MEMORY_EXHAUSTED` | The machine ran out of system memory, so the engine could not finish. Close other memory-heavy apps, unload unused models with **Flush models**, render a shorter passage, or select a lighter TTS engine. On Windows, enlarging the page file also helps. A CPU-only machine has no GPU memory to free — this is RAM, not VRAM. || `WINDOWS_APP_CONTROL_BLOCKED` | Windows application control blocked a required file. Ask the administrator to allow the trusted VoiceStudio runtime, then restart the app. || `AUDIO_IO_FAILED` | Check the audio format, free disk space, and file permissions; review the folder in Settings → Storage. |+| `ENGINE_DEPENDENCY_MISSING` | A Python package the engine imports is not installed. Open Model Catalogue, select the engine and use **Install / Repair**, then restart VoiceStudio. Terminal: retrying the same request fails the same way. |+| `REFERENCE_STT_MISSING` | The voice has no transcript and no speech-to-text model is installed to write one. Type the reference clip's words into the transcript box (clips up to 20 seconds), or install and select a speech-to-text model in Model Catalogue. || `HF_MIRROR_UNREACHABLE` | The configured Hugging Face mirror could not be reached while fetching the engine's weights. Restore the official endpoint in Settings → Models → Hugging Face mirror, then retry. |+Every unclassified 500 also carries `error_type` (the Python exception class, never+its message), and bug reports record it as "Backend error class" together with the+"Backend failure topic". A reverse proxy that times out (`502`/`504` with its own HTML+page) is reported as a proxy problem, not a VoiceStudio one: raise its read timeout+(for nginx, `proxy_read_timeout`) for long generations. Choosing the best 15-second+window of a long reference clip happens before the generate time budget starts, so a+slow CPU speech-to-text model no longer causes `TTS generate exceeded 300s`.+Unsupported GPU builds and application-control blocks are terminal for the currentstream: the client does not automatically render the whole passage again. Aftercorrecting the cause, start a new generation. Host RAM exhaustion is *not*diff --git a/electron/src/renderer/src/i18n/locales/ar.json b/electron/src/renderer/src/i18n/locales/ar.jsonindex 878488ce8..0de19c117 100644--- a/electron/src/renderer/src/i18n/locales/ar.json+++ b/electron/src/renderer/src/i18n/locales/ar.json@@ -2825,7 +2825,13 @@"audio_io_failed": "تعذرت قراءة الصوت أو حفظه. تحقق من تنسيق الملف ومساحة القرص المتاحة وأذونات الملفات. راجع المجلد في الإعدادات ← التخزين.","no_audio_track": "لا يحتوي هذا الملف على مسار صوتي، لذا لا يوجد كلام لتفريغه أو دبلجته أو استنساخه. اختر ملف فيديو أو صوت يحتوي على صوت.","transcription_media_tool": "يحتاج التفريغ النصي إلى ffmpeg، ولم يتمكن VoiceStudio من العثور عليه أو تشغيله. افتح الإعدادات ← أدوات الصوت واستخدم تنزيل/إصلاح، أو ثبّت ffmpeg (macOS: brew install ffmpeg؛ Windows: winget install Gyan.FFmpeg؛ Linux: مدير الحزم لديك) ثم أعد تشغيل VoiceStudio. يمكنك أيضًا توجيه FFMPEG_PATH إلى ملف ffmpeg.",- "transcription_pipe_lost": "فقد الخادم الخلفي قناة الإخراج إلى التطبيق أثناء التفريغ النصي (broken pipe). أعد تشغيل VoiceStudio وحاول مرة أخرى."+ "transcription_pipe_lost": "فقد الخادم الخلفي قناة الإخراج إلى التطبيق أثناء التفريغ النصي (broken pipe). أعد تشغيل VoiceStudio وحاول مرة أخرى.",+ "gpu_oom": "نفدت ذاكرة وحدة معالجة الرسومات. أغلق التطبيقات الأخرى التي تستخدمها بكثافة أو أفرغ النماذج ثم أعد المحاولة. يمكنك أيضًا اختيار المعالج (CPU) في الإعدادات ← الأداء والجهاز أو اختيار محرك TTS أصغر.",+ "host_memory_exhausted": "نفدت ذاكرة الجهاز. أغلق التطبيقات وعلامات تبويب المتصفح التي تستهلك الذاكرة، وأفرغ النماذج غير المستخدمة، وولّد مقطعًا أقصر، أو اختر محرك TTS أخف.",+ "engine_dependency_missing": "حزمة Python يحتاجها هذا المحرك غير مثبتة، لذلك تعذّر تشغيله. افتح كتالوج النماذج، وحدّد المحرك واستخدم تثبيت/إصلاح، ثم أعد تشغيل VoiceStudio.",+ "reference_stt_missing": "ليس لهذا الصوت نص مكتوب ولم يُثبَّت نموذج تحويل الكلام إلى نص لإنشائه. اكتب ما يقوله المقطع المرجعي في خانة النص (للمقاطع حتى 20 ثانية)، أو ثبّت نموذج تحويل الكلام إلى نص من كتالوج النماذج وحدّده، ثم أعد التوليد.",+ "proxy_gateway_error": "ردّ وكيل أو بوابة بين جهازك وVoiceStudio بالرمز HTTP {{status}} بدلاً من الخادم الخلفي. قد يكون الخادم الخلفي ما يزال يعمل. ارفع مهلة القراءة في الوكيل (في nginx هي proxy_read_timeout) للتوليدات الطويلة، ثم راجع الإعدادات ← السجلات ← الخادم الخلفي.",+ "route_not_found": "الخادم الخلفي الجاري تشغيله لا يملك نقطة النهاية {{route}}. أعد تشغيل VoiceStudio لتتطابق إصدارات التطبيق والخادم؛ وإن استمر الأمر فحدّث كليهما إلى الإصدار نفسه."},"network": {"copied": "منقول",diff --git a/electron/src/renderer/src/i18n/locales/de.json b/electron/src/renderer/src/i18n/locales/de.jsonindex 3a476d101..4f2b20a48 100644--- a/electron/src/renderer/src/i18n/locales/de.json+++ b/electron/src/renderer/src/i18n/locales/de.json@@ -2817,7 +2817,13 @@"audio_io_failed": "Die Audiodatei konnte nicht gelesen oder gespeichert werden. Prüfe Dateiformat, freien Speicherplatz und Dateiberechtigungen. Überprüfe den Ordner unter Einstellungen → Speicher.","no_audio_track": "Diese Datei hat keine Tonspur, daher gibt es keine Sprache zum Transkribieren, Synchronisieren oder Klonen. Wähle eine Video- oder Audiodatei mit Ton.","transcription_media_tool": "Für die Transkription wird ffmpeg benötigt, das VoiceStudio nicht finden oder ausführen konnte. Öffne Einstellungen → Audiotools und nutze Herunterladen/Reparieren, oder installiere ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: dein Paketmanager) und starte VoiceStudio neu. Alternativ kannst du FFMPEG_PATH auf eine ffmpeg-Datei setzen.",- "transcription_pipe_lost": "Das Backend hat während der Transkription seine Ausgabe-Pipe zur App verloren (Broken Pipe). Starte VoiceStudio neu und versuche es erneut."+ "transcription_pipe_lost": "Das Backend hat während der Transkription seine Ausgabe-Pipe zur App verloren (Broken Pipe). Starte VoiceStudio neu und versuche es erneut.",+ "gpu_oom": "Der GPU ist der Speicher ausgegangen. Schließe andere GPU-intensive Apps oder entlade Modelle und versuche es erneut. Du kannst auch unter Einstellungen → Leistung & Gerät die CPU wählen oder eine kleinere TTS-Engine auswählen.",+ "host_memory_exhausted": "Dem Computer ist der Arbeitsspeicher ausgegangen. Schließe andere speicherintensive Apps und Browser-Tabs, entlade nicht benötigte Modelle, erzeuge einen kürzeren Abschnitt oder wähle eine leichtere TTS-Engine.",+ "engine_dependency_missing": "Ein Python-Paket, das diese Engine benötigt, ist nicht installiert, daher konnte sie nicht starten. Öffne den Modellkatalog, wähle die Engine und nutze Installieren/Reparieren, und starte VoiceStudio dann neu.",+ "reference_stt_missing": "Diese Stimme hat kein Transkript, und es ist kein Spracherkennungsmodell installiert, um eines zu erstellen. Gib ein, was der Referenzclip sagt (Clips bis 20 Sekunden), oder installiere im Modellkatalog ein Spracherkennungsmodell, wähle es aus und erzeuge erneut.",+ "proxy_gateway_error": "Ein Proxy oder Gateway zwischen dir und VoiceStudio hat statt des Backends HTTP {{status}} geantwortet. Das Backend arbeitet möglicherweise noch. Erhöhe für lange Erzeugungen das Lese-Timeout des Proxys (bei nginx proxy_read_timeout) und prüfe dann Einstellungen → Protokolle → Backend.",+ "route_not_found": "Das laufende VoiceStudio-Backend kennt den Endpunkt {{route}} nicht. Starte VoiceStudio neu, damit App und Backend zusammenpassen; bleibt das Problem, aktualisiere beide auf dieselbe Version."},"network": {"copied": "Kopiert",diff --git a/electron/src/renderer/src/i18n/locales/en.json b/electron/src/renderer/src/i18n/locales/en.jsonindex 73cb05747..8fdaf7a11 100644--- a/electron/src/renderer/src/i18n/locales/en.json+++ b/electron/src/renderer/src/i18n/locales/en.json@@ -553,7 +553,13 @@"audio_io_failed": "Audio could not be read or saved. Check the file format, free disk space, and file permissions. Review the folder in Settings → Storage.","no_audio_track": "This file has no audio track, so there is no speech to transcribe, dub or clone. Choose a video or audio file that contains sound.","transcription_media_tool": "Transcription needs ffmpeg, which VoiceStudio could not find or run. Open Settings → Audio tools and use Download/Repair, or install ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: your package manager) and restart VoiceStudio. You can also point FFMPEG_PATH at an ffmpeg binary.",- "transcription_pipe_lost": "The backend lost its output pipe to the app while transcribing (broken pipe). Restart VoiceStudio and try again."+ "transcription_pipe_lost": "The backend lost its output pipe to the app while transcribing (broken pipe). Restart VoiceStudio and try again.",+ "gpu_oom": "The GPU ran out of memory. Close other GPU-heavy apps or unload models, then retry. You can also choose CPU in Settings → Performance & Device or select a smaller TTS engine.",+ "host_memory_exhausted": "The computer ran out of memory. Close other memory-heavy apps and browser tabs, flush models you are not using, render a shorter passage, or select a lighter TTS engine.",+ "engine_dependency_missing": "A Python package this engine needs is not installed, so the engine could not start. Open Model Catalogue, select the engine and use Install / Repair, then restart VoiceStudio.",+ "reference_stt_missing": "This voice has no transcript and no speech-to-text model is installed to write one. Type what the reference clip says into the transcript box (clips up to 20 seconds), or install a speech-to-text model in Model Catalogue, select it, then generate again.",+ "proxy_gateway_error": "A proxy or gateway between you and VoiceStudio answered HTTP {{status}} instead of the backend. The backend may still be working. Raise the proxy's read timeout (for nginx, proxy_read_timeout) for long generations, then check Settings → Logs → Backend.",+ "route_not_found": "The running VoiceStudio backend has no {{route}} endpoint. Restart VoiceStudio so the app and backend match; if it persists, update both to the same version."},"tts": {"generationComplete": "Speech generation complete",diff --git a/electron/src/renderer/src/i18n/locales/es.json b/electron/src/renderer/src/i18n/locales/es.jsonindex a96464926..fa8941503 100644--- a/electron/src/renderer/src/i18n/locales/es.json+++ b/electron/src/renderer/src/i18n/locales/es.json@@ -2819,7 +2819,13 @@"audio_io_failed": "No se pudo leer o guardar el audio. Comprueba el formato, el espacio libre y los permisos del archivo. Revisa la carpeta en Ajustes → Almacenamiento.","no_audio_track": "Este archivo no tiene pista de audio, así que no hay voz que transcribir, doblar o clonar. Elige un archivo de vídeo o audio que tenga sonido.","transcription_media_tool": "La transcripción necesita ffmpeg, que VoiceStudio no pudo encontrar o ejecutar. Abre Ajustes → Herramientas de audio y usa Descargar/Reparar, o instala ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: tu gestor de paquetes) y reinicia VoiceStudio. También puedes apuntar FFMPEG_PATH a un binario de ffmpeg.",- "transcription_pipe_lost": "El backend perdió su canal de salida con la aplicación durante la transcripción (broken pipe). Reinicia VoiceStudio e inténtalo de nuevo."+ "transcription_pipe_lost": "El backend perdió su canal de salida con la aplicación durante la transcripción (broken pipe). Reinicia VoiceStudio e inténtalo de nuevo.",+ "gpu_oom": "La GPU se quedó sin memoria. Cierra otras apps que usen mucho la GPU o descarga modelos y vuelve a intentarlo. También puedes elegir CPU en Ajustes → Rendimiento y dispositivo o seleccionar un motor TTS más pequeño.",+ "host_memory_exhausted": "El equipo se quedó sin memoria. Cierra otras apps y pestañas del navegador que consuman memoria, libera los modelos que no uses, genera un fragmento más corto o elige un motor TTS más ligero.",+ "engine_dependency_missing": "Falta instalar un paquete de Python que necesita este motor, por lo que no pudo iniciarse. Abre el Catálogo de modelos, selecciona el motor y usa Instalar / Reparar; luego reinicia VoiceStudio.",+ "reference_stt_missing": "Esta voz no tiene transcripción y no hay ningún modelo de voz a texto instalado para crearla. Escribe lo que dice el clip de referencia en el cuadro de transcripción (clips de hasta 20 segundos) o instala un modelo de voz a texto en el Catálogo de modelos, selecciónalo y genera de nuevo.",+ "proxy_gateway_error": "Un proxy o puerta de enlace entre tú y VoiceStudio respondió HTTP {{status}} en lugar del backend. Puede que el backend siga trabajando. Aumenta el tiempo de espera de lectura del proxy (en nginx, proxy_read_timeout) para generaciones largas y revisa Ajustes → Registros → Backend.",+ "route_not_found": "El backend de VoiceStudio en ejecución no tiene el endpoint {{route}}. Reinicia VoiceStudio para que la app y el backend coincidan; si persiste, actualiza ambos a la misma versión."},"network": {"copied": "Copiado",diff --git a/electron/src/renderer/src/i18n/locales/fr.json b/electron/src/renderer/src/i18n/locales/fr.jsonindex 5463ff265..bf6e7bec5 100644--- a/electron/src/renderer/src/i18n/locales/fr.json+++ b/electron/src/renderer/src/i18n/locales/fr.json@@ -2819,7 +2819,13 @@"audio_io_failed": "Impossible de lire ou d’enregistrer l’audio. Vérifiez le format du fichier, l’espace disque disponible et les autorisations. Vérifiez le dossier dans Paramètres → Stockage.","no_audio_track": "Ce fichier n'a pas de piste audio : il n'y a donc aucune parole à transcrire, doubler ou cloner. Choisissez un fichier vidéo ou audio qui contient du son.","transcription_media_tool": "La transcription nécessite ffmpeg, que VoiceStudio n'a pas pu trouver ou exécuter. Ouvrez Paramètres → Outils audio et utilisez Télécharger/Réparer, ou installez ffmpeg (macOS : brew install ffmpeg ; Windows : winget install Gyan.FFmpeg ; Linux : votre gestionnaire de paquets), puis redémarrez VoiceStudio. Vous pouvez aussi faire pointer FFMPEG_PATH vers un binaire ffmpeg.",- "transcription_pipe_lost": "Le backend a perdu son canal de sortie vers l'application pendant la transcription (broken pipe). Redémarrez VoiceStudio et réessayez."+ "transcription_pipe_lost": "Le backend a perdu son canal de sortie vers l'application pendant la transcription (broken pipe). Redémarrez VoiceStudio et réessayez.",+ "gpu_oom": "La mémoire du GPU est saturée. Fermez les autres applications gourmandes en GPU ou déchargez des modèles, puis réessayez. Vous pouvez aussi choisir le CPU dans Paramètres → Performances et appareil ou sélectionner un moteur TTS plus léger.",+ "host_memory_exhausted": "L'ordinateur n'a plus de mémoire. Fermez les autres applications et onglets gourmands en mémoire, déchargez les modèles inutilisés, générez un passage plus court ou choisissez un moteur TTS plus léger.",+ "engine_dependency_missing": "Un paquet Python requis par ce moteur n'est pas installé, le moteur n'a donc pas pu démarrer. Ouvrez le Catalogue de modèles, sélectionnez le moteur et utilisez Installer / Réparer, puis redémarrez VoiceStudio.",+ "reference_stt_missing": "Cette voix n'a pas de transcription et aucun modèle de reconnaissance vocale n'est installé pour en créer une. Saisissez ce que dit l'extrait de référence dans la zone de transcription (extraits jusqu'à 20 secondes), ou installez un modèle de reconnaissance vocale dans le Catalogue de modèles, sélectionnez-le et générez à nouveau.",+ "proxy_gateway_error": "Un proxy ou une passerelle entre vous et VoiceStudio a répondu HTTP {{status}} à la place du backend. Le backend est peut-être encore en cours de traitement. Augmentez le délai de lecture du proxy (pour nginx, proxy_read_timeout) pour les longues générations, puis consultez Paramètres → Journaux → Backend.",+ "route_not_found": "Le backend VoiceStudio en cours d'exécution n'a pas le point d'accès {{route}}. Redémarrez VoiceStudio pour que l'application et le backend correspondent ; si le problème persiste, mettez les deux à jour vers la même version."},"network": {"copied": "Copié",diff --git a/electron/src/renderer/src/i18n/locales/hi.json b/electron/src/renderer/src/i18n/locales/hi.jsonindex 97422a188..1144ac41f 100644--- a/electron/src/renderer/src/i18n/locales/hi.json+++ b/electron/src/renderer/src/i18n/locales/hi.json@@ -2817,7 +2817,13 @@"audio_io_failed": "ऑडियो पढ़ा या सहेजा नहीं जा सका। फ़ाइल का प्रारूप, डिस्क में खाली जगह और फ़ाइल की अनुमतियाँ जाँचें। सेटिंग्स → स्टोरेज में फ़ोल्डर जाँचें।","no_audio_track": "इस फ़ाइल में कोई ऑडियो ट्रैक नहीं है, इसलिए ट्रांसक्राइब, डब या क्लोन करने के लिए कोई आवाज़ नहीं है। ऐसी वीडियो या ऑडियो फ़ाइल चुनें जिसमें ध्वनि हो।","transcription_media_tool": "ट्रांसक्रिप्शन के लिए ffmpeg चाहिए, जिसे VoiceStudio ढूँढ या चला नहीं सका। सेटिंग्स → ऑडियो टूल खोलकर डाउनलोड/रिपेयर इस्तेमाल करें, या ffmpeg इंस्टॉल करें (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: आपका पैकेज मैनेजर) और VoiceStudio फिर से शुरू करें। आप FFMPEG_PATH को किसी ffmpeg फ़ाइल की ओर भी इंगित कर सकते हैं।",- "transcription_pipe_lost": "ट्रांसक्रिप्शन के दौरान बैकएंड का ऐप से आउटपुट पाइप टूट गया (broken pipe)। VoiceStudio फिर से शुरू करें और दोबारा कोशिश करें।"+ "transcription_pipe_lost": "ट्रांसक्रिप्शन के दौरान बैकएंड का ऐप से आउटपुट पाइप टूट गया (broken pipe)। VoiceStudio फिर से शुरू करें और दोबारा कोशिश करें।",+ "gpu_oom": "GPU की मेमोरी खत्म हो गई। GPU का भारी उपयोग करने वाले दूसरे ऐप बंद करें या मॉडल अनलोड करें, फिर दोबारा कोशिश करें। आप सेटिंग्स → प्रदर्शन और डिवाइस में CPU चुन सकते हैं या छोटा TTS इंजन चुन सकते हैं।",+ "host_memory_exhausted": "कंप्यूटर की मेमोरी खत्म हो गई। ज़्यादा मेमोरी लेने वाले दूसरे ऐप और ब्राउज़र टैब बंद करें, इस्तेमाल न हो रहे मॉडल अनलोड करें, छोटा अंश बनाएँ या हल्का TTS इंजन चुनें।",+ "engine_dependency_missing": "इस इंजन को जिस Python पैकेज की ज़रूरत है वह इंस्टॉल नहीं है, इसलिए इंजन शुरू नहीं हो सका। मॉडल कैटलॉग खोलें, इंजन चुनें और इंस्टॉल / मरम्मत का उपयोग करें, फिर VoiceStudio को रीस्टार्ट करें।",+ "reference_stt_missing": "इस आवाज़ का कोई ट्रांसक्रिप्ट नहीं है और उसे बनाने के लिए कोई स्पीच-टू-टेक्स्ट मॉडल इंस्टॉल नहीं है। रेफ़रेंस क्लिप में जो बोला गया है उसे ट्रांसक्रिप्ट बॉक्स में लिखें (20 सेकंड तक की क्लिप), या मॉडल कैटलॉग में स्पीच-टू-टेक्स्ट मॉडल इंस्टॉल करके चुनें और फिर से जनरेट करें।",+ "proxy_gateway_error": "आपके और VoiceStudio के बीच किसी प्रॉक्सी या गेटवे ने बैकएंड की जगह HTTP {{status}} लौटाया। बैकएंड शायद अब भी काम कर रहा हो। लंबे जनरेशन के लिए प्रॉक्सी का रीड टाइमआउट बढ़ाएँ (nginx में proxy_read_timeout), फिर सेटिंग्स → लॉग → बैकएंड देखें।",+ "route_not_found": "चल रहे VoiceStudio बैकएंड में {{route}} एंडपॉइंट नहीं है। ऐप और बैकएंड का मेल कराने के लिए VoiceStudio को रीस्टार्ट करें; समस्या बनी रहे तो दोनों को एक ही वर्ज़न पर अपडेट करें।"},"network": {"copied": "नकल की गई",diff --git a/electron/src/renderer/src/i18n/locales/id.json b/electron/src/renderer/src/i18n/locales/id.jsonindex 341c510a7..8e6c4f2ff 100644--- a/electron/src/renderer/src/i18n/locales/id.json+++ b/electron/src/renderer/src/i18n/locales/id.json@@ -2817,7 +2817,13 @@"audio_io_failed": "Audio tidak dapat dibaca atau disimpan. Periksa format file, ruang disk yang tersedia, dan izin file. Periksa folder di Pengaturan → Penyimpanan.","no_audio_track": "File ini tidak memiliki trek audio, jadi tidak ada ucapan untuk ditranskripsi, di-dubbing, atau dikloning. Pilih file video atau audio yang berisi suara.","transcription_media_tool": "Transkripsi membutuhkan ffmpeg, yang tidak dapat ditemukan atau dijalankan VoiceStudio. Buka Pengaturan → Alat audio lalu gunakan Unduh/Perbaiki, atau instal ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: pengelola paket Anda) dan mulai ulang VoiceStudio. Anda juga dapat mengarahkan FFMPEG_PATH ke berkas ffmpeg.",- "transcription_pipe_lost": "Backend kehilangan saluran keluarannya ke aplikasi saat transkripsi (broken pipe). Mulai ulang VoiceStudio dan coba lagi."+ "transcription_pipe_lost": "Backend kehilangan saluran keluarannya ke aplikasi saat transkripsi (broken pipe). Mulai ulang VoiceStudio dan coba lagi.",+ "gpu_oom": "GPU kehabisan memori. Tutup aplikasi lain yang berat memakai GPU atau bongkar model, lalu coba lagi. Anda juga bisa memilih CPU di Pengaturan → Performa & Perangkat atau memilih mesin TTS yang lebih kecil.",+ "host_memory_exhausted": "Komputer kehabisan memori. Tutup aplikasi dan tab peramban lain yang boros memori, bongkar model yang tidak dipakai, buat bagian yang lebih pendek, atau pilih mesin TTS yang lebih ringan.",+ "engine_dependency_missing": "Paket Python yang dibutuhkan mesin ini belum terpasang, sehingga mesin tidak bisa dimulai. Buka Katalog Model, pilih mesin lalu gunakan Pasang / Perbaiki, kemudian mulai ulang VoiceStudio.",+ "reference_stt_missing": "Suara ini tidak punya transkrip dan tidak ada model ucapan-ke-teks yang terpasang untuk membuatnya. Ketik isi klip referensi di kotak transkrip (klip hingga 20 detik), atau pasang model ucapan-ke-teks di Katalog Model, pilih, lalu buat lagi.",+ "proxy_gateway_error": "Proxy atau gateway di antara Anda dan VoiceStudio menjawab HTTP {{status}} menggantikan backend. Backend mungkin masih bekerja. Naikkan batas waktu baca proxy (di nginx, proxy_read_timeout) untuk pembuatan yang panjang, lalu periksa Pengaturan → Log → Backend.",+ "route_not_found": "Backend VoiceStudio yang berjalan tidak memiliki endpoint {{route}}. Mulai ulang VoiceStudio agar aplikasi dan backend cocok; jika masih terjadi, perbarui keduanya ke versi yang sama."},"network": {"copied": "Disalin",diff --git a/electron/src/renderer/src/i18n/locales/it.json b/electron/src/renderer/src/i18n/locales/it.jsonindex 6d566614d..2992d23e8 100644--- a/electron/src/renderer/src/i18n/locales/it.json+++ b/electron/src/renderer/src/i18n/locales/it.json@@ -2819,7 +2819,13 @@"audio_io_failed": "Impossibile leggere o salvare l’audio. Controlla il formato del file, lo spazio libero e le autorizzazioni. Verifica la cartella in Impostazioni → Archiviazione.","no_audio_track": "Questo file non ha una traccia audio, quindi non c'è parlato da trascrivere, doppiare o clonare. Scegli un file video o audio che contenga suono.","transcription_media_tool": "La trascrizione richiede ffmpeg, che VoiceStudio non ha trovato o non è riuscito a eseguire. Apri Impostazioni → Strumenti audio e usa Scarica/Ripara, oppure installa ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: il tuo gestore di pacchetti) e riavvia VoiceStudio. Puoi anche puntare FFMPEG_PATH a un binario ffmpeg.",- "transcription_pipe_lost": "Il backend ha perso il canale di output verso l'app durante la trascrizione (broken pipe). Riavvia VoiceStudio e riprova."+ "transcription_pipe_lost": "Il backend ha perso il canale di output verso l'app durante la trascrizione (broken pipe). Riavvia VoiceStudio e riprova.",+ "gpu_oom": "La GPU ha esaurito la memoria. Chiudi le altre app che usano molto la GPU o scarica i modelli, poi riprova. Puoi anche scegliere la CPU in Impostazioni → Prestazioni e dispositivo o selezionare un motore TTS più piccolo.",+ "host_memory_exhausted": "Il computer ha esaurito la memoria. Chiudi le altre app e le schede del browser che usano molta memoria, scarica i modelli inutilizzati, genera un brano più breve o scegli un motore TTS più leggero.",+ "engine_dependency_missing": "Manca un pacchetto Python necessario a questo motore, quindi non è stato possibile avviarlo. Apri il Catalogo modelli, seleziona il motore e usa Installa / Ripara, poi riavvia VoiceStudio.",+ "reference_stt_missing": "Questa voce non ha una trascrizione e non è installato alcun modello di riconoscimento vocale per crearne una. Scrivi ciò che dice la clip di riferimento nella casella della trascrizione (clip fino a 20 secondi), oppure installa un modello di riconoscimento vocale nel Catalogo modelli, selezionalo e genera di nuovo.",+ "proxy_gateway_error": "Un proxy o gateway tra te e VoiceStudio ha risposto HTTP {{status}} al posto del backend. Il backend potrebbe essere ancora al lavoro. Aumenta il timeout di lettura del proxy (in nginx, proxy_read_timeout) per le generazioni lunghe, poi controlla Impostazioni → Log → Backend.",+ "route_not_found": "Il backend VoiceStudio in esecuzione non ha l'endpoint {{route}}. Riavvia VoiceStudio perché app e backend coincidano; se persiste, aggiorna entrambi alla stessa versione."},"network": {"copied": "Copiato",diff --git a/electron/src/renderer/src/i18n/locales/ja.json b/electron/src/renderer/src/i18n/locales/ja.jsonindex b7591621b..318575cd5 100644--- a/electron/src/renderer/src/i18n/locales/ja.json+++ b/electron/src/renderer/src/i18n/locales/ja.json@@ -2817,7 +2817,13 @@"audio_io_failed": "音声を読み込むか保存することができませんでした。ファイル形式、ディスクの空き容量、ファイルのアクセス権を確認してください。設定 → ストレージでフォルダーを確認してください。","no_audio_track": "このファイルには音声トラックがないため、文字起こし・吹き替え・クローンする音声がありません。音声を含む動画または音声ファイルを選んでください。","transcription_media_tool": "文字起こしには ffmpeg が必要ですが、VoiceStudio は見つけられないか実行できませんでした。設定 → オーディオツールを開いてダウンロード/修復を使うか、ffmpeg をインストール(macOS: brew install ffmpeg、Windows: winget install Gyan.FFmpeg、Linux: お使いのパッケージマネージャー)して VoiceStudio を再起動してください。FFMPEG_PATH を ffmpeg のファイルに向けることもできます。",- "transcription_pipe_lost": "文字起こし中にバックエンドがアプリへの出力パイプを失いました(broken pipe)。VoiceStudio を再起動してもう一度お試しください。"+ "transcription_pipe_lost": "文字起こし中にバックエンドがアプリへの出力パイプを失いました(broken pipe)。VoiceStudio を再起動してもう一度お試しください。",+ "gpu_oom": "GPU のメモリが不足しました。GPU を多く使う他のアプリを閉じるかモデルをアンロードしてから、もう一度お試しください。設定 → パフォーマンスとデバイスで CPU を選ぶか、より小さな TTS エンジンを選ぶこともできます。",+ "host_memory_exhausted": "コンピューターのメモリが不足しました。メモリを多く使う他のアプリやブラウザータブを閉じ、使っていないモデルをアンロードし、短い文章で生成するか、より軽い TTS エンジンを選んでください。",+ "engine_dependency_missing": "このエンジンに必要な Python パッケージがインストールされていないため、エンジンを起動できませんでした。モデルカタログを開き、エンジンを選んでインストール/修復を使い、VoiceStudio を再起動してください。",+ "reference_stt_missing": "この音声には文字起こしがなく、作成するための音声認識モデルもインストールされていません。参照クリップの内容を文字起こし欄に入力する(20 秒までのクリップ)か、モデルカタログで音声認識モデルをインストールして選択し、もう一度生成してください。",+ "proxy_gateway_error": "お使いの環境と VoiceStudio の間のプロキシまたはゲートウェイが、バックエンドの代わりに HTTP {{status}} を返しました。バックエンドはまだ処理中の可能性があります。長い生成のためにプロキシの読み取りタイムアウト(nginx では proxy_read_timeout)を延ばし、設定 → ログ → バックエンドを確認してください。",+ "route_not_found": "実行中の VoiceStudio バックエンドに {{route}} エンドポイントがありません。アプリとバックエンドを一致させるため VoiceStudio を再起動してください。解決しない場合は両方を同じバージョンに更新してください。"},"network": {"copied": "コピーされました",diff --git a/electron/src/renderer/src/i18n/locales/ko.json b/electron/src/renderer/src/i18n/locales/ko.jsonindex 9d1215b8a..e70b0cc05 100644--- a/electron/src/renderer/src/i18n/locales/ko.json+++ b/electron/src/renderer/src/i18n/locales/ko.json@@ -2817,7 +2817,13 @@"audio_io_failed": "오디오를 읽거나 저장할 수 없습니다. 파일 형식, 디스크 여유 공간 및 파일 권한을 확인하세요. 설정 → 저장소에서 폴더를 확인하세요.","no_audio_track": "이 파일에는 오디오 트랙이 없어 전사, 더빙 또는 복제할 음성이 없습니다. 소리가 있는 동영상 또는 오디오 파일을 선택하세요.","transcription_media_tool": "전사에는 ffmpeg가 필요하지만 VoiceStudio가 찾거나 실행하지 못했습니다. 설정 → 오디오 도구에서 다운로드/복구를 사용하거나 ffmpeg를 설치(macOS: brew install ffmpeg, Windows: winget install Gyan.FFmpeg, Linux: 사용 중인 패키지 관리자)한 뒤 VoiceStudio를 다시 시작하세요. FFMPEG_PATH를 ffmpeg 파일로 지정할 수도 있습니다.",- "transcription_pipe_lost": "전사 중 백엔드가 앱으로의 출력 파이프를 잃었습니다(broken pipe). VoiceStudio를 다시 시작한 뒤 다시 시도하세요."+ "transcription_pipe_lost": "전사 중 백엔드가 앱으로의 출력 파이프를 잃었습니다(broken pipe). VoiceStudio를 다시 시작한 뒤 다시 시도하세요.",+ "gpu_oom": "GPU 메모리가 부족합니다. GPU를 많이 쓰는 다른 앱을 닫거나 모델을 언로드한 뒤 다시 시도하세요. 설정 → 성능 및 장치에서 CPU를 선택하거나 더 작은 TTS 엔진을 선택할 수도 있습니다.",+ "host_memory_exhausted": "컴퓨터의 메모리가 부족합니다. 메모리를 많이 쓰는 다른 앱과 브라우저 탭을 닫고, 쓰지 않는 모델을 언로드하고, 더 짧은 구간을 생성하거나 더 가벼운 TTS 엔진을 선택하세요.",+ "engine_dependency_missing": "이 엔진에 필요한 Python 패키지가 설치되어 있지 않아 엔진을 시작할 수 없습니다. 모델 카탈로그를 열어 엔진을 선택하고 설치/복구를 사용한 뒤 VoiceStudio를 다시 시작하세요.",+ "reference_stt_missing": "이 음성에는 스크립트가 없고 스크립트를 만들 음성 인식 모델도 설치되어 있지 않습니다. 참조 클립의 내용을 스크립트 입력란에 입력하거나(20초 이하 클립), 모델 카탈로그에서 음성 인식 모델을 설치해 선택한 뒤 다시 생성하세요.",+ "proxy_gateway_error": "사용자와 VoiceStudio 사이의 프록시 또는 게이트웨이가 백엔드 대신 HTTP {{status}}로 응답했습니다. 백엔드는 아직 작업 중일 수 있습니다. 긴 생성을 위해 프록시의 읽기 타임아웃(nginx는 proxy_read_timeout)을 늘린 다음 설정 → 로그 → 백엔드를 확인하세요.",+ "route_not_found": "실행 중인 VoiceStudio 백엔드에 {{route}} 엔드포인트가 없습니다. 앱과 백엔드가 일치하도록 VoiceStudio를 다시 시작하세요. 계속되면 둘 다 같은 버전으로 업데이트하세요."},"network": {"copied": "복사됨",diff --git a/electron/src/renderer/src/i18n/locales/nl.json b/electron/src/renderer/src/i18n/locales/nl.jsonindex 4b405d9ee..ea155610a 100644--- a/electron/src/renderer/src/i18n/locales/nl.json+++ b/electron/src/renderer/src/i18n/locales/nl.json@@ -2817,7 +2817,13 @@"audio_io_failed": "De audio kon niet worden gelezen of opgeslagen. Controleer het bestandsformaat, de vrije schijfruimte en de bestandsrechten. Controleer de map bij Instellingen → Opslag.","no_audio_track": "Dit bestand heeft geen audiotrack, dus er is geen spraak om te transcriberen, na te synchroniseren of te klonen. Kies een video- of audiobestand met geluid.","transcription_media_tool": "Voor transcriptie is ffmpeg nodig, dat VoiceStudio niet kon vinden of uitvoeren. Open Instellingen → Audiotools en gebruik Downloaden/Herstellen, of installeer ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: je pakketbeheerder) en herstart VoiceStudio. Je kunt ook FFMPEG_PATH naar een ffmpeg-bestand laten wijzen.",- "transcription_pipe_lost": "De backend verloor tijdens de transcriptie zijn uitvoerkanaal naar de app (broken pipe). Herstart VoiceStudio en probeer het opnieuw."+ "transcription_pipe_lost": "De backend verloor tijdens de transcriptie zijn uitvoerkanaal naar de app (broken pipe). Herstart VoiceStudio en probeer het opnieuw.",+ "gpu_oom": "De GPU heeft geen geheugen meer. Sluit andere GPU-intensieve apps of ontlaad modellen en probeer het opnieuw. Je kunt ook CPU kiezen in Instellingen → Prestaties en apparaat of een kleinere TTS-engine selecteren.",+ "host_memory_exhausted": "De computer heeft geen geheugen meer. Sluit andere geheugenintensieve apps en browsertabs, ontlaad ongebruikte modellen, genereer een kortere passage of kies een lichtere TTS-engine.",+ "engine_dependency_missing": "Een Python-pakket dat deze engine nodig heeft is niet geïnstalleerd, dus de engine kon niet starten. Open de Modelcatalogus, selecteer de engine en gebruik Installeren / Repareren en start VoiceStudio daarna opnieuw.",+ "reference_stt_missing": "Deze stem heeft geen transcriptie en er is geen spraak-naar-tekstmodel geïnstalleerd om er een te maken. Typ wat de referentieclip zegt in het transcriptievak (clips tot 20 seconden) of installeer een spraak-naar-tekstmodel in de Modelcatalogus, selecteer het en genereer opnieuw.",+ "proxy_gateway_error": "Een proxy of gateway tussen jou en VoiceStudio antwoordde met HTTP {{status}} in plaats van de backend. De backend is mogelijk nog bezig. Verhoog de lees-timeout van de proxy (bij nginx proxy_read_timeout) voor lange generaties en controleer daarna Instellingen → Logboeken → Backend.",+ "route_not_found": "De draaiende VoiceStudio-backend heeft geen {{route}}-endpoint. Start VoiceStudio opnieuw zodat app en backend overeenkomen; blijft het probleem, werk dan beide bij naar dezelfde versie."},"network": {"copied": "Gekopieerd",diff --git a/electron/src/renderer/src/i18n/locales/pl.json b/electron/src/renderer/src/i18n/locales/pl.jsonindex 766ae1ac8..fbecd91ff 100644--- a/electron/src/renderer/src/i18n/locales/pl.json+++ b/electron/src/renderer/src/i18n/locales/pl.json@@ -2821,7 +2821,13 @@"audio_io_failed": "Nie można odczytać ani zapisać dźwięku. Sprawdź format pliku, wolne miejsce na dysku i uprawnienia do plików. Sprawdź folder w Ustawienia → Pamięć.","no_audio_track": "Ten plik nie ma ścieżki dźwiękowej, więc nie ma mowy do transkrypcji, dubbingu ani klonowania. Wybierz plik wideo lub audio zawierający dźwięk.","transcription_media_tool": "Transkrypcja wymaga ffmpeg, którego VoiceStudio nie mogło znaleźć lub uruchomić. Otwórz Ustawienia → Narzędzia audio i użyj Pobierz/Napraw albo zainstaluj ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: menedżer pakietów) i uruchom VoiceStudio ponownie. Możesz też wskazać plik ffmpeg w FFMPEG_PATH.",- "transcription_pipe_lost": "Backend utracił kanał wyjściowy do aplikacji podczas transkrypcji (broken pipe). Uruchom VoiceStudio ponownie i spróbuj jeszcze raz."+ "transcription_pipe_lost": "Backend utracił kanał wyjściowy do aplikacji podczas transkrypcji (broken pipe). Uruchom VoiceStudio ponownie i spróbuj jeszcze raz.",+ "gpu_oom": "Procesorowi graficznemu zabrakło pamięci. Zamknij inne aplikacje mocno obciążające GPU lub wyładuj modele, a potem spróbuj ponownie. Możesz też wybrać CPU w Ustawienia → Wydajność i urządzenie albo mniejszy silnik TTS.",+ "host_memory_exhausted": "Komputerowi zabrakło pamięci. Zamknij inne aplikacje i karty przeglądarki zajmujące dużo pamięci, wyładuj nieużywane modele, wygeneruj krótszy fragment lub wybierz lżejszy silnik TTS.",+ "engine_dependency_missing": "Pakiet Pythona potrzebny temu silnikowi nie jest zainstalowany, więc silnik nie mógł się uruchomić. Otwórz Katalog modeli, wybierz silnik i użyj Zainstaluj / Napraw, a potem uruchom VoiceStudio ponownie.",+ "reference_stt_missing": "Ten głos nie ma transkrypcji, a nie jest zainstalowany żaden model rozpoznawania mowy, który mógłby ją utworzyć. Wpisz w polu transkrypcji, co mówi klip referencyjny (klipy do 20 sekund), albo zainstaluj model rozpoznawania mowy w Katalogu modeli, wybierz go i wygeneruj ponownie.",+ "proxy_gateway_error": "Serwer proxy lub brama między Tobą a VoiceStudio odpowiedziały HTTP {{status}} zamiast backendu. Backend może nadal pracować. Zwiększ limit czasu odczytu proxy (w nginx proxy_read_timeout) dla długich generacji, a potem sprawdź Ustawienia → Dzienniki → Backend.",+ "route_not_found": "Uruchomiony backend VoiceStudio nie ma punktu końcowego {{route}}. Uruchom VoiceStudio ponownie, aby aplikacja i backend do siebie pasowały; jeśli problem się utrzymuje, zaktualizuj oba do tej samej wersji."},"network": {"copied": "Skopiowano",diff --git a/electron/src/renderer/src/i18n/locales/pt.json b/electron/src/renderer/src/i18n/locales/pt.jsonindex 32dcc75a7..cd5eeb13c 100644--- a/electron/src/renderer/src/i18n/locales/pt.json+++ b/electron/src/renderer/src/i18n/locales/pt.json@@ -2819,7 +2819,13 @@"audio_io_failed": "Não foi possível ler ou salvar o áudio. Verifique o formato do arquivo, o espaço livre e as permissões. Confira a pasta em Configurações → Armazenamento.","no_audio_track": "Este arquivo não tem faixa de áudio, então não há fala para transcrever, dublar ou clonar. Escolha um arquivo de vídeo ou áudio que tenha som.","transcription_media_tool": "A transcrição precisa do ffmpeg, que o VoiceStudio não conseguiu encontrar ou executar. Abra Configurações → Ferramentas de áudio e use Baixar/Reparar, ou instale o ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: seu gerenciador de pacotes) e reinicie o VoiceStudio. Você também pode apontar FFMPEG_PATH para um binário do ffmpeg.",- "transcription_pipe_lost": "O backend perdeu o canal de saída para o aplicativo durante a transcrição (broken pipe). Reinicie o VoiceStudio e tente novamente."+ "transcription_pipe_lost": "O backend perdeu o canal de saída para o aplicativo durante a transcrição (broken pipe). Reinicie o VoiceStudio e tente novamente.",+ "gpu_oom": "A GPU ficou sem memória. Feche outros apps que usam muito a GPU ou descarregue modelos e tente novamente. Você também pode escolher CPU em Configurações → Desempenho e dispositivo ou selecionar um mecanismo TTS menor.",+ "host_memory_exhausted": "O computador ficou sem memória. Feche outros apps e abas do navegador que usam muita memória, descarregue modelos que não usa, gere um trecho mais curto ou escolha um mecanismo TTS mais leve.",+ "engine_dependency_missing": "Um pacote Python de que este mecanismo precisa não está instalado, então ele não pôde iniciar. Abra o Catálogo de modelos, selecione o mecanismo e use Instalar / Reparar; depois reinicie o VoiceStudio.",+ "reference_stt_missing": "Esta voz não tem transcrição e nenhum modelo de fala para texto está instalado para criá-la. Digite o que o clipe de referência diz na caixa de transcrição (clipes de até 20 segundos) ou instale um modelo de fala para texto no Catálogo de modelos, selecione-o e gere novamente.",+ "proxy_gateway_error": "Um proxy ou gateway entre você e o VoiceStudio respondeu HTTP {{status}} no lugar do backend. O backend pode ainda estar trabalhando. Aumente o tempo limite de leitura do proxy (no nginx, proxy_read_timeout) para gerações longas e depois confira Configurações → Logs → Backend.",+ "route_not_found": "O backend do VoiceStudio em execução não tem o endpoint {{route}}. Reinicie o VoiceStudio para que o app e o backend coincidam; se persistir, atualize ambos para a mesma versão."},"network": {"copied": "Copiado",diff --git a/electron/src/renderer/src/i18n/locales/ru.json b/electron/src/renderer/src/i18n/locales/ru.jsonindex dde141501..b167c5928 100644--- a/electron/src/renderer/src/i18n/locales/ru.json+++ b/electron/src/renderer/src/i18n/locales/ru.json@@ -2821,7 +2821,13 @@"audio_io_failed": "Не удалось прочитать или сохранить аудио. Проверьте формат файла, свободное место на диске и права доступа. Проверьте папку в Настройки → Хранилище.","no_audio_track": "В этом файле нет звуковой дорожки, поэтому нечего расшифровывать, дублировать или клонировать. Выберите видео- или аудиофайл со звуком.","transcription_media_tool": "Для расшифровки нужен ffmpeg, который VoiceStudio не удалось найти или запустить. Откройте Настройки → Аудиоинструменты и нажмите Загрузить/Восстановить либо установите ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: ваш пакетный менеджер) и перезапустите VoiceStudio. Также можно указать в FFMPEG_PATH путь к ffmpeg.",- "transcription_pipe_lost": "Во время расшифровки бэкенд потерял канал вывода к приложению (broken pipe). Перезапустите VoiceStudio и повторите попытку."+ "transcription_pipe_lost": "Во время расшифровки бэкенд потерял канал вывода к приложению (broken pipe). Перезапустите VoiceStudio и повторите попытку.",+ "gpu_oom": "У GPU закончилась память. Закройте другие приложения, активно использующие GPU, или выгрузите модели и повторите попытку. Также можно выбрать CPU в Настройки → Производительность и устройство или выбрать движок TTS поменьше.",+ "host_memory_exhausted": "На компьютере закончилась память. Закройте другие приложения и вкладки браузера, потребляющие много памяти, выгрузите неиспользуемые модели, сгенерируйте более короткий фрагмент или выберите более лёгкий движок TTS.",+ "engine_dependency_missing": "Не установлен пакет Python, необходимый этому движку, поэтому он не смог запуститься. Откройте Каталог моделей, выберите движок и нажмите «Установить / Восстановить», затем перезапустите VoiceStudio.",+ "reference_stt_missing": "У этого голоса нет расшифровки, и не установлена модель распознавания речи, чтобы её создать. Введите в поле расшифровки то, что говорится в эталонном клипе (клипы до 20 секунд), или установите модель распознавания речи в Каталоге моделей, выберите её и сгенерируйте снова.",+ "proxy_gateway_error": "Прокси или шлюз между вами и VoiceStudio ответил HTTP {{status}} вместо бэкенда. Бэкенд, возможно, всё ещё работает. Увеличьте тайм-аут чтения прокси (в nginx — proxy_read_timeout) для долгих генераций, затем проверьте Настройки → Журналы → Бэкенд.",+ "route_not_found": "У запущенного бэкенда VoiceStudio нет эндпоинта {{route}}. Перезапустите VoiceStudio, чтобы приложение и бэкенд совпали; если проблема не исчезнет, обновите оба до одной версии."},"network": {"copied": "Скопировано",diff --git a/electron/src/renderer/src/i18n/locales/sv.json b/electron/src/renderer/src/i18n/locales/sv.jsonindex 25efc2956..f7249da89 100644--- a/electron/src/renderer/src/i18n/locales/sv.json+++ b/electron/src/renderer/src/i18n/locales/sv.json@@ -2817,7 +2817,13 @@"audio_io_failed": "Ljudet kunde inte läsas eller sparas. Kontrollera filformat, ledigt diskutrymme och filbehörigheter. Kontrollera mappen under Inställningar → Lagring.","no_audio_track": "Filen saknar ljudspår, så det finns inget tal att transkribera, dubba eller klona. Välj en video- eller ljudfil som innehåller ljud.","transcription_media_tool": "Transkribering kräver ffmpeg, som VoiceStudio inte kunde hitta eller köra. Öppna Inställningar → Ljudverktyg och använd Ladda ned/Reparera, eller installera ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: din pakethanterare) och starta om VoiceStudio. Du kan också peka FFMPEG_PATH mot en ffmpeg-fil.",- "transcription_pipe_lost": "Backend förlorade sin utdatakanal till appen under transkriberingen (broken pipe). Starta om VoiceStudio och försök igen."+ "transcription_pipe_lost": "Backend förlorade sin utdatakanal till appen under transkriberingen (broken pipe). Starta om VoiceStudio och försök igen.",+ "gpu_oom": "GPU:n fick slut på minne. Stäng andra GPU-tunga appar eller avlasta modeller och försök igen. Du kan också välja CPU under Inställningar → Prestanda och enhet eller välja en mindre TTS-motor.",+ "host_memory_exhausted": "Datorn fick slut på minne. Stäng andra minnestunga appar och webbläsarflikar, avlasta modeller du inte använder, generera ett kortare stycke eller välj en lättare TTS-motor.",+ "engine_dependency_missing": "Ett Python-paket som den här motorn behöver är inte installerat, så motorn kunde inte starta. Öppna Modellkatalogen, välj motorn och använd Installera / Reparera och starta sedan om VoiceStudio.",+ "reference_stt_missing": "Rösten saknar transkription och ingen tal-till-text-modell är installerad för att skapa en. Skriv in vad referensklippet säger i transkriptionsrutan (klipp upp till 20 sekunder) eller installera en tal-till-text-modell i Modellkatalogen, välj den och generera igen.",+ "proxy_gateway_error": "En proxy eller gateway mellan dig och VoiceStudio svarade HTTP {{status}} i stället för backend. Backend kanske fortfarande arbetar. Höj proxyns läs-timeout (i nginx proxy_read_timeout) för långa genereringar och kontrollera sedan Inställningar → Loggar → Backend.",+ "route_not_found": "Den körande VoiceStudio-backenden har ingen {{route}}-ändpunkt. Starta om VoiceStudio så att appen och backend matchar; om det kvarstår, uppdatera båda till samma version."},"network": {"copied": "Kopierade",diff --git a/electron/src/renderer/src/i18n/locales/th.json b/electron/src/renderer/src/i18n/locales/th.jsonindex a1daaace6..72cf17aba 100644--- a/electron/src/renderer/src/i18n/locales/th.json+++ b/electron/src/renderer/src/i18n/locales/th.json@@ -2817,7 +2817,13 @@"audio_io_failed": "ไม่สามารถอ่านหรือบันทึกเสียงได้ ตรวจสอบรูปแบบไฟล์ พื้นที่ดิสก์ว่าง และสิทธิ์เข้าถึงไฟล์ ตรวจสอบโฟลเดอร์ในการตั้งค่า → ที่เก็บข้อมูล","no_audio_track": "ไฟล์นี้ไม่มีแทร็กเสียง จึงไม่มีเสียงพูดให้ถอดความ พากย์ หรือโคลน เลือกไฟล์วิดีโอหรือไฟล์เสียงที่มีเสียง","transcription_media_tool": "การถอดความต้องใช้ ffmpeg แต่ VoiceStudio หาหรือเรียกใช้ไม่ได้ เปิดการตั้งค่า → เครื่องมือเสียง แล้วใช้ดาวน์โหลด/ซ่อมแซม หรือติดตั้ง ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: ตัวจัดการแพ็กเกจของคุณ) แล้วรีสตาร์ท VoiceStudio หรือจะชี้ FFMPEG_PATH ไปยังไฟล์ ffmpeg ก็ได้",- "transcription_pipe_lost": "แบ็กเอนด์สูญเสียช่องทางส่งออกไปยังแอประหว่างการถอดความ (broken pipe) โปรดรีสตาร์ท VoiceStudio แล้วลองอีกครั้ง"+ "transcription_pipe_lost": "แบ็กเอนด์สูญเสียช่องทางส่งออกไปยังแอประหว่างการถอดความ (broken pipe) โปรดรีสตาร์ท VoiceStudio แล้วลองอีกครั้ง",+ "gpu_oom": "หน่วยความจำ GPU หมด ปิดแอปอื่นที่ใช้ GPU หนักหรือยกเลิกการโหลดโมเดล แล้วลองอีกครั้ง คุณยังเลือก CPU ได้ที่ การตั้งค่า → ประสิทธิภาพและอุปกรณ์ หรือเลือกเอนจิน TTS ที่เล็กลง",+ "host_memory_exhausted": "หน่วยความจำของคอมพิวเตอร์หมด ปิดแอปและแท็บเบราว์เซอร์อื่นที่ใช้หน่วยความจำมาก ยกเลิกการโหลดโมเดลที่ไม่ได้ใช้ สร้างข้อความให้สั้นลง หรือเลือกเอนจิน TTS ที่เบากว่า",+ "engine_dependency_missing": "ยังไม่ได้ติดตั้งแพ็กเกจ Python ที่เอนจินนี้ต้องใช้ เอนจินจึงเริ่มทำงานไม่ได้ เปิดแค็ตตาล็อกโมเดล เลือกเอนจินแล้วใช้ ติดตั้ง / ซ่อมแซม จากนั้นรีสตาร์ต VoiceStudio",+ "reference_stt_missing": "เสียงนี้ไม่มีข้อความถอดเสียง และไม่ได้ติดตั้งโมเดลแปลงเสียงเป็นข้อความเพื่อสร้างให้ พิมพ์สิ่งที่คลิปอ้างอิงพูดลงในช่องข้อความถอดเสียง (คลิปยาวไม่เกิน 20 วินาที) หรือติดตั้งโมเดลแปลงเสียงเป็นข้อความในแค็ตตาล็อกโมเดล เลือกใช้ แล้วสร้างอีกครั้ง",+ "proxy_gateway_error": "พร็อกซีหรือเกตเวย์ระหว่างคุณกับ VoiceStudio ตอบกลับ HTTP {{status}} แทนแบ็กเอนด์ แบ็กเอนด์อาจยังทำงานอยู่ ให้เพิ่มเวลารอการอ่านของพร็อกซี (ใน nginx คือ proxy_read_timeout) สำหรับการสร้างที่ยาว แล้วตรวจสอบ การตั้งค่า → บันทึก → แบ็กเอนด์",+ "route_not_found": "แบ็กเอนด์ VoiceStudio ที่กำลังทำงานไม่มีเอนด์พอยต์ {{route}} ให้รีสตาร์ต VoiceStudio เพื่อให้แอปและแบ็กเอนด์ตรงกัน หากยังเป็นอยู่ ให้อัปเดตทั้งสองเป็นเวอร์ชันเดียวกัน"},"network": {"copied": "คัดลอกแล้ว",diff --git a/electron/src/renderer/src/i18n/locales/tr.json b/electron/src/renderer/src/i18n/locales/tr.jsonindex 1a11776d0..2d629d954 100644--- a/electron/src/renderer/src/i18n/locales/tr.json+++ b/electron/src/renderer/src/i18n/locales/tr.json@@ -2817,7 +2817,13 @@"audio_io_failed": "Ses okunamadı veya kaydedilemedi. Dosya biçimini, boş disk alanını ve dosya izinlerini kontrol edin. Ayarlar → Depolama bölümündeki klasörü inceleyin.","no_audio_track": "Bu dosyada ses parçası yok, bu yüzden yazıya dökülecek, dublajlanacak veya klonlanacak konuşma yok. Ses içeren bir video veya ses dosyası seçin.","transcription_media_tool": "Yazıya dökme için ffmpeg gerekir, ancak VoiceStudio onu bulamadı veya çalıştıramadı. Ayarlar → Ses araçları bölümünü açıp İndir/Onar'ı kullanın ya da ffmpeg'i kurun (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: paket yöneticiniz) ve VoiceStudio'yu yeniden başlatın. FFMPEG_PATH değişkenini bir ffmpeg dosyasına da yönlendirebilirsiniz.",- "transcription_pipe_lost": "Arka uç, yazıya dökme sırasında uygulamaya giden çıkış kanalını kaybetti (broken pipe). VoiceStudio'yu yeniden başlatıp tekrar deneyin."+ "transcription_pipe_lost": "Arka uç, yazıya dökme sırasında uygulamaya giden çıkış kanalını kaybetti (broken pipe). VoiceStudio'yu yeniden başlatıp tekrar deneyin.",+ "gpu_oom": "GPU belleği tükendi. GPU'yu çok kullanan diğer uygulamaları kapatın veya modelleri boşaltın, sonra tekrar deneyin. Ayarlar → Performans ve Aygıt bölümünden CPU'yu seçebilir veya daha küçük bir TTS motoru seçebilirsiniz.",+ "host_memory_exhausted": "Bilgisayarın belleği tükendi. Belleği çok kullanan diğer uygulamaları ve tarayıcı sekmelerini kapatın, kullanmadığınız modelleri boşaltın, daha kısa bir bölüm üretin veya daha hafif bir TTS motoru seçin.",+ "engine_dependency_missing": "Bu motorun ihtiyaç duyduğu bir Python paketi yüklü değil, bu yüzden motor başlatılamadı. Model Kataloğu'nu açın, motoru seçin ve Yükle / Onar'ı kullanın, ardından VoiceStudio'yu yeniden başlatın.",+ "reference_stt_missing": "Bu sesin deşifresi yok ve bir tane oluşturacak konuşmadan metne modeli yüklü değil. Referans klibin söylediğini deşifre kutusuna yazın (en fazla 20 saniyelik klipler) veya Model Kataloğu'ndan bir konuşmadan metne modeli yükleyip seçin ve yeniden üretin.",+ "proxy_gateway_error": "Sizinle VoiceStudio arasındaki bir proxy veya ağ geçidi, arka uç yerine HTTP {{status}} yanıtı verdi. Arka uç hâlâ çalışıyor olabilir. Uzun üretimler için proxy'nin okuma zaman aşımını artırın (nginx'te proxy_read_timeout), ardından Ayarlar → Günlükler → Arka uç bölümüne bakın.",+ "route_not_found": "Çalışan VoiceStudio arka ucunda {{route}} uç noktası yok. Uygulama ile arka ucun eşleşmesi için VoiceStudio'yu yeniden başlatın; sorun sürerse ikisini de aynı sürüme güncelleyin."},"network": {"copied": "Kopyalandı",diff --git a/electron/src/renderer/src/i18n/locales/uk.json b/electron/src/renderer/src/i18n/locales/uk.jsonindex 38156c48a..0ea5f516f 100644--- a/electron/src/renderer/src/i18n/locales/uk.json+++ b/electron/src/renderer/src/i18n/locales/uk.json@@ -2821,7 +2821,13 @@"audio_io_failed": "Не вдалося прочитати або зберегти аудіо. Перевірте формат файлу, вільне місце на диску та права доступу. Перевірте папку в Налаштування → Сховище.","no_audio_track": "У цьому файлі немає звукової доріжки, тож нічого розшифровувати, дублювати чи клонувати. Виберіть відео- або аудіофайл зі звуком.","transcription_media_tool": "Для розшифрування потрібен ffmpeg, який VoiceStudio не вдалося знайти або запустити. Відкрийте Налаштування → Аудіоінструменти й натисніть Завантажити/Відновити або встановіть ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: ваш менеджер пакетів) і перезапустіть VoiceStudio. Також можна вказати в FFMPEG_PATH шлях до ffmpeg.",- "transcription_pipe_lost": "Під час розшифрування бекенд втратив канал виводу до застосунку (broken pipe). Перезапустіть VoiceStudio і спробуйте ще раз."+ "transcription_pipe_lost": "Під час розшифрування бекенд втратив канал виводу до застосунку (broken pipe). Перезапустіть VoiceStudio і спробуйте ще раз.",+ "gpu_oom": "У GPU закінчилася пам'ять. Закрийте інші програми, що активно використовують GPU, або вивантажте моделі й повторіть спробу. Також можна вибрати CPU в Налаштування → Продуктивність і пристрій або менший рушій TTS.",+ "host_memory_exhausted": "На комп'ютері закінчилася пам'ять. Закрийте інші програми й вкладки браузера, що споживають багато пам'яті, вивантажте непотрібні моделі, згенеруйте коротший фрагмент або виберіть легший рушій TTS.",+ "engine_dependency_missing": "Не встановлено пакет Python, потрібний цьому рушію, тому він не зміг запуститися. Відкрийте Каталог моделей, виберіть рушій і натисніть «Установити / Відновити», потім перезапустіть VoiceStudio.",+ "reference_stt_missing": "Цей голос не має розшифровки, і не встановлено модель розпізнавання мовлення, щоб її створити. Введіть у поле розшифровки те, що звучить в еталонному кліпі (кліпи до 20 секунд), або встановіть модель розпізнавання мовлення в Каталозі моделей, виберіть її та згенеруйте знову.",+ "proxy_gateway_error": "Проксі або шлюз між вами та VoiceStudio відповів HTTP {{status}} замість бекенда. Бекенд, імовірно, ще працює. Збільште тайм-аут читання проксі (в nginx — proxy_read_timeout) для довгих генерацій, потім перевірте Налаштування → Журнали → Бекенд.",+ "route_not_found": "У запущеного бекенда VoiceStudio немає кінцевої точки {{route}}. Перезапустіть VoiceStudio, щоб застосунок і бекенд збіглися; якщо проблема не зникне, оновіть обидва до однієї версії."},"network": {"copied": "Скопійовано",diff --git a/electron/src/renderer/src/i18n/locales/vi.json b/electron/src/renderer/src/i18n/locales/vi.jsonindex c4836bb46..135829a94 100644--- a/electron/src/renderer/src/i18n/locales/vi.json+++ b/electron/src/renderer/src/i18n/locales/vi.json@@ -2817,7 +2817,13 @@"audio_io_failed": "Không thể đọc hoặc lưu âm thanh. Kiểm tra định dạng tệp, dung lượng đĩa trống và quyền truy cập tệp. Kiểm tra thư mục trong Cài đặt → Lưu trữ.","no_audio_track": "Tệp này không có rãnh âm thanh nên không có lời nói để chép lời, lồng tiếng hoặc nhân bản. Hãy chọn tệp video hoặc âm thanh có tiếng.","transcription_media_tool": "Chép lời cần ffmpeg, nhưng VoiceStudio không thể tìm thấy hoặc chạy nó. Mở Cài đặt → Công cụ âm thanh và dùng Tải xuống/Sửa chữa, hoặc cài ffmpeg (macOS: brew install ffmpeg; Windows: winget install Gyan.FFmpeg; Linux: trình quản lý gói của bạn) rồi khởi động lại VoiceStudio. Bạn cũng có thể trỏ FFMPEG_PATH tới tệp ffmpeg.",- "transcription_pipe_lost": "Backend đã mất kênh đầu ra tới ứng dụng khi đang chép lời (broken pipe). Hãy khởi động lại VoiceStudio và thử lại."+ "transcription_pipe_lost": "Backend đã mất kênh đầu ra tới ứng dụng khi đang chép lời (broken pipe). Hãy khởi động lại VoiceStudio và thử lại.",+ "gpu_oom": "GPU đã hết bộ nhớ. Hãy đóng các ứng dụng khác dùng nhiều GPU hoặc gỡ mô hình khỏi bộ nhớ rồi thử lại. Bạn cũng có thể chọn CPU trong Cài đặt → Hiệu năng & Thiết bị hoặc chọn công cụ TTS nhỏ hơn.",+ "host_memory_exhausted": "Máy tính đã hết bộ nhớ. Hãy đóng các ứng dụng và thẻ trình duyệt khác dùng nhiều bộ nhớ, gỡ các mô hình không dùng, tạo đoạn ngắn hơn hoặc chọn công cụ TTS nhẹ hơn.",+ "engine_dependency_missing": "Một gói Python mà công cụ này cần chưa được cài đặt nên công cụ không thể khởi động. Hãy mở Danh mục mô hình, chọn công cụ và dùng Cài đặt / Sửa chữa, rồi khởi động lại VoiceStudio.",+ "reference_stt_missing": "Giọng này không có bản chép lời và chưa cài mô hình chuyển giọng nói thành văn bản để tạo bản chép. Hãy nhập nội dung đoạn âm thanh tham chiếu vào ô bản chép lời (đoạn tối đa 20 giây), hoặc cài mô hình chuyển giọng nói thành văn bản trong Danh mục mô hình, chọn nó rồi tạo lại.",+ "proxy_gateway_error": "Một proxy hoặc cổng giữa bạn và VoiceStudio đã trả lời HTTP {{status}} thay cho backend. Backend có thể vẫn đang xử lý. Hãy tăng thời gian chờ đọc của proxy (với nginx là proxy_read_timeout) cho các lần tạo dài, rồi kiểm tra Cài đặt → Nhật ký → Backend.",+ "route_not_found": "Backend VoiceStudio đang chạy không có điểm cuối {{route}}. Hãy khởi động lại VoiceStudio để ứng dụng và backend khớp nhau; nếu vẫn lỗi, hãy cập nhật cả hai lên cùng một phiên bản."},"network": {"copied": "Đã sao chép",diff --git a/electron/src/renderer/src/i18n/locales/zh-CN.json b/electron/src/renderer/src/i18n/locales/zh-CN.jsonindex 3e13b66f8..8655d59eb 100644--- a/electron/src/renderer/src/i18n/locales/zh-CN.json+++ b/electron/src/renderer/src/i18n/locales/zh-CN.json@@ -2817,7 +2817,13 @@"audio_io_failed": "无法读取或保存音频。请检查文件格式、磁盘剩余空间和文件访问权限,并在设置 → 存储中检查文件夹。","no_audio_track": "此文件没有音轨,因此没有可转录、配音或克隆的语音。请选择包含声音的视频或音频文件。","transcription_media_tool": "转录需要 ffmpeg,但 VoiceStudio 无法找到或运行它。请打开设置 → 音频工具并使用下载/修复,或安装 ffmpeg(macOS:brew install ffmpeg;Windows:winget install Gyan.FFmpeg;Linux:你的包管理器),然后重启 VoiceStudio。你也可以将 FFMPEG_PATH 指向 ffmpeg 可执行文件。",- "transcription_pipe_lost": "转录期间后端丢失了通往应用的输出管道(broken pipe)。请重启 VoiceStudio 后重试。"+ "transcription_pipe_lost": "转录期间后端丢失了通往应用的输出管道(broken pipe)。请重启 VoiceStudio 后重试。",+ "gpu_oom": "GPU 显存不足。请关闭其他占用 GPU 的应用或卸载模型后重试。你也可以在 设置 → 性能与设备 中选择 CPU,或选择更小的 TTS 引擎。",+ "host_memory_exhausted": "电脑内存不足。请关闭其他占用内存的应用和浏览器标签页,卸载不用的模型,生成较短的片段,或选择更轻量的 TTS 引擎。",+ "engine_dependency_missing": "此引擎所需的 Python 包未安装,因此引擎无法启动。请打开模型目录,选择该引擎并使用 安装 / 修复,然后重启 VoiceStudio。",+ "reference_stt_missing": "此声音没有文字稿,也没有安装可用于生成文字稿的语音转文字模型。请在文字稿框中输入参考音频所说的内容(音频不超过 20 秒),或在模型目录中安装并选择一个语音转文字模型,然后重新生成。",+ "proxy_gateway_error": "你与 VoiceStudio 之间的代理或网关返回了 HTTP {{status}},而不是后端的响应。后端可能仍在处理。对于较长的生成,请调大代理的读取超时(nginx 为 proxy_read_timeout),然后查看 设置 → 日志 → 后端。",+ "route_not_found": "正在运行的 VoiceStudio 后端没有 {{route}} 接口。请重启 VoiceStudio 使应用与后端一致;若仍然如此,请将两者更新到同一版本。"},"network": {"copied": "已复制",diff --git a/electron/src/renderer/src/i18n/locales/zh-TW.json b/electron/src/renderer/src/i18n/locales/zh-TW.jsonindex 6d6927fc8..a2fa3b874 100644--- a/electron/src/renderer/src/i18n/locales/zh-TW.json+++ b/electron/src/renderer/src/i18n/locales/zh-TW.json@@ -2817,7 +2817,13 @@"audio_io_failed": "無法讀取或儲存音訊。請檢查檔案格式、磁碟可用空間和檔案存取權限,並在設定 → 儲存空間中檢查資料夾。","no_audio_track": "此檔案沒有音軌,因此沒有可轉錄、配音或複製的語音。請選擇包含聲音的影片或音訊檔案。","transcription_media_tool": "轉錄需要 ffmpeg,但 VoiceStudio 找不到或無法執行它。請開啟設定 → 音訊工具並使用下載/修復,或安裝 ffmpeg(macOS:brew install ffmpeg;Windows:winget install Gyan.FFmpeg;Linux:你的套件管理員),然後重新啟動 VoiceStudio。你也可以將 FFMPEG_PATH 指向 ffmpeg 執行檔。",- "transcription_pipe_lost": "轉錄期間後端失去了通往應用程式的輸出管道(broken pipe)。請重新啟動 VoiceStudio 後再試一次。"+ "transcription_pipe_lost": "轉錄期間後端失去了通往應用程式的輸出管道(broken pipe)。請重新啟動 VoiceStudio 後再試一次。",+ "gpu_oom": "GPU 記憶體不足。請關閉其他佔用 GPU 的應用程式或卸載模型後重試。你也可以在 設定 → 效能與裝置 中選擇 CPU,或選擇較小的 TTS 引擎。",+ "host_memory_exhausted": "電腦記憶體不足。請關閉其他佔用記憶體的應用程式和瀏覽器分頁,卸載不用的模型,產生較短的片段,或選擇更輕量的 TTS 引擎。",+ "engine_dependency_missing": "此引擎所需的 Python 套件尚未安裝,因此引擎無法啟動。請開啟模型目錄,選擇該引擎並使用 安裝 / 修復,然後重新啟動 VoiceStudio。",+ "reference_stt_missing": "此聲音沒有逐字稿,也沒有安裝可用於產生逐字稿的語音轉文字模型。請在逐字稿欄位輸入參考音訊所說的內容(音訊不超過 20 秒),或在模型目錄中安裝並選擇一個語音轉文字模型,然後重新產生。",+ "proxy_gateway_error": "你與 VoiceStudio 之間的代理或閘道回傳了 HTTP {{status}},而不是後端的回應。後端可能仍在處理。對於較長的產生作業,請調高代理的讀取逾時(nginx 為 proxy_read_timeout),然後查看 設定 → 記錄 → 後端。",+ "route_not_found": "正在執行的 VoiceStudio 後端沒有 {{route}} 端點。請重新啟動 VoiceStudio 使應用程式與後端一致;若仍然如此,請將兩者更新到同一版本。"},"network": {"copied": "已複製",diff --git a/electron/src/renderer/src/lib/api/client.test.ts b/electron/src/renderer/src/lib/api/client.test.tsindex bf150ce18..0f2991740 100644--- a/electron/src/renderer/src/lib/api/client.test.ts+++ b/electron/src/renderer/src/lib/api/client.test.ts@@ -1,6 +1,9 @@-import i18next from 'i18next';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { _resetBackendContactForTests, lastBackendContact } from '@shared/utils/backendContact';+import i18next from "i18next";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ _resetBackendContactForTests,+ lastBackendContact,+} from "@shared/utils/backendContact";import {ApiError,apiFetch,@@ -12,8 +15,8 @@ import {profileAudioUrl,resolveApiBase,joinApiPath,-} from './client';-import { rewriteDevApiProxyPath } from '../../../../shared/web-api-routing';+} from "./client";+import { rewriteDevApiProxyPath } from "../../../../shared/web-api-routing";beforeEach(() => {_resetBackendContactForTests();@@ -25,291 +28,415 @@ afterEach(() => {_resetBackendContactForTests();});-describe('errorFromResponse', () => {- it('localizes Argos runtime errors and retains diagnostics', async () => {- const translate = vi.spyOn(i18next, 't').mockReturnValue('Localized recovery guidance');- const detail = { code: 'argos_runtime_unavailable', message: 'Raw native diagnostic' };- const err = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 400 }));- expect(err.detail).toBe('Localized recovery guidance');- expect(translate).toHaveBeenCalledWith('engines.argosRuntimeUnavailable');+describe("errorFromResponse", () => {+ it("localizes Argos runtime errors and retains diagnostics", async () => {+ const translate = vi+ .spyOn(i18next, "t")+ .mockReturnValue("Localized recovery guidance");+ const detail = {+ code: "argos_runtime_unavailable",+ message: "Raw native diagnostic",+ };+ const err = await errorFromResponse(+ new Response(JSON.stringify({ detail }), { status: 400 }),+ );+ expect(err.detail).toBe("Localized recovery guidance");+ expect(translate).toHaveBeenCalledWith("engines.argosRuntimeUnavailable");expect(err.payload?.detail).toEqual(detail);});- it('announces unaccepted model licences so the app can ask for acceptance', async () => {- const translate = vi.spyOn(i18next, 't').mockReturnValue('Accept the licence first');+ it("announces unaccepted model licences so the app can ask for acceptance", async () => {+ const translate = vi+ .spyOn(i18next, "t")+ .mockReturnValue("Accept the licence first");const models = [- { repo_id: 'a/b', category: 'noncommercial', fingerprint: `v1:${'a'.repeat(64)}` },+ {+ repo_id: "a/b",+ category: "noncommercial",+ fingerprint: `v1:${"a".repeat(64)}`,+ },];- const detail = { code: 'model_licence_required', message: 'raw', models };+ const detail = { code: "model_licence_required", message: "raw", models };const seen: unknown[] = [];const listener = (event: Event) => seen.push((event as CustomEvent).detail);- window.addEventListener('ov:model-licence-required', listener);+ window.addEventListener("ov:model-licence-required", listener);try {const err = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 403 }),);- expect(err.detail).toBe('Accept the licence first');- expect(translate).toHaveBeenCalledWith('modelLicense.requiredError');+ expect(err.detail).toBe("Accept the licence first");+ expect(translate).toHaveBeenCalledWith("modelLicense.requiredError");expect(seen).toEqual([models]);} finally {- window.removeEventListener('ov:model-licence-required', listener);+ window.removeEventListener("ov:model-licence-required", listener);}});- it('localizes background preservation errors and retains diagnostics', async () => {- const detail = { code: 'dub_background_unavailable', message: 'Raw diagnostic' };- const err = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 409 }));- expect(err.detail).not.toBe('Raw diagnostic');- expect(err.detail).not.toContain('Raw diagnostic');+ it("localizes background preservation errors and retains diagnostics", async () => {+ const detail = {+ code: "dub_background_unavailable",+ message: "Raw diagnostic",+ };+ const err = await errorFromResponse(+ new Response(JSON.stringify({ detail }), { status: 409 }),+ );+ expect(err.detail).not.toBe("Raw diagnostic");+ expect(err.detail).not.toContain("Raw diagnostic");expect(err.payload?.detail).toEqual(detail);});- it('uses a string detail verbatim and keeps the payload', async () => {- const res = new Response(JSON.stringify({ detail: 'Unsupported instruct items' }), {- status: 400,- });+ it("uses a string detail verbatim and keeps the payload", async () => {+ const res = new Response(+ JSON.stringify({ detail: "Unsupported instruct items" }),+ {+ status: 400,+ },+ );const err = await errorFromResponse(res);expect(err).toBeInstanceOf(ApiError);expect(err.status).toBe(400);- expect(err.detail).toBe('Unsupported instruct items');- expect(err.message).toBe('Unsupported instruct items');- expect(err.payload).toEqual({ detail: 'Unsupported instruct items' });+ expect(err.detail).toBe("Unsupported instruct items");+ expect(err.message).toBe("Unsupported instruct items");+ expect(err.payload).toEqual({ detail: "Unsupported instruct items" });});- it('compact-stringifies a structured detail', async () => {- const detail = { error: 'model_not_downloaded', repo_ids: ['a/b'] };+ it("compact-stringifies a structured detail", async () => {+ const detail = { error: "model_not_downloaded", repo_ids: ["a/b"] };const res = new Response(JSON.stringify({ detail }), { status: 409 });const err = await errorFromResponse(res);expect(err.detail).toBe(JSON.stringify(detail));expect(err.payload?.detail).toEqual(detail);});- it('falls back to the text body when it is not JSON', async () => {- const res = new Response('Internal Server Error', { status: 500 });+ it("falls back to the text body when it is not JSON", async () => {+ const res = new Response("Internal Server Error", { status: 500 });const err = await errorFromResponse(res);- expect(err.detail).toBe('Internal Server Error');+ expect(err.detail).toBe("Internal Server Error");expect(err.payload).toBeNull();});- it('falls back to the status line on an empty body', async () => {- const res = new Response(null, { status: 502, statusText: 'Bad Gateway' });+ it("falls back to the status line on an empty body", async () => {+ const res = new Response(null, { status: 502, statusText: "Bad Gateway" });const err = await errorFromResponse(res);- expect(err.detail).toBe('HTTP 502 Bad Gateway');+ expect(err.detail).toBe("HTTP 502 Bad Gateway");});});-describe('apiFetch', () => {- it('prefixes API_BASE and returns the response when ok', async () => {- const fetchMock = vi.fn(async () => new Response('{"ok":true}', { status: 200 }));- vi.stubGlobal('fetch', fetchMock);- const body = await apiJson<{ ok: boolean }>('/system/info');+describe("apiFetch", () => {+ it("prefixes API_BASE and returns the response when ok", async () => {+ const fetchMock = vi.fn(+ async () => new Response('{"ok":true}', { status: 200 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const body = await apiJson<{ ok: boolean }>("/system/info");expect(body).toEqual({ ok: true });- expect(fetchMock).toHaveBeenCalledWith('/api/system/info', undefined);+ expect(fetchMock).toHaveBeenCalledWith("/api/system/info", undefined);expect(lastBackendContact()).not.toBeNull();});- it('throws ApiError for a non-2xx response', async () => {- vi.stubGlobal('fetch', async () => new Response('{"detail":"nope"}', { status: 404 }));- await expect(apiFetch('/profiles/x')).rejects.toMatchObject({- name: 'ApiError',+ it("throws ApiError for a non-2xx response", async () => {+ vi.stubGlobal(+ "fetch",+ async () => new Response('{"detail":"nope"}', { status: 404 }),+ );+ await expect(apiFetch("/profiles/x")).rejects.toMatchObject({+ name: "ApiError",status: 404,- detail: 'nope',+ detail: "nope",});expect(lastBackendContact()).not.toBeNull();});- it('maps a network failure to status 0 with the backend_unreachable key', async () => {- vi.stubGlobal('fetch', async () => {- throw new TypeError('Failed to fetch');+ it("maps a network failure to status 0 with the backend_unreachable key", async () => {+ vi.stubGlobal("fetch", async () => {+ throw new TypeError("Failed to fetch");});- await expect(apiFetch('/engines')).rejects.toMatchObject({- name: 'ApiError',+ await expect(apiFetch("/engines")).rejects.toMatchObject({+ name: "ApiError",status: 0,- detail: 'tts_errors.backend_unreachable',+ detail: "tts_errors.backend_unreachable",});expect(lastBackendContact()).toBeNull();});- it('re-throws aborts untouched', async () => {- vi.stubGlobal('fetch', async () => {- throw new DOMException('Aborted', 'AbortError');+ it("re-throws aborts untouched", async () => {+ vi.stubGlobal("fetch", async () => {+ throw new DOMException("Aborted", "AbortError");+ });+ await expect(apiFetch("/generate")).rejects.toMatchObject({+ name: "AbortError",});- await expect(apiFetch('/generate')).rejects.toMatchObject({ name: 'AbortError' });});});-describe('url helpers', () => {- it('builds same-origin audio URLs', () => {- expect(audioUrl('take 1.wav')).toBe('/api/audio/take%201.wav');- expect(profileAudioUrl('abc')).toBe('/api/profiles/abc/audio');- expect(profileAudioUrl('abc', null)).toBe('/api/profiles/abc/audio');+describe("url helpers", () => {+ it("builds same-origin audio URLs", () => {+ expect(audioUrl("take 1.wav")).toBe("/api/audio/take%201.wav");+ expect(profileAudioUrl("abc")).toBe("/api/profiles/abc/audio");+ expect(profileAudioUrl("abc", null)).toBe("/api/profiles/abc/audio");// The versioned URL changes when the reference is replaced (#2282).- expect(profileAudioUrl('abc', '/profiles/abc/audio?v=42')).toBe('/api/profiles/abc/audio?v=42');+ expect(profileAudioUrl("abc", "/profiles/abc/audio?v=42")).toBe(+ "/api/profiles/abc/audio?v=42",+ );});- it('describes errors for toasts', () => {- expect(describeError(new ApiError(500, 'boom'))).toBe('boom');- expect(describeError(new Error('plain'))).toBe('plain');- expect(describeError('str')).toBe('str');+ it("describes errors for toasts", () => {+ expect(describeError(new ApiError(500, "boom"))).toBe("boom");+ expect(describeError(new Error("plain"))).toBe("plain");+ expect(describeError("str")).toBe("str");});});-describe('deployment API base', () => {- it('keeps Electron and web development on the /api proxy', () => {- expect(resolveApiBase(false, false)).toBe('/api');- expect(resolveApiBase(true, true)).toBe('/api');+describe("deployment API base", () => {+ it("keeps Electron and web development on the /api proxy", () => {+ expect(resolveApiBase(false, false)).toBe("/api");+ expect(resolveApiBase(true, true)).toBe("/api");});- it('uses backend-root routes in the production web bundle', () => {- expect(resolveApiBase(true, false)).toBe('');+ it("uses backend-root routes in the production web bundle", () => {+ expect(resolveApiBase(true, false)).toBe("");});- it('honors the runtime Docker/reverse-proxy override', () => {- const win = { __OMNIVOICE_API_BASE__: 'https://voice.example/studio/' } as Window & {+ it("honors the runtime Docker/reverse-proxy override", () => {+ const win = {+ __OMNIVOICE_API_BASE__: "https://voice.example/studio/",+ } as Window & {__OMNIVOICE_API_BASE__?: string;};- expect(resolveApiBase(true, false, win)).toBe('https://voice.example/studio');+ expect(resolveApiBase(true, false, win)).toBe(+ "https://voice.example/studio",+ );});- it('keeps transport prefixes separate from logical /api routes', () => {- expect(joinApiPath('https://voice.example/studio', '/engines')).toBe(- 'https://voice.example/studio/engines',- );- expect(joinApiPath('https://voice.example/api', '/api/settings/analytics')).toBe(- 'https://voice.example/api/api/settings/analytics',+ it("keeps transport prefixes separate from logical /api routes", () => {+ expect(joinApiPath("https://voice.example/studio", "/engines")).toBe(+ "https://voice.example/studio/engines",);+ expect(+ joinApiPath("https://voice.example/api", "/api/settings/analytics"),+ ).toBe("https://voice.example/api/api/settings/analytics");});- it('strips only the development transport prefix', () => {- expect(rewriteDevApiProxyPath('/api/engines')).toBe('/engines');- expect(rewriteDevApiProxyPath('/api/ws/events')).toBe('/ws/events');- expect(rewriteDevApiProxyPath('/api/settings/analytics')).toBe('/api/settings/analytics');- expect(rewriteDevApiProxyPath('/api/auth/session')).toBe('/api/auth/session');- expect(rewriteDevApiProxyPath('/api/integrations/twilio/state')).toBe(- '/api/integrations/twilio/state',+ it("strips only the development transport prefix", () => {+ expect(rewriteDevApiProxyPath("/api/engines")).toBe("/engines");+ expect(rewriteDevApiProxyPath("/api/ws/events")).toBe("/ws/events");+ expect(rewriteDevApiProxyPath("/api/settings/analytics")).toBe(+ "/api/settings/analytics",+ );+ expect(rewriteDevApiProxyPath("/api/auth/session")).toBe(+ "/api/auth/session",+ );+ expect(rewriteDevApiProxyPath("/api/integrations/twilio/state")).toBe(+ "/api/integrations/twilio/state",+ );+ expect(rewriteDevApiProxyPath("/api/mcp/bindings")).toBe(+ "/api/mcp/bindings",);- expect(rewriteDevApiProxyPath('/api/mcp/bindings')).toBe('/api/mcp/bindings');});});-describe('JSON request headers', () => {- it('labels serialized JSON bodies while preserving caller headers', async () => {+describe("JSON request headers", () => {+ it("labels serialized JSON bodies while preserving caller headers", async () => {const fetchMock = vi.fn(- async (_url: RequestInfo | URL, _init?: RequestInit) => new Response('{}'),+ async (_url: RequestInfo | URL, _init?: RequestInit) =>+ new Response("{}"),);- vi.stubGlobal('fetch', fetchMock);- await apiJson('/audiobook/plan', {- method: 'POST',- body: JSON.stringify({ text: 'Chapter' }),- headers: { 'X-Test': 'preserved' },+ vi.stubGlobal("fetch", fetchMock);+ await apiJson("/audiobook/plan", {+ method: "POST",+ body: JSON.stringify({ text: "Chapter" }),+ headers: { "X-Test": "preserved" },});const headers = new Headers(fetchMock.mock.calls[0][1]?.headers);- expect(headers.get('content-type')).toBe('application/json');- expect(headers.get('x-test')).toBe('preserved');+ expect(headers.get("content-type")).toBe("application/json");+ expect(headers.get("x-test")).toBe("preserved");});- it('leaves multipart boundaries and explicit content types to the caller', async () => {+ it("leaves multipart boundaries and explicit content types to the caller", async () => {const fetchMock = vi.fn(- async (_url: RequestInfo | URL, _init?: RequestInit) => new Response('{}'),+ async (_url: RequestInfo | URL, _init?: RequestInit) =>+ new Response("{}"),);- vi.stubGlobal('fetch', fetchMock);+ vi.stubGlobal("fetch", fetchMock);const body = new FormData();- body.set('cover', new Blob(['image']), 'cover.png');- await apiJson('/audiobook/cover', { method: 'POST', body });- expect(new Headers(fetchMock.mock.calls[0][1]?.headers).has('content-type')).toBe(false);- await apiJson('/custom', {- method: 'POST',- body: 'text',- headers: { 'content-type': 'text/plain' },+ body.set("cover", new Blob(["image"]), "cover.png");+ await apiJson("/audiobook/cover", { method: "POST", body });+ expect(+ new Headers(fetchMock.mock.calls[0][1]?.headers).has("content-type"),+ ).toBe(false);+ await apiJson("/custom", {+ method: "POST",+ body: "text",+ headers: { "content-type": "text/plain" },});- expect(new Headers(fetchMock.mock.calls[1][1]?.headers).get('content-type')).toBe('text/plain');+ expect(+ new Headers(fetchMock.mock.calls[1][1]?.headers).get("content-type"),+ ).toBe("text/plain");});});-it('uses a structured error message without losing recovery metadata', async () => {+it("uses a structured error message without losing recovery metadata", async () => {const detail = {- error: 'asr_model_missing',- message: 'Install the selected speech model.',- recommended: { repo_id: 'test/model' },+ error: "asr_model_missing",+ message: "Install the selected speech model.",+ recommended: { repo_id: "test/model" },};- const error = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 409 }));+ const error = await errorFromResponse(+ new Response(JSON.stringify({ detail }), { status: 409 }),+ );expect(error.message).toBe(detail.message);expect(error.payload?.detail).toEqual(detail);});-it('localizes structured profile language failures', async () => {- const translate = vi.spyOn(i18next, 't').mockReturnValue('Localized profile guidance');+it("localizes structured profile language failures", async () => {+ const translate = vi+ .spyOn(i18next, "t")+ .mockReturnValue("Localized profile guidance");try {const detail = {- code: 'profile_language_rejected',- language: 'Persian',- message: 'English fallback',+ code: "profile_language_rejected",+ language: "Persian",+ message: "English fallback",};const error = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 400 }),);- expect(error.detail).toBe('Localized profile guidance');- expect(translate).toHaveBeenCalledWith('tts_errors.profile_language_rejected', {- language: 'Persian',- });+ expect(error.detail).toBe("Localized profile guidance");+ expect(translate).toHaveBeenCalledWith(+ "tts_errors.profile_language_rejected",+ {+ language: "Persian",+ },+ );} finally {translate.mockRestore();}});-it('localizes a no-audio-track upload rejection (422)', async () => {- const translate = vi.spyOn(i18next, 't').mockReturnValue('Localized no-audio guidance');+it("localizes a no-audio-track upload rejection (422)", async () => {+ const translate = vi+ .spyOn(i18next, "t")+ .mockReturnValue("Localized no-audio guidance");try {const detail = {- code: 'no_audio_track',- docs_topic: 'NO_AUDIO_TRACK',- message: 'This file has no audio track, so there is no speech to transcribe, dub or clone.',- hint: 'English hint',+ code: "no_audio_track",+ docs_topic: "NO_AUDIO_TRACK",+ message:+ "This file has no audio track, so there is no speech to transcribe, dub or clone.",+ hint: "English hint",};const error = await errorFromResponse(new Response(JSON.stringify({ detail }), { status: 422 }),);- expect(error.message).toBe('Localized no-audio guidance');+ expect(error.message).toBe("Localized no-audio guidance");expect(error.payload?.detail).toEqual(detail);- expect(translate).toHaveBeenCalledWith('tts_errors.no_audio_track');+ expect(translate).toHaveBeenCalledWith("tts_errors.no_audio_track");} finally {translate.mockRestore();}});-it.each([false, true])('localizes HTTP failure topics (nested: %s)', async (nested) => {- const translate = vi.spyOn(i18next, 't').mockReturnValue('Localized recovery');+it.each([false, true])(+ "localizes HTTP failure topics (nested: %s)",+ async (nested) => {+ const translate = vi+ .spyOn(i18next, "t")+ .mockReturnValue("Localized recovery");+ try {+ const failure = {+ docs_topic: "GPU_ARCH_UNSUPPORTED",+ detail: "English fallback",+ };+ const payload = nested ? { detail: failure } : failure;+ const error = await errorFromResponse(+ new Response(JSON.stringify(payload), { status: 500 }),+ );+ expect(error.message).toBe("Localized recovery");+ expect(error.payload).toEqual(payload);+ expect(translate).toHaveBeenCalledWith("tts_errors.gpu_arch_unsupported");+ } finally {+ translate.mockRestore();+ }+ },+);++it("replaces a proxy gateway page with a localized explanation (#2781)", async () => {+ const translate = vi.spyOn(i18next, "t").mockReturnValue("Proxy gave up");+ try {+ const html =+ "<html><head><title>504 Gateway Time-out</title></head><body>nginx/1.31.6</body></html>";+ const error = await errorFromResponse(new Response(html, { status: 504 }));+ expect(error.message).toBe("Proxy gave up");+ expect(error.message).not.toContain("<html>");+ expect(translate).toHaveBeenCalledWith("tts_errors.proxy_gateway_error", {+ status: 504,+ });+ } finally {+ translate.mockRestore();+ }+});++it("keeps a backend-marked 504 as the backend answered it", async () => {+ const error = await errorFromResponse(+ new Response("upstream said no", {+ status: 504,+ headers: { "x-omnivoice-backend": "1" },+ }),+ );+ expect(error.message).toBe("upstream said no");+});++it("names the missing route for an unrouted 404 (#2627)", async () => {+ const translate = vi.spyOn(i18next, "t").mockReturnValue("No such route");try {- const failure = { docs_topic: 'GPU_ARCH_UNSUPPORTED', detail: 'English fallback' };- const payload = nested ? { detail: failure } : failure;- const error = await errorFromResponse(new Response(JSON.stringify(payload), { status: 500 }));- expect(error.message).toBe('Localized recovery');- expect(error.payload).toEqual(payload);- expect(translate).toHaveBeenCalledWith('tts_errors.gpu_arch_unsupported');+ const res = new Response(JSON.stringify({ detail: "Not Found" }), {+ status: 404,+ });+ Object.defineProperty(res, "url", {+ value: "http://127.0.0.1:3900/api/generate/preview",+ });+ const error = await errorFromResponse(res);+ expect(error.message).toBe("No such route");+ expect(translate).toHaveBeenCalledWith("tts_errors.route_not_found", {+ route: "/api/generate/preview",+ });} finally {translate.mockRestore();}});-it('shows top-level API recovery errors without exposing raw JSON', async () => {+it("leaves a specific 404 detail untouched", async () => {+ const error = await errorFromResponse(+ new Response(JSON.stringify({ detail: "Audio file not found" }), {+ status: 404,+ }),+ );+ expect(error.message).toBe("Audio file not found");+});++it("shows top-level API recovery errors without exposing raw JSON", async () => {const payload = {- error: 'Install the Argos language pack for en → es before translating.',- code: 'argos_pack_missing',- pairs: [{ source_lang: 'en', target_lang: 'es', installed: false }],+ error: "Install the Argos language pack for en → es before translating.",+ code: "argos_pack_missing",+ pairs: [{ source_lang: "en", target_lang: "es", installed: false }],};- const error = await errorFromResponse(new Response(JSON.stringify(payload), { status: 400 }));+ const error = await errorFromResponse(+ new Response(JSON.stringify(payload), { status: 400 }),+ );expect(error.message).toBe(payload.error);expect(error.payload).toEqual(payload);});-describe('engine selection event', () => {- it('fires after a successful POST /engines/select only', async () => {- vi.stubGlobal('fetch', async () => new Response('{}', { status: 200 }));+describe("engine selection event", () => {+ it("fires after a successful POST /engines/select only", async () => {+ vi.stubGlobal("fetch", async () => new Response("{}", { status: 200 }));const seen = vi.fn();window.addEventListener(ENGINE_SELECTED_EVENT, seen);try {- await apiFetch('/engines/select');- await apiFetch('/engines/select', { method: 'GET' });+ await apiFetch("/engines/select");+ await apiFetch("/engines/select", { method: "GET" });expect(seen).not.toHaveBeenCalled();- await apiFetch('/engines/select', { method: 'POST', body: '{}' });+ await apiFetch("/engines/select", { method: "POST", body: "{}" });expect(seen).toHaveBeenCalledTimes(1);- vi.stubGlobal('fetch', async () => new Response('{}', { status: 500 }));- await apiFetch('/engines/select', { method: 'POST', body: '{}' }).catch(() => {});+ vi.stubGlobal("fetch", async () => new Response("{}", { status: 500 }));+ await apiFetch("/engines/select", { method: "POST", body: "{}" }).catch(+ () => {},+ );expect(seen).toHaveBeenCalledTimes(1);} finally {window.removeEventListener(ENGINE_SELECTED_EVENT, seen);diff --git a/electron/src/renderer/src/lib/api/client.ts b/electron/src/renderer/src/lib/api/client.tsindex 547f60338..f8de0bad3 100644--- a/electron/src/renderer/src/lib/api/client.ts+++ b/electron/src/renderer/src/lib/api/client.ts@@ -1,44 +1,52 @@-import { generationFailureMessage } from '@shared/utils/generationFailureMessage.ts';-import { languageRejectionMessage } from '@shared/utils/languageRejection.ts';+import { generationFailureMessage } from "@shared/utils/generationFailureMessage.ts";+import { languageRejectionMessage } from "@shared/utils/languageRejection.ts";/** Native builds use Electron's `/api` protocol proxy. The production web* bundle is served by FastAPI itself, whose routes live at the origin root. */-import type { ApiErrorPayload } from './types';-import { tr } from '@/lib/i18n-text';-import { getBackendStatusSnapshot } from '@/hooks/use-backend-status';-import { isBackendReachable } from '@shared/utils/backendStage';-import { recordBackendContact } from '@shared/utils/backendContact';+import type { ApiErrorPayload } from "./types";+import { tr } from "@/lib/i18n-text";+import { getBackendStatusSnapshot } from "@/hooks/use-backend-status";+import { isBackendReachable } from "@shared/utils/backendStage";+import { recordBackendContact } from "@shared/utils/backendContact";import {clearAdminSession,CSRF_HEADER_NAME,getAdminSession,isSameOriginApi,-} from '@shared/api/authSession';-import { joinApiPath } from '../../../../shared/web-api-routing';+} from "@shared/api/authSession";+import { joinApiPath } from "../../../../shared/web-api-routing";import {announceModelLicenceRequired,modelLicenceRequirements,-} from '@/features/settings/model-license-contract';-export { joinApiPath } from '../../../../shared/web-api-routing';+} from "@/features/settings/model-license-contract";+export { joinApiPath } from "../../../../shared/web-api-routing";type ApiBaseWindow = Window & { __OMNIVOICE_API_BASE__?: string };-export function resolveApiBase(webDeployment: boolean, dev: boolean, win?: ApiBaseWindow): string {- if (!webDeployment || dev) return '/api';+export function resolveApiBase(+ webDeployment: boolean,+ dev: boolean,+ win?: ApiBaseWindow,+): string {+ if (!webDeployment || dev) return "/api";const runtime = win?.__OMNIVOICE_API_BASE__?.trim();- return runtime ? runtime.replace(/\/+$/, '') : '';+ return runtime ? runtime.replace(/\/+$/, "") : "";}export const API_BASE = resolveApiBase(__WEB_DEPLOYMENT__,import.meta.env.DEV,- typeof window === 'undefined' ? undefined : (window as ApiBaseWindow),+ typeof window === "undefined" ? undefined : (window as ApiBaseWindow),);export function absoluteApiBase(): string {- if (typeof window === 'undefined') return API_BASE;- return new URL(API_BASE || '/', window.location.href).toString().replace(/\/+$/, '');+ if (typeof window === "undefined") return API_BASE;+ return new URL(API_BASE || "/", window.location.href)+ .toString()+ .replace(/\/+$/, "");}+const BACKEND_MARKER = "x-omnivoice-backend";+export class ApiError extends Error {readonly status: number;/** Human-readable detail (the backend's `detail`, JSON-stringified when structured). */@@ -46,9 +54,13 @@ export class ApiError extends Error {/** The parsed JSON error body when there was one. */readonly payload: ApiErrorPayload | null;- constructor(status: number, detail: string, payload: ApiErrorPayload | null = null) {+ constructor(+ status: number,+ detail: string,+ payload: ApiErrorPayload | null = null,+ ) {super(detail);- this.name = 'ApiError';+ this.name = "ApiError";this.status = status;this.detail = detail;this.payload = payload;@@ -64,7 +76,9 @@ export function apiPath(path: string): string {export function isAbortError(err: unknown): boolean {return (- typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'AbortError'+ typeof err === "object" &&+ err !== null &&+ (err as { name?: unknown }).name === "AbortError");}@@ -76,28 +90,30 @@ export function describeError(err: unknown): string {}function detailToString(detail: unknown): string {- const localized = languageRejectionMessage(detail, tr) || generationFailureMessage(detail, tr);+ const localized =+ languageRejectionMessage(detail, tr) ||+ generationFailureMessage(detail, tr);if (localized) return localized;if (detail &&- typeof detail === 'object' &&- 'code' in detail &&- detail.code === 'argos_runtime_unavailable'+ typeof detail === "object" &&+ "code" in detail &&+ detail.code === "argos_runtime_unavailable")- return tr('engines.argosRuntimeUnavailable');+ return tr("engines.argosRuntimeUnavailable");if (detail &&- typeof detail === 'object' &&- 'code' in detail &&- detail.code === 'dub_background_unavailable'+ typeof detail === "object" &&+ "code" in detail &&+ detail.code === "dub_background_unavailable")- return tr('dubIntegrity.backgroundUnavailable');- if (typeof detail === 'string') return detail;- if (detail == null) return '';+ return tr("dubIntegrity.backgroundUnavailable");+ if (typeof detail === "string") return detail;+ if (detail == null) return "";if (- typeof detail === 'object' &&- 'message' in detail &&- typeof detail.message === 'string' &&+ typeof detail === "object" &&+ "message" in detail &&+ typeof detail.message === "string" &&detail.message.trim())return detail.message;@@ -110,7 +126,7 @@ function detailToString(detail: unknown): string {/** Build the ApiError for a non-2xx response: JSON `detail` when present, else the body text. */export async function errorFromResponse(res: Response): Promise<ApiError> {- let text = '';+ let text = "";try {text = await res.text();} catch {@@ -120,50 +136,91 @@ export async function errorFromResponse(res: Response): Promise<ApiError> {if (text) {try {const parsed: unknown = JSON.parse(text);- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {payload = parsed as ApiErrorPayload;}} catch {// Plain-text body.}}+ // A 502/503/504 that is not JSON did not come from VoiceStudio: a reverse+ // proxy (nginx, Caddy, a tunnel) gave up waiting and answered with its own+ // HTML page (#2781). Echoing that page told the user nothing about the real+ // situation, which is that the backend may well still be rendering.+ if (+ !payload &&+ text.trim() &&+ [502, 503, 504].includes(res.status) &&+ !res.headers?.get?.(BACKEND_MARKER)+ ) {+ return new ApiError(+ res.status,+ tr("tts_errors.proxy_gateway_error", { status: res.status }),+ null,+ );+ }+ // Starlette's unrouted-path reply. The running backend has no such route, so+ // name where the request went instead of an unexplained "Not Found" (#2627).+ if (+ res.status === 404 &&+ payload &&+ payload.detail === "Not Found" &&+ Object.keys(payload).length === 1+ ) {+ let route = "";+ try {+ route = new URL(res.url).pathname;+ } catch {+ // No URL on a synthetic response; the message still reads correctly.+ }+ return new ApiError(+ 404,+ tr("tts_errors.route_not_found", { route: route || "/" }),+ payload,+ );+ }// Any feature can hit a model whose licence is not yet accepted; one// app-level dialog handles them all.- const licence = announceModelLicenceRequired(payload) ? modelLicenceRequirements(payload) : null;+ const licence = announceModelLicenceRequired(payload)+ ? modelLicenceRequirements(payload)+ : null;const detail =- (licence && tr('modelLicense.requiredError')) ||+ (licence && tr("modelLicense.requiredError")) ||generationFailureMessage(payload, tr) ||- (payload && 'detail' in payload+ (payload && "detail" in payload? detailToString(payload.detail)- : payload && typeof payload.error === 'string'+ : payload && typeof payload.error === "string"? payload.error.trim()- : payload && typeof payload.message === 'string'+ : payload && typeof payload.message === "string"? payload.message.trim(): text.trim());- const statusLine = `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''}`;+ const statusLine = `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ""}`;return new ApiError(res.status, detail || statusLine, payload);}/** Fired after a successful `POST /engines/select`. */-export const ENGINE_SELECTED_EVENT = 'ov:engine-selected';+export const ENGINE_SELECTED_EVENT = "ov:engine-selected";/*** fetch() against the API. Throws ApiError on any non-2xx response and an* ApiError with status 0 when the backend is unreachable. Deliberate aborts* are re-thrown untouched so callers can tell them apart.*/-export async function apiFetch(path: string, init?: RequestInit): Promise<Response> {+export async function apiFetch(+ path: string,+ init?: RequestInit,+): Promise<Response> {// #2430: only a stage that cannot answer at all short-circuits here. A// live-but-busy `unresponsive` backend is still listening, so the request is// issued and simply resolves late, when the job holding the event loop// finishes. Rejecting it up front is what made fetching the audio of an// already-succeeded streamed generation fail.if (- typeof window !== 'undefined' &&+ typeof window !== "undefined" &&window.voicestudio?.backend &&!isBackendReachable(getBackendStatusSnapshot().stage))- throw new ApiError(0, tr('tts_errors.backend_unreachable'));+ throw new ApiError(0, tr("tts_errors.backend_unreachable"));let res: Response;let sentSession: ReturnType<typeof getAdminSession> = null;try {@@ -172,41 +229,49 @@ export async function apiFetch(path: string, init?: RequestInit): Promise<Responconst headers = new Headers(init?.headers);let pin: string | null = null;try {- pin = sessionStorage.getItem('ov_pin');+ pin = sessionStorage.getItem("ov_pin");} catch {// Cookie and bearer-session authentication still work when storage is blocked.}sentSession = getAdminSession(apiBase);- if (pin) headers.set('X-OmniVoice-Pin', pin);- if (sentSession) headers.set('Authorization', `Bearer ${sentSession.token}`);- if (isSameOriginApi(apiBase)) headers.set(CSRF_HEADER_NAME, '1');- init = { ...init, headers, credentials: 'include' };+ if (pin) headers.set("X-OmniVoice-Pin", pin);+ if (sentSession)+ headers.set("Authorization", `Bearer ${sentSession.token}`);+ if (isSameOriginApi(apiBase)) headers.set(CSRF_HEADER_NAME, "1");+ init = { ...init, headers, credentials: "include" };}res = await fetch(apiPath(path), init);} catch (err) {if (isAbortError(err)) throw err;- throw new ApiError(0, tr('tts_errors.backend_unreachable'));+ throw new ApiError(0, tr("tts_errors.backend_unreachable"));}// Any HTTP response, including an error status, proves the backend answered.recordBackendContact();if (!res.ok) {const error = await errorFromResponse(res);const detail = error.detail.toLowerCase();- const adminGate = error.status === 403 && detail.includes('admin api key');+ const adminGate = error.status === 403 && detail.includes("admin api key");if (__WEB_DEPLOYMENT__ && (error.status === 401 || adminGate)) {- const mode = detail.includes('api key') ? 'apikey' : 'pin';+ const mode = detail.includes("api key") ? "apikey" : "pin";const currentSession = getAdminSession(absoluteApiBase());- const staleResponse = mode === 'apikey' && currentSession?.token !== sentSession?.token;+ const staleResponse =+ mode === "apikey" && currentSession?.token !== sentSession?.token;if (!staleResponse) {- if (mode === 'apikey' && sentSession) clearAdminSession();- window.dispatchEvent(new CustomEvent('ov:auth-required', { detail: { mode } }));+ if (mode === "apikey" && sentSession) clearAdminSession();+ window.dispatchEvent(+ new CustomEvent("ov:auth-required", { detail: { mode } }),+ );}}throw error;}// The active engine decides which compute route (and so which generate// budget) a take gets; consumers re-read their derived state on this event.- if (typeof window !== 'undefined' && path === '/engines/select' && init?.method === 'POST')+ if (+ typeof window !== "undefined" &&+ path === "/engines/select" &&+ init?.method === "POST"+ )window.dispatchEvent(new CustomEvent(ENGINE_SELECTED_EVENT));return res;}@@ -214,9 +279,10 @@ export async function apiFetch(path: string, init?: RequestInit): Promise<Responexport async function apiJson<T>(path: string, init?: RequestInit): Promise<T> {// String bodies on this helper are serialized JSON; never label FormData,// whose multipart boundary must be supplied by the browser.- if (typeof init?.body === 'string') {+ if (typeof init?.body === "string") {const headers = new Headers(init.headers);- if (!headers.has('Content-Type')) headers.set('Content-Type', 'application/json');+ if (!headers.has("Content-Type"))+ headers.set("Content-Type", "application/json");init = { ...init, headers };}const res = await apiFetch(path, init);@@ -234,6 +300,6 @@ export function audioUrl(filename: string): string {* replaced, so players and HTTP caches never keep the previous sample.*/export function profileAudioUrl(id: string, audioUrl?: string | null): string {- if (audioUrl?.startsWith('/profiles/')) return apiPath(audioUrl);+ if (audioUrl?.startsWith("/profiles/")) return apiPath(audioUrl);return `${API_BASE}/profiles/${encodeURIComponent(id)}/audio`;}diff --git a/electron/src/shared/utils/bugReportDocument.js b/electron/src/shared/utils/bugReportDocument.jsindex 1f0e6055c..72aad3b65 100644--- a/electron/src/shared/utils/bugReportDocument.js+++ b/electron/src/shared/utils/bugReportDocument.js@@ -43,17 +43,23 @@ export function composeBugReportUrl({// unclassified engine failure from another (#1800). Taken from the error// itself, then from a parsed 500 body — the Electron client keeps that on// `payload` instead of lifting the field onto the error (lib/api/client.ts).+ // `error_type` is the exception type the 500 handler names (#2917); the+ // older `error_class` there is the diagnosis taxonomy, which is "UNKNOWN"+ // for most failures, so it only fills in when no type was sent.const rawClass =typeof error?.errorClass === 'string' && error.errorClass? error.errorClass- : error?.payload?.error_class;+ : error?.payload?.error_type || error?.payload?.error_class;const klass = typeof rawClass === 'string' && rawClass ? scrubText(rawClass) : '';+ const rawTopic = error?.payload?.docs_topic ?? error?.payload?.detail?.docs_topic;+ const topic = typeof rawTopic === 'string' && rawTopic ? scrubText(rawTopic) : '';errorSection.push('## Error','','```',msgForBody,...(klass ? [`Backend error class: ${klass}`] : []),+ ...(topic ? [`Backend failure topic: ${topic}`] : []),...(stack && stack !== msgForBody ? [stack] : []),'```','',diff --git a/electron/src/shared/utils/bugReportDocument.test.js b/electron/src/shared/utils/bugReportDocument.test.jsindex f481d3b9f..7c389c607 100644--- a/electron/src/shared/utils/bugReportDocument.test.js+++ b/electron/src/shared/utils/bugReportDocument.test.js@@ -33,6 +33,25 @@ describe('composeBugReportUrl', () => {expect(bodyOf({ error })).toContain('Backend error class: RuntimeError');});+ it('reports the exception type and diagnosis topic of a 500 body (#2917)', () => {+ const error = new Error('VoiceStudio hit an internal error');+ error.payload = {+ error_class: 'UNKNOWN',+ error_type: 'RuntimeError',+ docs_topic: 'ENGINE_DEPENDENCY_MISSING',+ };+ const body = bodyOf({ error });+ expect(body).toContain('Backend error class: RuntimeError');+ expect(body).toContain('Backend failure topic: ENGINE_DEPENDENCY_MISSING');+ expect(body).not.toContain('UNKNOWN');+ });++ it('reads the topic of a structured detail', () => {+ const error = new Error('boom');+ error.payload = { detail: { docs_topic: 'REFERENCE_STT_MISSING' } };+ expect(bodyOf({ error })).toContain('Backend failure topic: REFERENCE_STT_MISSING');+ });+it('prefers an explicit errorClass over the payload', () => {const error = new Error('boom');error.errorClass = 'ValueError';diff --git a/electron/src/shared/utils/generationFailureMessage.test.ts b/electron/src/shared/utils/generationFailureMessage.test.tsindex ba52aa10b..96f187d24 100644--- a/electron/src/shared/utils/generationFailureMessage.test.ts+++ b/electron/src/shared/utils/generationFailureMessage.test.ts@@ -23,6 +23,16 @@ describe('generationFailureMessage', () => {expect(generationFailureMessage({ code }, translate)).toBe(`t:${key}`);});+ it.each([+ ['GPU_OOM', 'tts_errors.gpu_oom'],+ ['HOST_MEMORY_EXHAUSTED', 'tts_errors.host_memory_exhausted'],+ ['ENGINE_DEPENDENCY_MISSING', 'tts_errors.engine_dependency_missing'],+ ['REFERENCE_STT_MISSING', 'tts_errors.reference_stt_missing'],+ ])('localizes the %s diagnostic topic instead of the generic floor message', (topic, key) => {+ const translate = vi.fn((k: string) => `t:${k}`);+ expect(generationFailureMessage({ docs_topic: topic }, translate)).toBe(`t:${key}`);+ });+it('never turns a server-supplied code into a translation key', () => {const translate = vi.fn();expect(generationFailureMessage({ code: 'tts_errors.no_audio_track' }, translate)).toBeUndefined();diff --git a/electron/src/shared/utils/generationFailureMessage.ts b/electron/src/shared/utils/generationFailureMessage.tsindex 0c3a76622..3a807a0ce 100644--- a/electron/src/shared/utils/generationFailureMessage.ts+++ b/electron/src/shared/utils/generationFailureMessage.ts@@ -21,6 +21,14 @@ export function generationFailureMessage(return translate('tts_errors.audio_io_failed');case 'NO_AUDIO_TRACK':return translate('tts_errors.no_audio_track');+ case 'GPU_OOM':+ return translate('tts_errors.gpu_oom');+ case 'HOST_MEMORY_EXHAUSTED':+ return translate('tts_errors.host_memory_exhausted');+ case 'ENGINE_DEPENDENCY_MISSING':+ return translate('tts_errors.engine_dependency_missing');+ case 'REFERENCE_STT_MISSING':+ return translate('tts_errors.reference_stt_missing');default:return undefined;}diff --git a/tests/test_failure_classify.py b/tests/test_failure_classify.pyindex ea9c4a1de..a82c58fcf 100644--- a/tests/test_failure_classify.py+++ b/tests/test_failure_classify.py@@ -102,8 +102,8 @@ def test_classify_broken_venv_encodings():assert failure.classify("ModuleNotFoundError: No module named 'encodings'") == ("BROKEN_VENV")- # ...but an app-level import of an 'encodings'-prefixed package must NOT.- assert failure.classify("No module named 'encodings_helper'") == ""+ # ...but an app-level import of an 'encodings'-prefixed package is not BROKEN_VENV (it is a missing engine package).+ assert failure.classify("No module named 'encodings_helper'") == "ENGINE_DEPENDENCY_MISSING"def test_classify_broken_venv_missing_own_package():@@ -113,9 +113,9 @@ def test_classify_broken_venv_missing_own_package():assert failure.classify("ModuleNotFoundError: No module named 'omnivoice'") == ("BROKEN_VENV")- # ...but a legitimately-named 'omnivoice_*' helper package must NOT match+ # ...but a legitimately-named 'omnivoice_*' helper package is not BROKEN_VENV# (the trailing quote in the matcher is the guard).- assert failure.classify("No module named 'omnivoice_helper'") == ""+ assert failure.classify("No module named 'omnivoice_helper'") == "ENGINE_DEPENDENCY_MISSING"def test_classify_socks_proxy_support_missing():diff --git a/tests/test_generation_failure_diagnostics.py b/tests/test_generation_failure_diagnostics.pynew file mode 100644index 000000000..f852c24df--- /dev/null+++ b/tests/test_generation_failure_diagnostics.py@@ -0,0 +1,147 @@+"""Generation failures must name their real cause, not the generic floor text.++Covers the distinct causes behind #2895/#2684/#2666/#2626/#2622/#2580 ("Generation+failed. Check the selected engine..."), #2917/#2916/#2688 (500 "internal error"),+#2929/#2678 (no speech-to-text model) and #2764 (reference ranking billed to the+generate clock).+"""+import pytest++from core.failure import classify, is_terminal_failure_topic+from core.public_errors import public_exception_response, stream_generation_failure+++ "exc, topic",+ [+ (ModuleNotFoundError("No module named 'kokoro_onnx'"), "ENGINE_DEPENDENCY_MISSING"),+ (+ ValueError(+ "Automatic reference transcription needs an installed speech-to-text "+ "model. Provide a matching reference transcript."+ ),+ "REFERENCE_STT_MISSING",+ ),+ ],+)+def test_distinct_causes_are_classified(exc, topic):+ assert classify(exc) == topic+ assert is_terminal_failure_topic(topic)+++def test_broken_venv_modules_keep_their_own_class():+ assert classify("No module named 'encodings'") == "BROKEN_VENV"+ assert classify("No module named 'omnivoice'") == "BROKEN_VENV"+++def test_an_unrelated_failure_is_still_unclassified():+ assert classify(RuntimeError("boom")) == ""+++def test_stream_frame_names_the_cause_and_stops_retries():+ payload = stream_generation_failure(+ RuntimeError("engine import failed: No module named 'secret_pkg_name'")+ )+ assert payload["docs_topic"] == "ENGINE_DEPENDENCY_MISSING"+ assert payload["error_class"] == "RuntimeError"+ assert payload["terminal"] is True and payload["retryable"] is False+ assert "Install / Repair" in payload["detail"]+ # Only VoiceStudio-owned text: the module name from the exception is not echoed.+ assert "secret_pkg_name" not in str(payload)+++def test_response_hint_is_owned_text():+ resp = public_exception_response(+ ModuleNotFoundError("No module named 'C:/Users/someone/m'"),+ fallback="VoiceStudio hit an internal error.",+ )+ assert resp["docs_topic"] == "ENGINE_DEPENDENCY_MISSING"+ assert "someone" not in str(resp)++[email protected](scope="module")+def client():+ from fastapi.testclient import TestClient+ from main import app+ import core.db++ core.db.init_db()+ return TestClient(app, client=("127.0.0.1", 50000), raise_server_exceptions=False)+++def test_500_body_carries_exception_type_and_topic(client, monkeypatch):+ import api.routers.generation as gen++ async def boom():+ raise RuntimeError("engine import failed: No module named 'pytorch_model_bin'")++ monkeypatch.setattr(gen, "get_model", boom)+ r = client.post("/generate", data={"text": "hello", "engine": "omnivoice"})+ assert r.status_code == 500+ body = r.json()+ assert body["error_type"] == "RuntimeError"+ assert body["docs_topic"] == "ENGINE_DEPENDENCY_MISSING"+ assert "pytorch_model_bin" not in str(body)+++def test_missing_stt_400_is_structured_for_localization(client, monkeypatch):+ import api.routers.generation as gen++ class _Model:+ pass++ async def fake_model():+ return _Model()++ def reject(*_a, **_k):+ raise ValueError(+ "Automatic reference transcription needs an installed speech-to-text model."+ )++ monkeypatch.setattr(gen, "get_model", fake_model)+ monkeypatch.setattr(gen, "_run_inference", reject)+ r = client.post("/generate", data={"text": "hello", "engine": "omnivoice"})+ if r.status_code == 400 and isinstance(r.json().get("detail"), dict):+ assert r.json()["detail"]["docs_topic"] == "REFERENCE_STT_MISSING"+ else: # the route short-circuited before inference on this host+ pytest.skip(f"route answered {r.status_code} before reaching inference")+++def test_prepare_reference_passage_ranks_once_and_cleans_up(tmp_path, monkeypatch):+ import services.tts_backend as tb++ window = tmp_path / "w.wav"+ window.write_bytes(b"x")+ calls = []++ monkeypatch.setattr(tb, "reference_duration_s", lambda _p: 40.0)+ monkeypatch.setattr(+ tb, "_reuse_or_rank_passage", lambda p: calls.append(p) or (str(window), "hello")+ )+ assert tb.prepare_reference_passage(str(tmp_path / "ref.wav")) is True+ assert len(calls) == 1+ assert not window.exists()+++def test_prepare_reference_passage_ignores_short_clips(monkeypatch):+ import services.tts_backend as tb++ monkeypatch.setattr(tb, "reference_duration_s", lambda _p: 8.0)+ monkeypatch.setattr(+ tb, "_reuse_or_rank_passage", lambda p: pytest.fail("short clip must not be ranked")+ )+ assert tb.prepare_reference_passage("ref.wav") is False+ assert tb.prepare_reference_passage(None) is False+++def test_generate_route_ranks_long_reference_before_the_engine_clock():+ """Fail-before/pass-after guard: the pre-rank must sit above the dispatch."""+ import inspect++ import api.routers.generation as gen++ src = inspect.getsource(gen)+ pre = src.index("prepare_reference_passage")+ first_engine_dispatch = src.index("_run_inference,", pre) if "_run_inference," in src[pre:] else len(src)+ assert pre < first_engine_dispatch+ assert "Reference passage selection" in src