Files
VoiceStudio/tests/test_no_hardcoded_cjk.py
davidsiguenzaanddebpalash 4bff24b820 feat(dub): guide subtitle-led dubbing from preparation to listening and export (#4221)
* feat(dub): guide subtitle-led dubbing from preparation to listening and export

* test(dub): allow functional multilingual phrase punctuation

* docs(changelog): record pull request #4221

* fix(dub): generate without a plan preview when the backend has no plan route

An older or remote backend answers POST /dub/plan with Starlette's
unrouted 404, which left Generate permanently disabled behind a retry.
Treat only the missing route (or 405) as 'no preview available' and keep
blocking real check failures.

* fix(dub): keep background separation on unless voice only is chosen

The staged preparation flow defaulted Keep music and ambience to off, so
a user clicking through the new steps lost the music and ambience every
dub kept before (and that the demo path and API still keep). Default to
separation, honour an explicit voice-only choice, and label SRT-only
imports as imports.

* fix(dub): audition lines that have no saved take yet

The row listen control now only read saved segment WAVs, so before the
first generation (live preview is off by default) it answered 'Segment
not generated yet' instead of auditioning the line as it did before.
Read saved takes back and fall back to the existing preview-segment
audition for lines without one.

* fix(dub): only offer issue Listen when the full track player exists

The issues panel offered Listen whenever a track existed, but the player
it seeks only renders for the current audio revision, so the click did
nothing and the stored seek fired later. Switching projects also kept the
previous project's open player and pending seek.

* fix(dub): restore the review-mode checkpoint in the guided flow

The guided workflow dropped the dub page's checkpoint banner, its only
consumer, so Settings -> Review mode no longer did anything. Show the
dismissible stage checkpoint again when review mode is on, with the
stage decision in a tested helper.

* fix(dub): show audio from earlier versions as complete in the guide

Projects generated before guided completion records have no request key,
so the guide sent them back to Create audio and an Assemble track pass.
Without a record, count the track as current when every spoken line has
a saved segment fingerprint and the incremental check reports no changed
line; a record, once written, stays authoritative.

* fix(dub): make automatic overflow fitting opt-in

Match the backend default (auto_fit_overflow=false): new sessions, drafts
and saved projects that never chose it keep the blocking timing error,
the switch starts unticked, and requests send the flag only when the
user turned it on.

* fix(dub): keep the open project when replacement subtitles are rejected

- Validate a replacement SRT before clearing the open project and its
  undo history; a rejection now leaves the current work intact.
- Resolve target-language subtitles through the translation-target map,
  so targets the source picker lacks (Uyghur, Kabyle, Cebuano) no longer
  import silently as source captions.
- Restore the timing narration replaced when new subtitles replace its
  blocks, instead of keeping Concise.

* fix(dub): allow plain-text export while narration audio is pending

TXT, like SRT/VTT/ASS, needs only the transcript, but the narration
readiness guard disabled it until the narration track was generated.

* fix(dub): require translation when the target is the media language after a target SRT

After importing target-language captions, the media's language still
matched the same-language shortcut, so switching the output to it marked
the English captions as ready Spanish text. Only the caption language now
counts as already-written text.

* fix(dub): show skipped, dropped and clamped cue counts after an SRT import

The guided source panel showed only the imported count, and the PR had
retired the three count messages, so a lossy import looked complete.
Restore the messages in all 22 locales and list each non-zero count.

* fix(dub): keep guided setup usable and its smokes green

- Ask the speaker count with the file when transcribing, and label the field.
- Keep "Translate all again" available once every line is translated.
- Close a link form opened for another project.
- Let the guide, next-step panels and issues share one band that shrinks
  first, so short windows keep the timeline and transcript on screen.
- Restore the deleted "Pending" guide label under dub.guide_pending.
- Mark the setup divider decorative.
- Check i18n keys picked by a condition inside t(), which hid that label.
- Walk the dub smoke through the guided steps.

* fix(dub): address review findings on guided dubbing

- A TXT save no longer marks the dubbed audio as exported.
- A partial regeneration that covers every stale row completes the audio step.
- The saved file path stays in memory, never in drafts or project files.
- Narration turns off without a language lookup; a target change waits for it.
- An unresolved target refuses target-language subtitles before replacing the project.
- A finished preparation is never replayed after a failed SRT import; a dropped
  stream resumes into the staged SRT, and after a reload the project asks for it.
- Generation previews and saved errors follow the submitted request, and the
  saved notice uses the same actionable message as a failed task.
- The completed player keeps its own revision; Merge previous selects the
  surviving row; the export step scrolls the player into view.

* fix(dub): complete the export step only for current target audio

A save of the retained track after an edit stores a file but no longer
records the export, so the later render still asks to be saved.

---------

Co-authored-by: debpalash <4178343+debpalash@users.noreply.github.com>
2026-11-26 12:09:01 -08:00

194 lines
7.9 KiB
Python

"""Keep CJK user-facing text in translation catalogs.
UI copy must use i18n ``t('...')`` keys backed by locale JSON. Native language
names come from ``Intl.DisplayNames`` in ``electron/src/renderer/src/i18n/``.
Functional CJK may be allowlisted below, with a justification for every file.
"""
from __future__ import annotations
import os
from pathlib import Path
import re
import subprocess
import pytest
_ROOT = Path(__file__).resolve().parents[1]
_CJK = re.compile(r"[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]")
_SKIP_EXTENSIONS = {
# images
".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".svg",
# fonts
".woff", ".woff2", ".ttf", ".otf",
# documents
".pdf",
# audio / video
".mp3", ".wav", ".mp4",
# lockfiles
".lock",
# model weights
".bin", ".onnx", ".safetensors",
}
_SKIP_DIRECTORIES = {
".git", "node_modules", "dist", "build", "__pycache__", ".venv", "venv",
"target", ".specify", ".claude", ".pytest_cache",
}
_ALLOWED_PREFIXES = {
"electron/src/renderer/src/i18n/": "The translation layer itself.",
"docs/specs/": "Design specs quote localized product copy as examples.",
"docs/readme/": "Translated READMEs and their native language-switcher links.",
}
_ALLOWED_FILES = {
"mobile/contract/tts/zipvoice-lexicon.txt": "Pinned multilingual pronunciation data, not UI copy.",
"electron/src/main/blank-window-guard.ts": "Matches localized window text.",
"README.md": "Presents translated project copy.",
"docs/data_preparation.md": "Includes multilingual data examples.",
"docs/voice-design.md": "Documents multilingual voice prompts.",
"docs/engines/omnivoice.md": "Documents engine vocabulary.",
"docs/superpowers/specs/2026-05-31-voice-gallery-design.md": "Preserves design examples.",
"examples/README.md": "Contains multilingual examples.",
"backend/services/segmentation.py": "CJK-aware segmentation rules.",
"backend/services/sentence_chunker.py": "CJK sentence-boundary logic.",
"electron/src/renderer/src/features/dub/dub-narration.ts": "Functional sentence-ending punctuation, not UI copy.",
"backend/services/subtitle_segmenter.py": "CJK subtitle segmentation.",
"backend/services/text_normalization.py": "CJK normalization patterns.",
"backend/core/http_headers.py": "Parses localized HTTP filenames.",
"electron/src/shared/utils/voiceInstruct.js": "CJK instruction vocabulary.",
"omnivoice/utils/text.py": "Core multilingual text processing.",
"backend/services/tts_backend.py": "Engine speaker vocabulary.",
"backend/core/personalities.py": "Model prompt vocabulary.",
"backend/core/archetypes.py": "Voice archetype vocabulary.",
"backend/core/describe_voice.py": "Voice-description vocabulary.",
"electron/src/shared/utils/constants.js": "Engine language constants.",
"omnivoice/models/omnivoice.py": "Model language tokens.",
"omnivoice/utils/duration.py": "CJK duration rules for character-based timing.",
"omnivoice/utils/voice_design.py": "Voice-design model vocabulary.",
"backend/migrations/versions/0007_rebuild_poisoned_design_instruct.py": "Migrates model prompts.",
"electron/src/shared/utils/errorDocsMap.ts": "Recognizes localized errors.",
"omnivoice/eval/wer/fleurs.py": "Multilingual evaluation data.",
"omnivoice/eval/wer/punctuations.lst": "Evaluation punctuation corpus.",
"omnivoice/cli/demo.py": "Multilingual demo content.",
"scripts/build_demos.sh": "Builds multilingual demos.",
"scripts/build_dub_demo.sh": "Builds localized dub samples.",
"scripts/dub_demo_scripts.json": "Stores multilingual demo scripts.",
"backend/assets/samples/demo/dubbing/dubbed_zh.srt": "Chinese demo subtitles.",
"backend/assets/samples/demo/dubbing/dubbed_ja.srt": "Japanese demo subtitles.",
"backend/assets/samples/demo/dubbing/manifest.json": "Multilingual demo metadata.",
}
def _is_allowed(rel: str) -> bool:
path = Path(rel)
basename = path.name
return (
rel in _ALLOWED_FILES
or rel.startswith(tuple(_ALLOWED_PREFIXES))
or ".test." in basename
or basename.startswith("test_")
or basename.endswith("_test.py")
or any(part in {"tests", "test"} for part in path.parts)
)
def _tracked_files() -> list[str]:
try:
result = subprocess.run(
["git", "ls-files", "-z"], cwd=_ROOT, capture_output=True,
check=True, timeout=30,
)
files = [item.decode() for item in result.stdout.split(b"\0") if item]
if files:
return files
except (OSError, subprocess.SubprocessError, UnicodeDecodeError):
pass
files = []
for root, dirs, names in os.walk(_ROOT):
dirs[:] = [name for name in dirs if name not in _SKIP_DIRECTORIES]
base = Path(root)
files.extend(str((base / name).relative_to(_ROOT)) for name in names)
return files
def test_no_hardcoded_cjk_outside_locales():
offenders: dict[str, list[tuple[int, str]]] = {}
for rel in _tracked_files():
path = _ROOT / rel
if _is_allowed(rel) or path.suffix.lower() in _SKIP_EXTENSIONS:
continue
try:
text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
hits = [
(number, line.strip()[:80])
for number, line in enumerate(text.splitlines(), 1)
if _CJK.search(line)
]
if hits:
offenders[rel] = hits
details = [
"Hardcoded CJK was found outside the translation layer.",
"Move user-facing strings into the locale JSON catalogs.",
"For functional CJK, add the path to _ALLOWED_FILES with a reason.",
]
for rel in sorted(offenders):
details.append(rel)
details.extend(f" L{line}: {snippet}" for line, snippet in offenders[rel][:3])
assert not offenders, "\n".join(details)
@pytest.mark.parametrize(
"path",
[
"electron/src/renderer/src/i18n/locales/zh-CN.json",
"widget.test.ts",
"test_widget.py",
"widget_test.py",
"pkg/tests/widget.py",
"pkg/test/widget.py",
],
)
def test_is_allowed_patterns(path):
assert _is_allowed(path)
# ── The allowlist itself ───────────────────────────────────────────────────
# Every entry is a path mapped to the reason it may hold functional CJK. The
# reason is what a reviewer reads when the entry is added or removed, so it has
# to exist, say something, and stay attached to a file that is still there.
_PLACEHOLDER_REASONS = {"todo", "tbd", "temp", "fixme", "n/a", "na", "xxx", "..."}
def _entries() -> dict[str, str]:
return {**_ALLOWED_FILES, **_ALLOWED_PREFIXES}
def test_every_allowlist_entry_carries_a_reason() -> None:
problems = []
for path, reason in _entries().items():
if not isinstance(reason, str) or len(reason.strip()) < 20:
problems.append(f"{path}: reason too short ({reason!r})")
elif reason.strip().lower().rstrip(".") in _PLACEHOLDER_REASONS:
problems.append(f"{path}: placeholder reason ({reason!r})")
elif not reason.strip().endswith("."):
problems.append(f"{path}: reason should be a sentence ({reason!r})")
assert not problems, "every allowlist entry needs a real reason:\n " + "\n ".join(problems)
def test_every_allowlist_entry_still_matches_the_tree() -> None:
"""An entry whose file is gone silently widens the allowlist."""
missing = []
for path in _ALLOWED_FILES:
if not (_ROOT / path).is_file():
missing.append(path)
for prefix in _ALLOWED_PREFIXES:
if not (_ROOT / prefix).is_dir():
missing.append(prefix)
assert not missing, (
"these allowlist entries no longer match a tracked file or directory; delete "
"them from tests/test_no_hardcoded_cjk.py:\n " + "\n ".join(missing)
)