mirror of
https://github.com/debpalash/VoiceStudio.git
synced 2026-12-04 01:18:16 +00:00
feat(dub): download the dubbing demo videos on demand (#4326)
* feat(dub): download the dubbing demo videos on demand * docs: changelog fragment for on-demand dub demo videos * fix(dub): ignore a stale initial status answer once Download starts * fix(dub): CI fixes for the demo card (docstring marker, structure counts, fake backend status route) * fix(dub): harden demo download (Windows paths, error detail, proxy errors, poll races) * fix(dub): poll demo download status one request at a time
This commit is contained in:
1 parent
467c503ccf
commit
23fb389892
57 files changed
+1173
-18
No files matched your search
@@ -702,6 +702,12 @@ test-only PR. Docker Hub overview edits still publish through the small
|
||||
(`backend/api/routers/community.py`); the voice-preview gallery's signed
|
||||
downloads from `omnivoice-gallery` GitHub Releases, only after it is turned
|
||||
on in Settings (`backend/services/gallery.py`).
|
||||
- **Dubbing demo videos, only when the user clicks Download** in the Dub
|
||||
demo card (owner-approved 2026-11-21): five ~10 MB clips, sha256- and
|
||||
size-pinned in `backend/assets/samples/demo/dubbing/demo_assets.json`, from
|
||||
the `dub-demo-v1` pre-release of `debpalash/omnivoice-gallery`
|
||||
(`backend/services/demo_assets.py`). Nothing is fetched at install or
|
||||
startup; offline, the card shows bundled poster stills.
|
||||
- **Packaged-app update checks** against GitHub Releases, and the background
|
||||
download of a found update from the same release (on by default; Settings
|
||||
→ Updates → Download updates automatically turns it off, so downloads wait
|
||||
|
||||
@@ -62,7 +62,7 @@ licence/catalog data. CLA, identity and secret checks remain enabled.
|
||||
## Change rules (see CLAUDE.md for full text)
|
||||
- Root-cause the class, not the instance; fail-before/pass-after regression test; smallest correct change.
|
||||
- Default behavior identical on macOS/Windows/Linux; platform-only features go behind explicit opt-in. Divergent default = P0.
|
||||
- Local-first: no new required network calls; any HF download gated on installed-ness or explicit user action; all synthetic audio through the `mark_synthetic` chokepoint. Sanctioned calls are listed in `.github/CONTRIBUTING.md` → Quality gates: user-started first-run setup (ffmpeg from GitHub `zackees/ffmpeg_bins`, the huggingface.co/hf-mirror.com reachability probe, `uv.lock`-pinned package downloads from their locked URLs or the chosen/auto-selected regional mirror incl. the parallel wheel prefetch, the Auto region's one-wheel PyPI vs Aliyun speed check, a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), HF model downloads), opening/enabling the galleries (jsDelivr manifest, GitHub Releases), packaged update checks, user-clicked yt-dlp updates from PyPI, user-selected Windows ROCm setup (owner-approved 2026-10-26, hash-pinned: `repo.radeon.com` and `stable.repo.amd.com/rocm/whl-next/` wheels, the OpenNMT/CTranslate2 GitHub release, and this repository's own HIP CTranslate2 release (2026-11-09)), user-clicked optional engine installs/repairs (owner-approved 2026-11-07: GitHub source (branch clone, then the reviewed commit or its archive, plus pinned helper-source archives), a uv-managed python-build-standalone Python when missing, PyPI or mirror packages, the matching `download.pytorch.org` CUDA/CPU/ROCm PyTorch build, HF weights at install or first use), consent-gated analytics, separately opted-in automatic failure reports to the Supermetry public events endpoint (owner-approved 2026-11-14; off by default, closed content-free `config/diagnostics.json` policy, withdrawal stops delivery and invalidates queued reports; no messages/logs/raw stacks/dumps), prefilled-URL bug reports, phone content reports sent from a result's Report sheet, the Pro licence check after a key is entered, and VoiceStudio Cloud sign-in/account calls (and settings sync once cloud sync is on) only after the user turns them on (off by default; switching off stops them at once). Owner-approved exception (2026-09-28): the public GitHub star count may refresh automatically every 20 minutes, without credentials/referrer or user content; offline use remains unaffected.
|
||||
- Local-first: no new required network calls; any HF download gated on installed-ness or explicit user action; all synthetic audio through the `mark_synthetic` chokepoint. Sanctioned calls are listed in `.github/CONTRIBUTING.md` → Quality gates: user-started first-run setup (ffmpeg from GitHub `zackees/ffmpeg_bins`, the huggingface.co/hf-mirror.com reachability probe, `uv.lock`-pinned package downloads from their locked URLs or the chosen/auto-selected regional mirror incl. the parallel wheel prefetch, the Auto region's one-wheel PyPI vs Aliyun speed check, a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), HF model downloads), opening/enabling the galleries (jsDelivr manifest, GitHub Releases), the dubbing demo videos only when the user clicks Download (sha256-pinned `omnivoice-gallery` GitHub Release assets, owner-approved 2026-11-21, `backend/services/demo_assets.py`), packaged update checks, user-clicked yt-dlp updates from PyPI, user-selected Windows ROCm setup (owner-approved 2026-10-26, hash-pinned: `repo.radeon.com` and `stable.repo.amd.com/rocm/whl-next/` wheels, the OpenNMT/CTranslate2 GitHub release, and this repository's own HIP CTranslate2 release (2026-11-09)), user-clicked optional engine installs/repairs (owner-approved 2026-11-07: GitHub source (branch clone, then the reviewed commit or its archive, plus pinned helper-source archives), a uv-managed python-build-standalone Python when missing, PyPI or mirror packages, the matching `download.pytorch.org` CUDA/CPU/ROCm PyTorch build, HF weights at install or first use), consent-gated analytics, separately opted-in automatic failure reports to the Supermetry public events endpoint (owner-approved 2026-11-14; off by default, closed content-free `config/diagnostics.json` policy, withdrawal stops delivery and invalidates queued reports; no messages/logs/raw stacks/dumps), prefilled-URL bug reports, phone content reports sent from a result's Report sheet, the Pro licence check after a key is entered, and VoiceStudio Cloud sign-in/account calls (and settings sync once cloud sync is on) only after the user turns them on (off by default; switching off stops them at once). Owner-approved exception (2026-09-28): the public GitHub star count may refresh automatically every 20 minutes, without credentials/referrer or user content; offline use remains unaffected.
|
||||
- Every user-facing string via i18n, present in ALL 21 `electron/src/renderer/src/i18n/locales/*.json` files (the catalog the app loads) with real translations; `tests/test_locale_parity.py` and Electron `locale:check` enforce it.
|
||||
- Docs-sync in the same PR. Changelog: one quiet one-liner per PR in `changelog.d/<PR#>.<type>.md` (not `CHANGELOG.md`), ending `(#N)` + `— thanks @user!` for community work; the release script folds fragments into Unreleased.
|
||||
- Tagged release announcements lead with the biggest user-visible change; redesigns need real UI screenshots and migrations need installer links and steps. Verify all contributor credits from the tag comparison and included PRs; list authors and bug reporters separately (see `docs/RELEASING.md`).
|
||||
|
||||
@@ -44,7 +44,7 @@ Everything else (new engines, fancy features) is downstream of "the thing instal
|
||||
- **Cross-platform parity**: Every fix must work on macOS (Apple Silicon; Intel Macs are limited to the app UI with a remote backend, as README.md and `docs/install/macos.md` document), Windows (x64), and Linux (AppImage + deb). No platform-only regressions; the cross-platform bug bash (PR #51) is the baseline.
|
||||
- **Default features must work on every platform (strict rule, 2026-05-20):** A feature that ships in default mode — out-of-the-box, no user customization, no opt-in toggle — must behave identically on macOS, Windows, and Linux. Platform-specific *implementation code* is allowed for OS APIs / shells / packaging, but the user-visible *default behavior* cannot diverge. Platform-only features (e.g., a macOS-only global shortcut, a Windows-only path picker) must go behind explicit user opt-in: Settings toggle, env var, or CLI flag. When a default doesn't work on a platform, that's a P0 bug — either fix it on the missing platform or move it behind opt-in. No third option. **This rule governs BEHAVIOUR, not PERFORMANCE** (clarified 2026-07-30, council): hardware acceleration is expected to vary by host — CUDA, MPS, DirectML, Triton availability and `torch.compile` are all host-dependent by design, and reading the rule to forbid that would forbid GPU support itself. An optimization that is skipped where it cannot work (missing Triton, an arch the wheel lacks, a path its toolchain cannot link) is NOT a parity violation; a *feature* the user can see and use on one OS but not another is.
|
||||
- **Backward-compatible project data**: Existing `omnivoice_data/` (user voices, projects, settings) must keep working without manual migration. Any DB schema change goes through alembic with a tested upgrade path.
|
||||
- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Manual bug reporting submits to GitHub Issues (prefilled-URL, from the user's own browser). Owner-approved exception (2026-11-14): automatic failure reports may use Supermetry after a separate explicit opt-in, off by default even for existing analytics users; follow `config/diagnostics.json` and `docs/electron-privacy.md`, with no user content, exception messages, logs, raw stacks or crash dumps. Withdrawal stops delivery and invalidates queued reports. Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in Supermetry (`https://app.supermetry.com`, public site id in `config/analytics.json`; replaced PostHog, owner decision 2026-11-08) with a **first-run consent prompt** — asked before runtime setup on a fresh install, two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — uses the public site id in `config/analytics.json` and shows the same consent ask, with `SUPERMETRY_SITE_ID` overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), the dependency install's download of the packages pinned in `uv.lock` from their locked URLs or the user's chosen/auto-selected regional mirror, including the parallel wheel prefetch (`electron/src/main/wheel-prefetch.ts`, owner-approved 2026-10-27), the Auto region's one-wheel files.pythonhosted.org vs mirrors.aliyun.com speed check (two small ranged requests, `electron/src/main/pypi-mirror.ts`), a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); packaged update checks against GitHub Releases and the background download of a found update from that same release (owner-approved 2026-11-09; on by default, Settings → Updates → Download updates automatically turns it off so downloads wait for the user) (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; opt-in Windows ROCm setup the user selects (owner-approved 2026-10-26, hash-pinned in `scripts/windows-rocm-recipe.json`): AMD's `repo.radeon.com` SDK/PyTorch wheels, AMD's `stable.repo.amd.com/rocm/whl-next/` PyTorch wheels (owner-approved 2026-11-09), the OpenNMT/CTranslate2 GitHub release archive, and the HIP CTranslate2 wheels this repository builds and publishes on its own GitHub Releases (owner-approved 2026-11-09); dependency repair for an existing Python the user selected (owner-approved 2026-11-09, `electron/src/main/ipc.ts`): `pip install` of the listed missing packages from PyPI, only after the user confirms the plan; optional engine installs and repairs the user clicks (owner-approved 2026-11-07, `backend/services/sidecar_install.py`): the engine's GitHub source (a shallow branch clone, then the reviewed commit or its source archive, plus pinned GitHub archives of helper sources such as CosyVoice's Matcha-TTS, PyWorld and World), a uv-managed Python from `astral-sh/python-build-standalone` (or the regional mirror) when its version is missing, its Python packages from PyPI or the user's chosen mirror, the host's PyTorch build from `download.pytorch.org` (CUDA or CPU; on Linux AMD, engines with ROCm support use the ROCm index for their Torch version, replaced by `OMNIVOICE_TORCH_INDEX`; uv may also resolve other packages from that index), and its Hugging Face weights where the install fetches them (others download weights on first use, as Hugging Face model downloads); `OMNIVOICE_TORCH_INDEX` replaces it), and its Hugging Face weights; phone content reports to `appapi.voicestudio.sh/v1/content-reports`, only when the user taps Send on a result's Report sheet (`mobile/contract/SPEC.md`); and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on, all stopped at once when switched off. Narrow owner-approved exception (2026-09-28): the GitHub Star badge may fetch the public repository star count when shown and refresh every 20 minutes whiLine truncated
|
||||
- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Manual bug reporting submits to GitHub Issues (prefilled-URL, from the user's own browser). Owner-approved exception (2026-11-14): automatic failure reports may use Supermetry after a separate explicit opt-in, off by default even for existing analytics users; follow `config/diagnostics.json` and `docs/electron-privacy.md`, with no user content, exception messages, logs, raw stacks or crash dumps. Withdrawal stops delivery and invalidates queued reports. Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in Supermetry (`https://app.supermetry.com`, public site id in `config/analytics.json`; replaced PostHog, owner decision 2026-11-08) with a **first-run consent prompt** — asked before runtime setup on a fresh install, two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — uses the public site id in `config/analytics.json` and shows the same consent ask, with `SUPERMETRY_SITE_ID` overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), the dependency install's download of the packages pinned in `uv.lock` from their locked URLs or the user's chosen/auto-selected regional mirror, including the parallel wheel prefetch (`electron/src/main/wheel-prefetch.ts`, owner-approved 2026-10-27), the Auto region's one-wheel files.pythonhosted.org vs mirrors.aliyun.com speed check (two small ranged requests, `electron/src/main/pypi-mirror.ts`), a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); the dubbing demo videos, only when the user clicks Download: sha256-pinned GitHub Release assets of `debpalash/omnivoice-gallery` (owner-approved 2026-11-21, `backend/services/demo_assets.py`); packaged update checks against GitHub Releases and the background download of a found update from that same release (owner-approved 2026-11-09; on by default, Settings → Updates → Download updates automatically turns it off so downloads wait for the user) (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; opt-in Windows ROCm setup the user selects (owner-approved 2026-10-26, hash-pinned in `scripts/windows-rocm-recipe.json`): AMD's `repo.radeon.com` SDK/PyTorch wheels, AMD's `stable.repo.amd.com/rocm/whl-next/` PyTorch wheels (owner-approved 2026-11-09), the OpenNMT/CTranslate2 GitHub release archive, and the HIP CTranslate2 wheels this repository builds and publishes on its own GitHub Releases (owner-approved 2026-11-09); dependency repair for an existing Python the user selected (owner-approved 2026-11-09, `electron/src/main/ipc.ts`): `pip install` of the listed missing packages from PyPI, only after the user confirms the plan; optional engine installs and repairs the user clicks (owner-approved 2026-11-07, `backend/services/sidecar_install.py`): the engine's GitHub source (a shallow branch clone, then the reviewed commit or its source archive, plus pinned GitHub archives of helper sources such as CosyVoice's Matcha-TTS, PyWorld and World), a uv-managed Python from `astral-sh/python-build-standalone` (or the regional mirror) when its version is missing, its Python packages from PyPI or the user's chosen mirror, the host's PyTorch build from `download.pytorch.org` (CUDA or CPU; on Linux AMD, engines with ROCm support use the ROCm index for their Torch version, replaced by `OMNIVOICE_TORCH_INDEX`; uv may also resolve other packages from that index), and its Hugging Face weights where the install fetches them (others download weights on first use, as Hugging Face model downloads); `OMNIVOICE_TORCH_INDEX` replaces it), and its Hugging Face weights; phone content reports to `appapi.voicestudio.sh/v1/content-reports`, only when the user taps Send on a result's Report sheet (`mobile/contract/SPEC.md`); and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on,Line truncated
|
||||
- **Beta release cadence (no RC, no ceremony — strict rule, 2026-05-20):** the current release line (0.5.x today) has **no release candidates, no 48h soak, no formal release ceremony**. Every fix goes continuous-to-main; the owner tags a patch from main whenever the current state is worth cutting. No `-rc` tags. No phased release. The one sanctioned prerelease is the opt-in **Beta channel** (owner-approved 2026-10-22): `vX.Y.Z-beta.N` tags cut from `main`, published as GitHub prereleases that never become `latest`, with their own `electron-beta-*` update feed and `:beta` Docker tag (see `docs/RELEASING.md` → Beta channel). It adds no soak, ceremony or side branch. No deferrals to a future minor or major version — every open issue and every open community PR gets absorbed into the current line or explicitly declined. Users follow `main` for previews; users wanting stable stay on the latest tagged release.
|
||||
<!-- GSD:project-end -->
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Dubbing demo videos: user-requested download and its status.
|
||||
|
||||
``POST /demo/dubbing/download`` is the only thing that ever starts an outbound
|
||||
call (``services/demo_assets.py``); ``GET /demo/dubbing/status`` reads local
|
||||
state only and works offline.
|
||||
"""
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from api.dependencies import require_admin, require_consumer
|
||||
from services import demo_assets
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/demo/dubbing/status", dependencies=[Depends(require_consumer)])
|
||||
def demo_dubbing_status():
|
||||
return demo_assets.status()
|
||||
|
||||
|
||||
@router.post("/demo/dubbing/download", dependencies=[Depends(require_admin)])
|
||||
async def demo_dubbing_download():
|
||||
return await demo_assets.start_download()
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"tag": "dub-demo-v1",
|
||||
"cache_dir": "dubbing-v1",
|
||||
"files": [
|
||||
{
|
||||
"name": "dubbed_es.mp4",
|
||||
"sha256": "b7e74d6c2eb77e37f1714cf08868fa318427585af725245da189474511bd0a5a",
|
||||
"bytes": 1996376,
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_es.src.wav",
|
||||
"sha256": "0d917cb05721906322d19cab94e1dbaae446f4e48ef5bdfed1ff0c6045906231",
|
||||
"bytes": 1210182,
|
||||
"kind": "dev"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_fr.mp4",
|
||||
"sha256": "ce6ae4c664d617e83d3a0a4d2ecbaeadaa1a78c2b62e504c691eb707c0a030d9",
|
||||
"bytes": 1929364,
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_fr.src.wav",
|
||||
"sha256": "1aac16b185f5fabfec60f3da4f429c51f3895af624bf14691878227a03fce45c",
|
||||
"bytes": 1323078,
|
||||
"kind": "dev"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_ja.mp4",
|
||||
"sha256": "a0978d2d8cf327938703a09ef5f79fe3053ca247743032b5628af1eb7bb469c7",
|
||||
"bytes": 2126117,
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_ja.src.wav",
|
||||
"sha256": "65a9708ef01c5ae2d2e5a0a28d93eec0974578886fea6c586244a4dd090c19ff",
|
||||
"bytes": 1460670,
|
||||
"kind": "dev"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_zh.mp4",
|
||||
"sha256": "a4f7a0e8a50c047283d2eb432ef1ab4ca5d60e522f13d52e7eb6fe469fe1e88f",
|
||||
"bytes": 2140741,
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "dubbed_zh.src.wav",
|
||||
"sha256": "9dada377a20c9b5b2b526208d37884d94d27c4ed16accd36eed08b117d6b5298",
|
||||
"bytes": 1164318,
|
||||
"kind": "dev"
|
||||
},
|
||||
{
|
||||
"name": "source.mp4",
|
||||
"sha256": "ba9895782bd6dac0bcc12f271af182d8b78bfad66b171e2453fd61ca18b473c5",
|
||||
"bytes": 1541262,
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "source.src.wav",
|
||||
"sha256": "9f6b19a20b59a21552465c7b958ee55fbcb7b0e9644d401b19c2ba7825f1e88f",
|
||||
"bytes": 1005558,
|
||||
"kind": "dev"
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 6.1 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
Binary file not shown.
Binary file not shown.
+6
-2
@@ -802,6 +802,7 @@ def _phase_a_build_inner() -> None:
|
||||
stories,
|
||||
setup,
|
||||
gallery,
|
||||
demo_assets as demo_assets_router,
|
||||
archetypes,
|
||||
describe_voice,
|
||||
community,
|
||||
@@ -833,7 +834,7 @@ def _phase_a_build_inner() -> None:
|
||||
_router_modules.extend([
|
||||
system, profiles, profile_images, exports, generation, voice_convert, sfx, dub_core, dub_generate,
|
||||
dub_export, dub_translate, projects, glossary, engines, tools,
|
||||
stories, setup, gallery, archetypes, describe_voice, community,
|
||||
stories, setup, gallery, demo_assets_router, archetypes, describe_voice, community,
|
||||
batch, watermark, events, capture, capture_ws, speech_platform, dictation,
|
||||
openai_compat, tts_stream, marketplace, personas, sonitranslate,
|
||||
audiobook, longform_jobs, pronunciation, settings_router,
|
||||
@@ -886,7 +887,10 @@ def _phase_a_finalize() -> None:
|
||||
# Bundled demo assets — read-only, ships with the app, no network.
|
||||
_demo_dir = os.path.join(os.path.dirname(__file__), "assets", "samples")
|
||||
if os.path.isdir(_demo_dir):
|
||||
app.mount("/demo_audio", SafeMediaFiles(directory=_demo_dir), name="demo_audio")
|
||||
from services.demo_assets import make_demo_mount
|
||||
|
||||
# Dub demo videos are not bundled: served from the on-demand cache.
|
||||
app.mount("/demo_audio", make_demo_mount(_demo_dir), name="demo_audio")
|
||||
|
||||
# SPA shell LAST so the "/" StaticFiles mount can't shadow any router.
|
||||
from core.spa_inject import (
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
"""On-demand dubbing demo videos.
|
||||
|
||||
The Dub workspace's demo card plays five short clips (an original and four
|
||||
dubs). They are ~10 MB, so they are not in the app bundle: the bundle carries
|
||||
only the manifest, the subtitles and one small poster still per clip, and the
|
||||
videos are fetched from a pinned pre-release of the ``omnivoice-gallery`` repo
|
||||
(tag ``dub-demo-v1``, one release asset per file, owner-approved 2026-11-21).
|
||||
``scripts/package_dub_demo.py`` produces those assets and the pinned table
|
||||
(``backend/assets/samples/demo/dubbing/demo_assets.json``) this module verifies
|
||||
against.
|
||||
|
||||
Consent:
|
||||
Nothing here runs at import or startup. The only network entry point is
|
||||
:func:`start_download`, which the user triggers with the Download button
|
||||
(``POST /demo/dubbing/download``). With it never pressed, or the network down,
|
||||
the card shows the posters and every other feature is untouched.
|
||||
|
||||
Integrity:
|
||||
Every file is pinned by sha256 and byte size in the committed table. A download
|
||||
is streamed to a temp file under a hard size cap (the pinned size), then size
|
||||
and hash are checked; only a file that passes is renamed into the cache. A
|
||||
wrong hash, a truncated body or an oversized body is deleted and never served.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from core.config import DATA_DIR
|
||||
|
||||
logger = logging.getLogger("omnivoice.demo_assets")
|
||||
|
||||
_TABLE_PATH = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "assets" / "samples" / "demo" / "dubbing" / "demo_assets.json"
|
||||
)
|
||||
|
||||
_BASE_URL_TEMPLATE = "https://github.com/debpalash/omnivoice-gallery/releases/download/{tag}"
|
||||
_HTTP_TIMEOUT_S = 30.0
|
||||
|
||||
#: Hard ceiling on any single response regardless of the table.
|
||||
MAX_FILE_BYTES = 16 << 20
|
||||
|
||||
|
||||
class DemoAssetError(RuntimeError):
|
||||
"""A download could not be accepted."""
|
||||
|
||||
|
||||
def _load_table() -> dict[str, Any]:
|
||||
return json.loads(_TABLE_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
_TABLE = _load_table()
|
||||
TAG: str = _TABLE["tag"]
|
||||
CACHE_SUBDIR: str = _TABLE["cache_dir"]
|
||||
|
||||
#: name -> {"sha256", "bytes"} for the files the Download button fetches.
|
||||
PINNED: dict[str, dict[str, Any]] = {
|
||||
f["name"]: f for f in _TABLE["files"] if f.get("kind") == "video"
|
||||
}
|
||||
#: Dev/test fixtures (source audio); pinned but never downloaded by the app.
|
||||
DEV_PINNED: dict[str, dict[str, Any]] = {
|
||||
f["name"]: f for f in _TABLE["files"] if f.get("kind") == "dev"
|
||||
}
|
||||
|
||||
|
||||
def base_url() -> str:
|
||||
"""Where the assets are published. Overridable for self-hosting and tests."""
|
||||
default = _BASE_URL_TEMPLATE.format(tag=TAG)
|
||||
return (os.environ.get("OMNIVOICE_DEMO_ASSETS_URL") or default).rstrip("/")
|
||||
|
||||
|
||||
def cache_dir() -> Path:
|
||||
return Path(DATA_DIR) / "demo_cache" / CACHE_SUBDIR
|
||||
|
||||
|
||||
def total_bytes() -> int:
|
||||
return sum(int(f["bytes"]) for f in PINNED.values())
|
||||
|
||||
|
||||
def cached_path(name: str) -> Optional[Path]:
|
||||
"""The cached file for a pinned *name*, or None.
|
||||
|
||||
Only names from the pinned table resolve, so a request can never name a path
|
||||
outside the cache. Presence plus exact size is checked here (hash was
|
||||
verified before the file was ever renamed into place).
|
||||
"""
|
||||
pin = PINNED.get(name)
|
||||
if pin is None:
|
||||
return None
|
||||
path = cache_dir() / name
|
||||
try:
|
||||
if path.is_file() and path.stat().st_size == int(pin["bytes"]):
|
||||
return path
|
||||
except OSError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _cached_names() -> list[str]:
|
||||
return [n for n in PINNED if cached_path(n) is not None]
|
||||
|
||||
|
||||
# ── Status ───────────────────────────────────────────────────────────────────
|
||||
|
||||
_state: dict[str, Any] = {"state": "idle", "downloaded_bytes": 0, "error": None}
|
||||
#: Strong references to background downloads (the loop only keeps weak ones).
|
||||
_tasks: set["asyncio.Task[Any]"] = set()
|
||||
|
||||
|
||||
def status() -> dict[str, Any]:
|
||||
"""Offline-safe: reads local state only, never touches the network."""
|
||||
cached = _cached_names()
|
||||
complete = len(cached) == len(PINNED)
|
||||
state = _state["state"]
|
||||
if state != "downloading":
|
||||
state = "ready" if complete else ("error" if _state["error"] else "idle")
|
||||
done = _state["downloaded_bytes"] if state == "downloading" else (
|
||||
total_bytes() if complete else sum(int(PINNED[n]["bytes"]) for n in cached)
|
||||
)
|
||||
return {
|
||||
"state": state,
|
||||
"total_bytes": total_bytes(),
|
||||
"downloaded_bytes": done,
|
||||
"files": {name: name in cached for name in PINNED},
|
||||
"error": _state["error"] if state == "error" else None,
|
||||
}
|
||||
|
||||
|
||||
# ── Download ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _client(client=None):
|
||||
if client is not None:
|
||||
return client
|
||||
from api.http_client import get_http_client
|
||||
|
||||
return get_http_client()
|
||||
|
||||
|
||||
async def _download_one(client, name: str, pin: dict[str, Any], on_chunk) -> None:
|
||||
"""Stream *name* to a temp file, verify, then atomically publish it."""
|
||||
import httpx
|
||||
|
||||
expected = int(pin["bytes"])
|
||||
limit = min(expected, MAX_FILE_BYTES)
|
||||
dest_dir = cache_dir()
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=str(dest_dir), prefix=".demo-", suffix=".part")
|
||||
digest = hashlib.sha256()
|
||||
total = 0
|
||||
published = False
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as fh:
|
||||
try:
|
||||
async with client.stream(
|
||||
"GET", f"{base_url()}/{name}", timeout=_HTTP_TIMEOUT_S,
|
||||
follow_redirects=True,
|
||||
) as response:
|
||||
if response.status_code != 200:
|
||||
raise DemoAssetError(f"HTTP {response.status_code}")
|
||||
async for chunk in response.aiter_bytes():
|
||||
total += len(chunk)
|
||||
if total > limit:
|
||||
raise DemoAssetError("response exceeded its size cap")
|
||||
digest.update(chunk)
|
||||
fh.write(chunk)
|
||||
on_chunk(len(chunk))
|
||||
except httpx.HTTPError as exc:
|
||||
raise DemoAssetError(f"transfer failed: {type(exc).__name__}") from exc
|
||||
fh.flush()
|
||||
os.fsync(fh.fileno())
|
||||
if total != expected:
|
||||
raise DemoAssetError("download was truncated")
|
||||
if digest.hexdigest() != str(pin["sha256"]).lower():
|
||||
raise DemoAssetError("sha256 mismatch")
|
||||
os.replace(tmp, dest_dir / name)
|
||||
published = True
|
||||
finally:
|
||||
# Runs for failures and cancellation alike; a half file is never kept.
|
||||
if not published:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
async def download_all(client=None) -> dict[str, Any]:
|
||||
"""Fetch every missing pinned file. All-or-nothing per file; resumable by rerun."""
|
||||
_state.update(state="downloading", error=None)
|
||||
try:
|
||||
client = _client(client)
|
||||
except Exception as exc: # noqa: BLE001 - e.g. ValueError for an unsupported proxy scheme
|
||||
logger.info("Demo video download client unavailable: %s", type(exc).__name__)
|
||||
_state.update(state="error", error="download client unavailable (check proxy settings)")
|
||||
return status()
|
||||
base = sum(int(PINNED[n]["bytes"]) for n in _cached_names())
|
||||
_state["downloaded_bytes"] = base
|
||||
|
||||
def on_chunk(n: int) -> None:
|
||||
_state["downloaded_bytes"] += n
|
||||
|
||||
try:
|
||||
for name, pin in PINNED.items():
|
||||
if cached_path(name) is not None:
|
||||
continue
|
||||
before = _state["downloaded_bytes"]
|
||||
try:
|
||||
await _download_one(client, name, pin, on_chunk)
|
||||
except (Exception, asyncio.CancelledError):
|
||||
_state["downloaded_bytes"] = before
|
||||
raise
|
||||
except asyncio.CancelledError:
|
||||
_state.update(state="idle")
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - reported through status()
|
||||
# Only fixed messages or the exception type: OS errors carry absolute paths.
|
||||
detail = str(exc) if isinstance(exc, DemoAssetError) else type(exc).__name__
|
||||
logger.info("Demo video download failed: %s", detail)
|
||||
_state.update(state="error", error=detail)
|
||||
else:
|
||||
_state.update(state="ready", error=None)
|
||||
return status()
|
||||
|
||||
|
||||
async def start_download() -> dict[str, Any]:
|
||||
"""Begin the user-requested download in the background (idempotent)."""
|
||||
if status()["state"] == "ready":
|
||||
return status()
|
||||
if not any(not t.done() for t in _tasks):
|
||||
_state.update(state="downloading", error=None)
|
||||
task = asyncio.create_task(download_all())
|
||||
_tasks.add(task)
|
||||
task.add_done_callback(_tasks.discard)
|
||||
return status()
|
||||
|
||||
|
||||
# ── Serving ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def make_demo_mount(directory: str):
|
||||
"""``/demo_audio`` mount: bundled files, with cached demo videos as fallback."""
|
||||
from core.safe_static import SafeMediaFiles
|
||||
|
||||
class DemoMediaFiles(SafeMediaFiles):
|
||||
async def get_response(self, path: str, scope):
|
||||
# Windows hands the static mount backslash-separated paths.
|
||||
norm = path.replace("\\", "/")
|
||||
prefix = "demo/dubbing/"
|
||||
if norm.startswith(prefix):
|
||||
# Only exact pinned names resolve, so no separator or ".." survives.
|
||||
name = norm[len(prefix):]
|
||||
cached = cached_path(name)
|
||||
if cached is not None:
|
||||
inner = SafeMediaFiles(directory=str(cached.parent), check_dir=False)
|
||||
return await inner.get_response(name, scope)
|
||||
return await super().get_response(path, scope)
|
||||
|
||||
return DemoMediaFiles(directory=directory)
|
||||
@@ -13,6 +13,7 @@ tracked speech demo renders, and assert the render constants did not regress.
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import soundfile as sf
|
||||
@@ -143,9 +144,17 @@ _SPEECH_FIXTURES = [
|
||||
|
||||
@pytest.mark.parametrize("fixture", _SPEECH_FIXTURES)
|
||||
def test_real_shipped_speech_clears_quality_floor(fixture):
|
||||
# These are existing tracked demo renders, not synthesized stand-ins or
|
||||
# asserted measurements. Loading PCM needs neither a model nor a network.
|
||||
audio, _sample_rate = sf.read(_SAMPLES / fixture, dtype="float32", always_2d=True)
|
||||
# These are existing demo renders, not synthesized stand-ins or asserted
|
||||
# measurements. Loading PCM needs neither a model nor a network.
|
||||
path = _SAMPLES / fixture
|
||||
if fixture.startswith("demo/dubbing/") and not path.is_file():
|
||||
# The dubbing source audio is a release asset (dub-demo-v1), not bundled;
|
||||
# point OMNIVOICE_DEMO_DEV_DIR at the unpacked assets to run these.
|
||||
dev_dir = os.environ.get("OMNIVOICE_DEMO_DEV_DIR")
|
||||
path = Path(dev_dir) / Path(fixture).name if dev_dir else path
|
||||
if not path.is_file():
|
||||
pytest.skip("dubbing source audio is not bundled; set OMNIVOICE_DEMO_DEV_DIR")
|
||||
audio, _sample_rate = sf.read(path, dtype="float32", always_2d=True)
|
||||
speech = torch.from_numpy(audio.T)
|
||||
flatness = arch._spectral_flatness(speech)
|
||||
assert flatness is not None
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
The Dub demo videos now download on demand (about 10 MB, only when you click Download) instead of shipping inside the app (#4326)
|
||||
+2
-2
@@ -32,13 +32,13 @@ VoiceStudio/
|
||||
│
|
||||
├── backend/ ⟵ FastAPI server
|
||||
│ ├── main.py sole process entry; its annotated startup sequence must retain its order
|
||||
│ ├── api/routers/ 45 routers, auto-included; HTTP/WS adaptation stays thin here
|
||||
│ ├── api/routers/ 46 routers, auto-included; HTTP/WS adaptation stays thin here
|
||||
│ │ └── setup/ setup-wizard endpoints and model acquisition
|
||||
│ ├── core/ shared infrastructure: configuration, persistence, job/event plumbing,
|
||||
│ │ auth and CSRF, safe paths, model artifact fingerprints, analytics consent,
|
||||
│ │ version and diagnostics
|
||||
│ │ └── asr_budget.py duration-based transcription budget shared with MCP
|
||||
│ ├── services/ 137 modules of business logic spanning speech, dubbing, DSP, GPU dispatch,
|
||||
│ ├── services/ 138 modules of business logic spanning speech, dubbing, DSP, GPU dispatch,
|
||||
│ │ engine selection and loaded-model ownership
|
||||
│ │ └── asr_timing.py inherited ASR execution clocks without media dependencies
|
||||
│ ├── engines/ per-engine adapters: audiocpp, confucius4, cosyvoice_gguf,
|
||||
|
||||
@@ -70,6 +70,9 @@ program makes, all started or consented to by the user, are listed in the
|
||||
- First-run setup the user starts: the pinned ffmpeg download from GitHub,
|
||||
Python and package downloads from their locked URLs or the chosen mirror,
|
||||
and Hugging Face model downloads.
|
||||
- The dubbing demo videos (~10 MB), only when the user clicks Download in
|
||||
the Dub demo card: sha256-pinned GitHub Release assets of
|
||||
`debpalash/omnivoice-gallery`.
|
||||
- Update checks of packaged builds against GitHub Releases, and the background
|
||||
download of a found update from that same release. Both are on by default
|
||||
(an owner-approved exception to the local-first rule). Settings, Updates,
|
||||
|
||||
@@ -18,6 +18,13 @@ const mocks = vi.hoisted(() => ({
|
||||
|
||||
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock('@/lib/api/client', () => ({ apiJson: mocks.api, apiPath: (path: string) => path }));
|
||||
vi.mock('@/components/ui/progress', () => ({
|
||||
Progress: ({ value, children }: Record<string, any>) => (
|
||||
<div role="progressbar" aria-valuenow={value}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
vi.mock('@/components/video-player', () => ({
|
||||
VideoPlayer: ({ controls, playerRef, onPlay, onPause, onCanPlay, source, src }: Record<string, any>) => {
|
||||
mocks.videoProps.push({ controls, source });
|
||||
@@ -88,8 +95,24 @@ afterEach(() => {
|
||||
mocks.videoProps.length = 0;
|
||||
});
|
||||
|
||||
type Status = { state: string; total_bytes: number; downloaded_bytes: number };
|
||||
const READY: Status = { state: 'ready', total_bytes: 100, downloaded_bytes: 100 };
|
||||
const IDLE: Status = { state: 'idle', total_bytes: 100, downloaded_bytes: 0 };
|
||||
|
||||
function route(status: Status | Error, download?: (init?: RequestInit) => Promise<Status>) {
|
||||
mocks.api.mockImplementation(async (path: string, init?: RequestInit) => {
|
||||
if (path.endsWith('/manifest.json')) return manifest;
|
||||
if (path === '/demo/dubbing/status') {
|
||||
if (status instanceof Error) throw status;
|
||||
return status;
|
||||
}
|
||||
if (path === '/demo/dubbing/download') return download!(init);
|
||||
throw new Error(`unexpected ${path}`);
|
||||
});
|
||||
}
|
||||
|
||||
function mount(onEdit = vi.fn()) {
|
||||
mocks.api.mockResolvedValue(manifest);
|
||||
route(READY);
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={onEdit} />);
|
||||
}
|
||||
|
||||
@@ -179,3 +202,131 @@ it('preserves the active dubbed position when its language source resets', async
|
||||
fireEvent.click(translated);
|
||||
expect(original.currentTime).toBe(9.5);
|
||||
});
|
||||
|
||||
it('shows posters and a download button, with no player, until the videos are cached', async () => {
|
||||
route(IDLE);
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'demo.dubbing_download' })).toBeTruthy();
|
||||
expect(mocks.videoProps).toHaveLength(0);
|
||||
const posters = document.querySelectorAll('img');
|
||||
expect(Array.from(posters).map((img) => img.getAttribute('src'))).toEqual([
|
||||
'/demo_audio/demo/dubbing/source.jpg',
|
||||
'/demo_audio/demo/dubbing/dubbed_es.jpg',
|
||||
]);
|
||||
expect(screen.queryByRole('button', { name: 'clone.edit Español' })).toBeNull();
|
||||
// Nothing is downloaded until the user asks.
|
||||
expect(mocks.api.mock.calls.some(([path]) => path === '/demo/dubbing/download')).toBe(false);
|
||||
});
|
||||
|
||||
it('plays and offers Edit immediately when the videos are already cached', async () => {
|
||||
mount();
|
||||
await screen.findByRole('button', { name: 'dubbing-demo-comparison-demo.original_tag' });
|
||||
expect(screen.queryByRole('button', { name: 'demo.dubbing_download' })).toBeNull();
|
||||
expect(document.querySelectorAll('img')).toHaveLength(0);
|
||||
expect(screen.getByRole('button', { name: 'clone.edit Español' })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('shows progress while downloading, then switches to the players', async () => {
|
||||
let release: (s: Status) => void = () => {};
|
||||
route(IDLE, () => new Promise<Status>((resolve) => { release = resolve; }));
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'demo.dubbing_download' }));
|
||||
const bar = await screen.findByRole('progressbar');
|
||||
expect(bar.getAttribute('aria-valuenow')).toBe('0');
|
||||
expect(mocks.videoProps).toHaveLength(0);
|
||||
|
||||
release(READY);
|
||||
await screen.findByRole('button', { name: 'dubbing-demo-comparison-demo.original_tag' });
|
||||
expect(screen.queryByRole('progressbar')).toBeNull();
|
||||
});
|
||||
|
||||
it('stays on the poster with a short message and a retry when the download fails', async () => {
|
||||
let attempt = 0;
|
||||
route(IDLE, async () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) throw new Error('offline');
|
||||
return READY;
|
||||
});
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'demo.dubbing_download' }));
|
||||
expect((await screen.findByRole('status')).textContent).toBe('demo.dubbing_download_failed');
|
||||
expect(mocks.videoProps).toHaveLength(0);
|
||||
expect(document.querySelectorAll('img')).toHaveLength(2);
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'demo.dubbing_retry' }));
|
||||
await screen.findByRole('button', { name: 'dubbing-demo-comparison-demo.original_tag' });
|
||||
});
|
||||
|
||||
it('keeps posters and the download button when the status call fails', async () => {
|
||||
route(new Error('backend down'));
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
expect(await screen.findByRole('button', { name: 'demo.dubbing_download' })).toBeTruthy();
|
||||
expect(mocks.videoProps).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('ignores a slow initial status answer that arrives after Download was clicked', async () => {
|
||||
let answerStatus: (s: Status) => void = () => {};
|
||||
let statusCalls = 0;
|
||||
mocks.api.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('/manifest.json')) return manifest;
|
||||
if (path === '/demo/dubbing/status') {
|
||||
statusCalls += 1;
|
||||
if (statusCalls === 1) return new Promise<Status>((resolve) => { answerStatus = resolve; });
|
||||
return READY;
|
||||
}
|
||||
return { state: 'downloading', total_bytes: 100, downloaded_bytes: 10 } satisfies Status;
|
||||
});
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
await screen.findByRole('textbox', {}, { timeout: 2000 }).catch(() => {});
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'demo.dubbing_download' }));
|
||||
await screen.findByRole('progressbar');
|
||||
answerStatus(IDLE);
|
||||
await Promise.resolve();
|
||||
expect(screen.getByRole('progressbar')).toBeTruthy();
|
||||
// Polling then reaches ready.
|
||||
await screen.findByRole('button', { name: 'dubbing-demo-comparison-demo.original_tag' }, { timeout: 3000 });
|
||||
});
|
||||
|
||||
it('does not let a status poll that raced ahead of the POST undo the downloading state', async () => {
|
||||
let releasePost: (s: Status) => void = () => {};
|
||||
mocks.api.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('/manifest.json')) return manifest;
|
||||
if (path === '/demo/dubbing/status') return IDLE;
|
||||
return new Promise<Status>((resolve) => { releasePost = resolve; });
|
||||
});
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'demo.dubbing_download' }));
|
||||
await screen.findByRole('progressbar');
|
||||
// Let at least one poll tick answer idle while the POST is still pending.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
expect(screen.getByRole('progressbar')).toBeTruthy();
|
||||
expect(screen.queryByRole('button', { name: 'demo.dubbing_download' })).toBeNull();
|
||||
|
||||
releasePost({ state: 'downloading', total_bytes: 100, downloaded_bytes: 50 });
|
||||
await screen.findByRole('progressbar');
|
||||
});
|
||||
|
||||
it('reaches ready when each status reply takes longer than the poll interval', async () => {
|
||||
let statusCalls = 0;
|
||||
mocks.api.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('/manifest.json')) return manifest;
|
||||
if (path === '/demo/dubbing/status') {
|
||||
statusCalls += 1;
|
||||
if (statusCalls === 1) return IDLE;
|
||||
await new Promise((resolve) => setTimeout(resolve, 900));
|
||||
return READY;
|
||||
}
|
||||
return { state: 'downloading', total_bytes: 100, downloaded_bytes: 10 } satisfies Status;
|
||||
});
|
||||
render(<DubbingDemo onDismiss={vi.fn()} onTry={vi.fn()} onEdit={vi.fn()} />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'demo.dubbing_download' }));
|
||||
await screen.findByRole('progressbar');
|
||||
await screen.findByRole('button', { name: 'dubbing-demo-comparison-demo.original_tag' }, { timeout: 4000 });
|
||||
// Never more than one status request outstanding: initial + one poll.
|
||||
expect(statusCalls).toBe(2);
|
||||
}, 10000);
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
DownloadIcon,
|
||||
FilmIcon,
|
||||
LoaderCircleIcon,
|
||||
PencilIcon,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
import type { MediaPlayerInstance } from '@/components/media-player';
|
||||
import { VideoPlayer } from '@/components/video-player';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { apiJson, apiPath } from '@/lib/api/client';
|
||||
@@ -33,6 +35,17 @@ interface DemoManifest {
|
||||
}
|
||||
|
||||
const DEMO_BASE = '/demo_audio/demo/dubbing';
|
||||
const POLL_MS = 700;
|
||||
|
||||
/** Mirrors GET /demo/dubbing/status (backend/services/demo_assets.py). */
|
||||
export interface DemoDownloadStatus {
|
||||
state: 'idle' | 'downloading' | 'ready' | 'error';
|
||||
total_bytes: number;
|
||||
downloaded_bytes: number;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
const poster = (video: string) => `${DEMO_BASE}/${video.replace(/\.mp4$/, '.jpg')}`;
|
||||
const PLAYBACK_GROUP = 'dubbing-demo-comparison';
|
||||
|
||||
interface EditableDemoVideo {
|
||||
@@ -52,6 +65,7 @@ export function DubbingDemo({
|
||||
const { t } = useTranslation();
|
||||
const [manifest, setManifest] = useState<DemoManifest | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [download, setDownload] = useState<DemoDownloadStatus | null>(null);
|
||||
const [language, setLanguage] = useState('es');
|
||||
const [synchronized, setSynchronized] = useState(true);
|
||||
const [scripts, setScripts] = useState<Record<string, string>>({});
|
||||
@@ -61,6 +75,9 @@ export function DubbingDemo({
|
||||
const mirroring = useRef(false);
|
||||
const activePlayer = useRef<MediaPlayerInstance | null>(null);
|
||||
const pendingDubbedPosition = useRef<number | null>(null);
|
||||
const initialStatus = useRef<AbortController | null>(null);
|
||||
const statusSeq = useRef(0);
|
||||
const postInFlight = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
@@ -70,6 +87,67 @@ export function DubbingDemo({
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
// Local state only (never touches the network), so it also works offline.
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
initialStatus.current = controller;
|
||||
void apiJson<DemoDownloadStatus>('/demo/dubbing/status', { signal: controller.signal })
|
||||
.then((next) => !controller.signal.aborted && setDownload(next))
|
||||
.catch(() => {});
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
const downloading = download?.state === 'downloading';
|
||||
useEffect(() => {
|
||||
if (!downloading) return;
|
||||
let cancelled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
// One status request at a time: the next poll is scheduled when the current one
|
||||
// settles, so a slow reply is never superseded (and dropped) by its own successor.
|
||||
const poll = () => {
|
||||
// A reply counts only if the POST has not started/settled since it was sent
|
||||
// and the effect is still live: a read that raced ahead of the POST says idle.
|
||||
const id = ++statusSeq.current;
|
||||
const current = () => !cancelled && id === statusSeq.current && !postInFlight.current;
|
||||
void apiJson<DemoDownloadStatus>('/demo/dubbing/status')
|
||||
.then((next) => current() && setDownload(next))
|
||||
.catch(() => current() && setDownload((cur) => (cur ? { ...cur, state: 'error' } : cur)))
|
||||
.finally(() => {
|
||||
if (!cancelled) timer = setTimeout(poll, POLL_MS);
|
||||
});
|
||||
};
|
||||
timer = setTimeout(poll, POLL_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [downloading]);
|
||||
|
||||
const startDownload = () => {
|
||||
// A slow initial status answer must not overwrite the newer download state.
|
||||
initialStatus.current?.abort();
|
||||
setDownload((cur) => ({
|
||||
total_bytes: cur?.total_bytes ?? 0,
|
||||
downloaded_bytes: 0,
|
||||
state: 'downloading',
|
||||
}));
|
||||
postInFlight.current = true;
|
||||
statusSeq.current++;
|
||||
void apiJson<DemoDownloadStatus>('/demo/dubbing/download', { method: 'POST' })
|
||||
.then(setDownload)
|
||||
.catch(() =>
|
||||
setDownload((cur) => ({
|
||||
total_bytes: cur?.total_bytes ?? 0,
|
||||
downloaded_bytes: 0,
|
||||
state: 'error',
|
||||
})),
|
||||
)
|
||||
.finally(() => {
|
||||
postInFlight.current = false;
|
||||
statusSeq.current++; // polls issued before the POST settled are stale
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void sourcePlayer.current?.pause().catch(() => {});
|
||||
void dubbedPlayer.current?.pause().catch(() => {});
|
||||
@@ -84,6 +162,10 @@ export function DubbingDemo({
|
||||
</div>
|
||||
);
|
||||
|
||||
const ready = download?.state === 'ready';
|
||||
const percent = download?.total_bytes
|
||||
? Math.min(100, Math.round((download.downloaded_bytes / download.total_bytes) * 100))
|
||||
: 0;
|
||||
const dubbed = manifest.dubbed.find((item) => item.code === language) || manifest.dubbed[0];
|
||||
if (!dubbed) return null;
|
||||
|
||||
@@ -145,7 +227,7 @@ export function DubbingDemo({
|
||||
<RotateCcwIcon />
|
||||
</Button>
|
||||
)}
|
||||
{editableVideo && (
|
||||
{ready && editableVideo && (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
@@ -170,6 +252,14 @@ export function DubbingDemo({
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-2.5">
|
||||
{!ready ? (
|
||||
<img
|
||||
src={apiPath(poster(video))}
|
||||
alt=""
|
||||
draggable={false}
|
||||
className="aspect-video w-full rounded-lg bg-muted/30 object-cover"
|
||||
/>
|
||||
) : (
|
||||
<VideoPlayer
|
||||
playerRef={player}
|
||||
controls="compact"
|
||||
@@ -197,6 +287,7 @@ export function DubbingDemo({
|
||||
}}
|
||||
onSeeked={() => synchronizePosition(player.current, peer.current)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<label className="sr-only" htmlFor={`dubbing-demo-script-${code}`}>
|
||||
{label} — {t('dub.transcript')}
|
||||
@@ -274,6 +365,29 @@ export function DubbingDemo({
|
||||
<Switch checked={synchronized} onCheckedChange={setSynchronized} />
|
||||
</label>
|
||||
</div>
|
||||
{!ready && (
|
||||
<div className="flex flex-wrap items-center gap-2.5 rounded-xl border border-border/45 bg-background/30 p-2.5 text-xs">
|
||||
{downloading ? (
|
||||
<Progress value={percent} aria-label={t('demo.dubbing_downloading')} className="flex-1">
|
||||
<span className="text-muted-foreground">
|
||||
{t('demo.dubbing_downloading')} {percent}%
|
||||
</span>
|
||||
</Progress>
|
||||
) : (
|
||||
<>
|
||||
<Button size="sm" onClick={startDownload}>
|
||||
{download?.state === 'error' ? <RotateCcwIcon /> : <DownloadIcon />}
|
||||
{download?.state === 'error' ? t('demo.dubbing_retry') : t('demo.dubbing_download')}
|
||||
</Button>
|
||||
{download?.state === 'error' && (
|
||||
<span role="status" className="text-muted-foreground">
|
||||
{t('demo.dubbing_download_failed')}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-3 min-[1100px]:grid-cols-2">
|
||||
{card(
|
||||
'A',
|
||||
|
||||
@@ -2299,6 +2299,10 @@
|
||||
"dubbing_cta": "قم بتشغيل هذا على الفيديو الخاص بك →",
|
||||
"dubbing_loading": "جارٍ تحميل العرض التوضيحي للدبلجة...",
|
||||
"dubbing_dismiss": "رفض الدبلجة التجريبية",
|
||||
"dubbing_download": "تنزيل فيديوهات العرض (~10 ميغابايت)",
|
||||
"dubbing_downloading": "جارٍ التنزيل…",
|
||||
"dubbing_download_failed": "فشل التنزيل. تحقق من اتصالك.",
|
||||
"dubbing_retry": "إعادة المحاولة",
|
||||
"original_tag": "original",
|
||||
"dubbed_tag": "يطلق عليها اسم",
|
||||
"script_conversational": "محادثة",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Führen Sie dies in Ihrem eigenen Video aus →",
|
||||
"dubbing_loading": "Synchronisationsdemo wird geladen…",
|
||||
"dubbing_dismiss": "Synchronisationsdemo schließen",
|
||||
"dubbing_download": "Demovideos herunterladen (~10 MB)",
|
||||
"dubbing_downloading": "Wird heruntergeladen…",
|
||||
"dubbing_download_failed": "Download fehlgeschlagen. Prüfe deine Verbindung.",
|
||||
"dubbing_retry": "Erneut versuchen",
|
||||
"original_tag": "Original",
|
||||
"dubbed_tag": "synchronisiert",
|
||||
"script_conversational": "Konversation",
|
||||
|
||||
@@ -2338,6 +2338,10 @@
|
||||
"dubbing_cta": "Run this on your own video →",
|
||||
"dubbing_loading": "Loading dubbing demo…",
|
||||
"dubbing_dismiss": "Dismiss dubbing demo",
|
||||
"dubbing_download": "Download demo videos (~10 MB)",
|
||||
"dubbing_downloading": "Downloading…",
|
||||
"dubbing_download_failed": "Download failed. Check your connection.",
|
||||
"dubbing_retry": "Retry",
|
||||
"original_tag": "original",
|
||||
"dubbed_tag": "dubbed",
|
||||
"script_conversational": "Conversational",
|
||||
|
||||
@@ -2253,6 +2253,10 @@
|
||||
"dubbing_cta": "Ejecute esto en su propio video →",
|
||||
"dubbing_loading": "Cargando demostración de doblaje…",
|
||||
"dubbing_dismiss": "Descartar demostración de doblaje",
|
||||
"dubbing_download": "Descargar vídeos de demostración (~10 MB)",
|
||||
"dubbing_downloading": "Descargando…",
|
||||
"dubbing_download_failed": "La descarga falló. Revisa tu conexión.",
|
||||
"dubbing_retry": "Reintentar",
|
||||
"original_tag": "originales",
|
||||
"dubbed_tag": "apodado",
|
||||
"script_conversational": "conversacional",
|
||||
|
||||
@@ -2253,6 +2253,10 @@
|
||||
"dubbing_cta": "Exécutez ceci sur votre propre vidéo →",
|
||||
"dubbing_loading": "Chargement de la démo de doublage…",
|
||||
"dubbing_dismiss": "Ignorer la démo de doublage",
|
||||
"dubbing_download": "Télécharger les vidéos de démo (~10 Mo)",
|
||||
"dubbing_downloading": "Téléchargement…",
|
||||
"dubbing_download_failed": "Échec du téléchargement. Vérifiez votre connexion.",
|
||||
"dubbing_retry": "Réessayer",
|
||||
"original_tag": "originale",
|
||||
"dubbed_tag": "doublé",
|
||||
"script_conversational": "Conversationnel",
|
||||
|
||||
@@ -2338,6 +2338,10 @@
|
||||
"dubbing_cta": "Executa isto no teu propio vídeo →",
|
||||
"dubbing_loading": "Cargando demostración de dobraxe…",
|
||||
"dubbing_dismiss": "Rexeitar a demostración de dobraxe",
|
||||
"dubbing_download": "Descargar vídeos de demostración (~10 MB)",
|
||||
"dubbing_downloading": "Descargando…",
|
||||
"dubbing_download_failed": "A descarga fallou. Comproba a túa conexión.",
|
||||
"dubbing_retry": "Reintentar",
|
||||
"original_tag": "orixinal",
|
||||
"dubbed_tag": "dobrado",
|
||||
"script_conversational": "Conversacional",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "इसे अपने वीडियो पर चलाएँ →",
|
||||
"dubbing_loading": "डबिंग डेमो लोड हो रहा है...",
|
||||
"dubbing_dismiss": "डबिंग डेमो ख़ारिज करें",
|
||||
"dubbing_download": "डेमो वीडियो डाउनलोड करें (~10 MB)",
|
||||
"dubbing_downloading": "डाउनलोड हो रहा है…",
|
||||
"dubbing_download_failed": "डाउनलोड विफल रहा। अपना कनेक्शन जाँचें।",
|
||||
"dubbing_retry": "फिर कोशिश करें",
|
||||
"original_tag": "मौलिक",
|
||||
"dubbed_tag": "डब किया गया",
|
||||
"script_conversational": "संवादात्मक",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Jalankan ini di video Anda sendiri →",
|
||||
"dubbing_loading": "Memuat demo sulih suara…",
|
||||
"dubbing_dismiss": "Tolak demo sulih suara",
|
||||
"dubbing_download": "Unduh video demo (~10 MB)",
|
||||
"dubbing_downloading": "Mengunduh…",
|
||||
"dubbing_download_failed": "Unduhan gagal. Periksa koneksi Anda.",
|
||||
"dubbing_retry": "Coba lagi",
|
||||
"original_tag": "asli",
|
||||
"dubbed_tag": "dijuluki",
|
||||
"script_conversational": "Percakapan",
|
||||
|
||||
@@ -2253,6 +2253,10 @@
|
||||
"dubbing_cta": "Eseguilo sul tuo video →",
|
||||
"dubbing_loading": "Caricamento demo del doppiaggio…",
|
||||
"dubbing_dismiss": "Ignora la demo del doppiaggio",
|
||||
"dubbing_download": "Scarica i video demo (~10 MB)",
|
||||
"dubbing_downloading": "Download in corso…",
|
||||
"dubbing_download_failed": "Download non riuscito. Controlla la connessione.",
|
||||
"dubbing_retry": "Riprova",
|
||||
"original_tag": "originale",
|
||||
"dubbed_tag": "doppiato",
|
||||
"script_conversational": "Conversazionale",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "これを自分のビデオで実行します→",
|
||||
"dubbing_loading": "ダビングデモを読み込み中…",
|
||||
"dubbing_dismiss": "ダビングデモを閉じる",
|
||||
"dubbing_download": "デモ動画をダウンロード(約10 MB)",
|
||||
"dubbing_downloading": "ダウンロード中…",
|
||||
"dubbing_download_failed": "ダウンロードに失敗しました。接続を確認してください。",
|
||||
"dubbing_retry": "再試行",
|
||||
"original_tag": "オリジナル",
|
||||
"dubbed_tag": "吹き替えられた",
|
||||
"script_conversational": "会話型",
|
||||
|
||||
@@ -2250,6 +2250,10 @@
|
||||
"dubbing_cta": "자신의 비디오에서 이것을 실행 →",
|
||||
"dubbing_loading": "더빙 데모 로드 중…",
|
||||
"dubbing_dismiss": "더빙 데모 닫기",
|
||||
"dubbing_download": "데모 영상 다운로드 (~10 MB)",
|
||||
"dubbing_downloading": "다운로드 중…",
|
||||
"dubbing_download_failed": "다운로드에 실패했습니다. 연결을 확인하세요.",
|
||||
"dubbing_retry": "다시 시도",
|
||||
"original_tag": "원본",
|
||||
"dubbed_tag": "더빙된",
|
||||
"script_conversational": "대화",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Voer dit uit op uw eigen video →",
|
||||
"dubbing_loading": "Dubdemo laden…",
|
||||
"dubbing_dismiss": "Nasynchronisatiedemo sluiten",
|
||||
"dubbing_download": "Demovideo's downloaden (~10 MB)",
|
||||
"dubbing_downloading": "Downloaden…",
|
||||
"dubbing_download_failed": "Downloaden mislukt. Controleer je verbinding.",
|
||||
"dubbing_retry": "Opnieuw proberen",
|
||||
"original_tag": "origineel",
|
||||
"dubbed_tag": "nagesynchroniseerd",
|
||||
"script_conversational": "Gemoedelijk",
|
||||
|
||||
@@ -2275,6 +2275,10 @@
|
||||
"dubbing_cta": "Uruchom to na swoim własnym filmie →",
|
||||
"dubbing_loading": "Ładowanie wersji demonstracyjnej kopiowania…",
|
||||
"dubbing_dismiss": "Zamknij demonstrację dubbingu",
|
||||
"dubbing_download": "Pobierz filmy demonstracyjne (~10 MB)",
|
||||
"dubbing_downloading": "Pobieranie…",
|
||||
"dubbing_download_failed": "Pobieranie nie powiodło się. Sprawdź połączenie.",
|
||||
"dubbing_retry": "Spróbuj ponownie",
|
||||
"original_tag": "oryginał",
|
||||
"dubbed_tag": "dubbingowany",
|
||||
"script_conversational": "Konwersacyjny",
|
||||
|
||||
@@ -2253,6 +2253,10 @@
|
||||
"dubbing_cta": "Execute isso em seu próprio vídeo →",
|
||||
"dubbing_loading": "Carregando demonstração de dublagem…",
|
||||
"dubbing_dismiss": "Ignorar demonstração de dublagem",
|
||||
"dubbing_download": "Baixar vídeos de demonstração (~10 MB)",
|
||||
"dubbing_downloading": "Baixando…",
|
||||
"dubbing_download_failed": "O download falhou. Verifique sua conexão.",
|
||||
"dubbing_retry": "Tentar novamente",
|
||||
"original_tag": "originais",
|
||||
"dubbed_tag": "dublado",
|
||||
"script_conversational": "Conversacional",
|
||||
|
||||
@@ -2275,6 +2275,10 @@
|
||||
"dubbing_cta": "Запустите это на своем собственном видео →",
|
||||
"dubbing_loading": "Загрузка демо-версии дубляжа…",
|
||||
"dubbing_dismiss": "Закрыть демонстрационный вариант дубляжа",
|
||||
"dubbing_download": "Скачать демо-видео (~10 МБ)",
|
||||
"dubbing_downloading": "Загрузка…",
|
||||
"dubbing_download_failed": "Не удалось скачать. Проверьте подключение.",
|
||||
"dubbing_retry": "Повторить",
|
||||
"original_tag": "оригинальный",
|
||||
"dubbed_tag": "дублированный",
|
||||
"script_conversational": "Разговорный",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Kör detta på din egen video →",
|
||||
"dubbing_loading": "Laddar dubbningsdemo...",
|
||||
"dubbing_dismiss": "Avvisa dubbningsdemon",
|
||||
"dubbing_download": "Ladda ner demovideor (~10 MB)",
|
||||
"dubbing_downloading": "Laddar ner…",
|
||||
"dubbing_download_failed": "Nedladdningen misslyckades. Kontrollera anslutningen.",
|
||||
"dubbing_retry": "Försök igen",
|
||||
"original_tag": "original",
|
||||
"dubbed_tag": "dubbat",
|
||||
"script_conversational": "Konversation",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "เรียกใช้สิ่งนี้ในวิดีโอของคุณเอง →",
|
||||
"dubbing_loading": "กำลังโหลดการสาธิตการพากย์...",
|
||||
"dubbing_dismiss": "ยกเลิกการสาธิตการพากย์เสียง",
|
||||
"dubbing_download": "ดาวน์โหลดวิดีโอตัวอย่าง (~10 MB)",
|
||||
"dubbing_downloading": "กำลังดาวน์โหลด…",
|
||||
"dubbing_download_failed": "ดาวน์โหลดไม่สำเร็จ ตรวจสอบการเชื่อมต่อของคุณ",
|
||||
"dubbing_retry": "ลองอีกครั้ง",
|
||||
"original_tag": "ต้นฉบับ",
|
||||
"dubbed_tag": "ขนานนาม",
|
||||
"script_conversational": "การสนทนา",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Bunu kendi videonuzda çalıştırın →",
|
||||
"dubbing_loading": "Dublaj demosu yükleniyor…",
|
||||
"dubbing_dismiss": "Dublaj demosunu kapat",
|
||||
"dubbing_download": "Demo videolarını indir (~10 MB)",
|
||||
"dubbing_downloading": "İndiriliyor…",
|
||||
"dubbing_download_failed": "İndirme başarısız. Bağlantınızı kontrol edin.",
|
||||
"dubbing_retry": "Yeniden dene",
|
||||
"original_tag": "orijinal",
|
||||
"dubbed_tag": "dublajlı",
|
||||
"script_conversational": "konuşkan",
|
||||
|
||||
@@ -2275,6 +2275,10 @@
|
||||
"dubbing_cta": "Запустіть це на власному відео →",
|
||||
"dubbing_loading": "Завантаження демонстрації дубляжу…",
|
||||
"dubbing_dismiss": "Закрити демонстрацію дубляжу",
|
||||
"dubbing_download": "Завантажити демо-відео (~10 МБ)",
|
||||
"dubbing_downloading": "Завантаження…",
|
||||
"dubbing_download_failed": "Не вдалося завантажити. Перевірте з'єднання.",
|
||||
"dubbing_retry": "Повторити",
|
||||
"original_tag": "оригінальний",
|
||||
"dubbed_tag": "дубльований",
|
||||
"script_conversational": "Розмовний",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "Chạy cái này trên video của riêng bạn →",
|
||||
"dubbing_loading": "Đang tải bản demo lồng tiếng…",
|
||||
"dubbing_dismiss": "Loại bỏ bản demo lồng tiếng",
|
||||
"dubbing_download": "Tải video demo (~10 MB)",
|
||||
"dubbing_downloading": "Đang tải xuống…",
|
||||
"dubbing_download_failed": "Tải xuống thất bại. Hãy kiểm tra kết nối.",
|
||||
"dubbing_retry": "Thử lại",
|
||||
"original_tag": "nguyên bản",
|
||||
"dubbed_tag": "được mệnh danh là",
|
||||
"script_conversational": "đàm thoại",
|
||||
|
||||
@@ -2238,6 +2238,10 @@
|
||||
"dubbing_sync": "同步播放位置",
|
||||
"dubbing_loading": "正在加载配音演示...",
|
||||
"dubbing_dismiss": "关闭配音演示",
|
||||
"dubbing_download": "下载演示视频(约 10 MB)",
|
||||
"dubbing_downloading": "正在下载…",
|
||||
"dubbing_download_failed": "下载失败,请检查网络连接。",
|
||||
"dubbing_retry": "重试",
|
||||
"original_tag": "原创",
|
||||
"dubbed_tag": "配音",
|
||||
"script_conversational": "会话型",
|
||||
|
||||
@@ -2251,6 +2251,10 @@
|
||||
"dubbing_cta": "在您自己的影片上運行此→",
|
||||
"dubbing_loading": "正在載入配音演示...",
|
||||
"dubbing_dismiss": "關閉配音演示",
|
||||
"dubbing_download": "下載示範影片(約 10 MB)",
|
||||
"dubbing_downloading": "下載中…",
|
||||
"dubbing_download_failed": "下載失敗,請檢查網路連線。",
|
||||
"dubbing_retry": "重試",
|
||||
"original_tag": "原創",
|
||||
"dubbed_tag": "配音",
|
||||
"script_conversational": "會話型",
|
||||
|
||||
@@ -277,6 +277,7 @@ export const DEFAULT_FIXTURES = {
|
||||
source: { code: 'en', label: 'English', video: 'source.mp4', script: 'source.txt' },
|
||||
dubbed: [],
|
||||
},
|
||||
'/demo/dubbing/status': { state: 'idle', total_bytes: 0, downloaded_bytes: 0, files: {}, error: null },
|
||||
'/openapi.json': {},
|
||||
'/stats/usage': {},
|
||||
'/sysinfo': {
|
||||
|
||||
@@ -11341,6 +11341,38 @@
|
||||
"summary": "Convert Speech"
|
||||
}
|
||||
},
|
||||
"/demo/dubbing/download": {
|
||||
"post": {
|
||||
"operationId": "demo_dubbing_download_demo_dubbing_download_post",
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
}
|
||||
},
|
||||
"summary": "Demo Dubbing Download"
|
||||
}
|
||||
},
|
||||
"/demo/dubbing/status": {
|
||||
"get": {
|
||||
"operationId": "demo_dubbing_status_demo_dubbing_status_get",
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {}
|
||||
}
|
||||
},
|
||||
"description": "Successful Response"
|
||||
}
|
||||
},
|
||||
"summary": "Demo Dubbing Status"
|
||||
}
|
||||
},
|
||||
"/design/describe": {
|
||||
"post": {
|
||||
"description": "Parse a free-text description into design attrs + a validator-safe instruct.\n\nResponse shape::\n\n {\n \"attrs\": {\"Gender\": \"female\", \"Age\": \"elderly\", ... or \"Auto\"},\n \"instruct\": \"female, elderly, low pitch, british accent\",\n \"matched\": [{\"category\": \"Age\", \"token\": \"elderly\", \"phrase\": \"elderly\"}, ...],\n \"unmatched\": [\"slightly raspy\"]\n }",
|
||||
|
||||
@@ -13,8 +13,12 @@
|
||||
# *.srt transcripts for each
|
||||
# manifest.json single source of truth the frontend reads
|
||||
#
|
||||
# Bundle target: ~5 MB per mp4 × 5 files = ~25 MB. Well under the 45 MB
|
||||
# cap from the dubbing-demo design spec.
|
||||
# The mp4 files are NOT committed: the app downloads them on demand from the
|
||||
# omnivoice-gallery `dub-demo-v1` release (backend/services/demo_assets.py).
|
||||
# After rebuilding, run scripts/package_dub_demo.py --out <dir> --table
|
||||
# backend/assets/samples/demo/dubbing/demo_assets.json --posters
|
||||
# backend/assets/samples/demo/dubbing, upload <dir>, and commit the table and
|
||||
# posters (not the mp4/wav files). Bump the tag in package_dub_demo.py first.
|
||||
|
||||
set -e
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package the dubbing demo payload for upload as GitHub Release assets.
|
||||
|
||||
The demo videos and source audio are not bundled with the app; they are
|
||||
fetched on demand (``backend/services/demo_assets.py``) from a pre-release of
|
||||
``debpalash/omnivoice-gallery`` tagged ``dub-demo-v1``. This script turns a
|
||||
directory of rendered demo files (the output of ``build_dub_demo.sh``) into:
|
||||
|
||||
* one release asset per mp4 / ``.src.wav`` plus a ``SHA256SUMS`` file in --out;
|
||||
* optionally (--table) the pinned ``demo_assets.json`` the app verifies against;
|
||||
* optionally (--posters) a small jpg still per clip, committed with the app so
|
||||
the card has an offline fallback.
|
||||
|
||||
Nothing is uploaded; the maintainer uploads the files in --out:
|
||||
|
||||
gh release create dub-demo-v1 --repo debpalash/omnivoice-gallery \
|
||||
--prerelease --title "Dubbing demo v1" /tmp/dub-demo-v1/*
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_SRC = REPO / "backend" / "assets" / "samples" / "demo" / "dubbing"
|
||||
TAG = "dub-demo-v1"
|
||||
CACHE_DIR = "dubbing-v1"
|
||||
POSTER_WIDTH = 480
|
||||
|
||||
|
||||
def sha256_of(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def payload_files(src: Path) -> list[Path]:
|
||||
return sorted([*src.glob("*.mp4"), *src.glob("*.src.wav")], key=lambda p: p.name)
|
||||
|
||||
|
||||
def make_poster(video: Path, dest: Path) -> None:
|
||||
"""One frame ~3s in, scaled down, quality lowered until it is under 40 KB."""
|
||||
for quality in (6, 8, 11, 14, 18, 24):
|
||||
subprocess.run(
|
||||
["ffmpeg", "-y", "-loglevel", "error", "-ss", "3", "-i", str(video),
|
||||
"-frames:v", "1", "-vf", f"scale={POSTER_WIDTH}:-2",
|
||||
"-q:v", str(quality), str(dest)],
|
||||
check=True,
|
||||
)
|
||||
if dest.stat().st_size < 40_000:
|
||||
return
|
||||
raise SystemExit(f"could not get {dest.name} under 40 KB")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--src", type=Path, default=DEFAULT_SRC, help="directory holding the rendered demo files")
|
||||
ap.add_argument("--out", type=Path, required=True, help="output directory for the release assets")
|
||||
ap.add_argument("--table", type=Path, help="write the pinned demo_assets.json here")
|
||||
ap.add_argument("--posters", type=Path, help="write <name>.jpg stills here")
|
||||
args = ap.parse_args()
|
||||
|
||||
files = payload_files(args.src)
|
||||
if not files:
|
||||
print(f"no mp4/.src.wav files in {args.src}", file=sys.stderr)
|
||||
return 1
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
entries = []
|
||||
for path in files:
|
||||
dest = args.out / path.name
|
||||
if path.resolve() != dest.resolve():
|
||||
shutil.copyfile(path, dest)
|
||||
entries.append({
|
||||
"name": path.name,
|
||||
"sha256": sha256_of(dest),
|
||||
"bytes": dest.stat().st_size,
|
||||
# Videos are what the Download button fetches; the .src.wav files
|
||||
# are dev/test fixtures only and are never downloaded by the app.
|
||||
"kind": "video" if path.suffix == ".mp4" else "dev",
|
||||
})
|
||||
if args.posters and path.suffix == ".mp4":
|
||||
args.posters.mkdir(parents=True, exist_ok=True)
|
||||
make_poster(path, args.posters / f"{path.stem}.jpg")
|
||||
(args.out / "SHA256SUMS").write_text(
|
||||
"".join(f"{e['sha256']} {e['name']}\n" for e in entries), encoding="utf-8"
|
||||
)
|
||||
if args.table:
|
||||
args.table.write_text(
|
||||
json.dumps({"tag": TAG, "cache_dir": CACHE_DIR, "files": entries}, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
for e in entries:
|
||||
print(f"{e['sha256']} {e['bytes']:>9} {e['name']}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Vendored
+2
@@ -85,6 +85,7 @@ GET /community/items/{item_id}/preview
|
||||
GET /community/manifest
|
||||
GET /community/sources
|
||||
GET /community/submit-url
|
||||
GET /demo/dubbing/status
|
||||
GET /dictation/models
|
||||
GET /dictation/prefs
|
||||
GET /dictation/readiness
|
||||
@@ -240,6 +241,7 @@ POST /calls/{call_id}/takeover
|
||||
POST /clean-audio
|
||||
POST /community/items/{item_id}/use
|
||||
POST /convert
|
||||
POST /demo/dubbing/download
|
||||
POST /design/describe
|
||||
POST /dictation/prefs
|
||||
POST /dub/abort/{job_id}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""On-demand dubbing demo videos: integrity, consent, offline and serving.
|
||||
|
||||
No test here touches the network: downloads run through an
|
||||
``httpx.MockTransport`` that counts every request, which is what makes "no
|
||||
request without the user's POST" an assertable outcome.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Mount
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
|
||||
_GOOD = b"good-video-bytes" * 64
|
||||
|
||||
|
||||
def _pin(data: bytes) -> dict:
|
||||
return {"sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data), "kind": "video"}
|
||||
|
||||
|
||||
class Server:
|
||||
"""Serves {name: bytes} from memory and records every request."""
|
||||
|
||||
def __init__(self, files: dict[str, bytes], status: int = 200):
|
||||
self.files = files
|
||||
self.status = status
|
||||
self.requests: list[str] = []
|
||||
|
||||
def client(self) -> httpx.AsyncClient:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
self.requests.append(str(request.url))
|
||||
name = request.url.path.rsplit("/", 1)[-1]
|
||||
if self.status != 200 or name not in self.files:
|
||||
return httpx.Response(self.status if self.status != 200 else 404)
|
||||
return httpx.Response(200, content=self.files[name])
|
||||
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def demo_assets():
|
||||
"""Resolved per test: other suites may reload `services.*` in sys.modules."""
|
||||
import importlib
|
||||
|
||||
return importlib.import_module("services.demo_assets")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path, monkeypatch, demo_assets):
|
||||
monkeypatch.setattr(demo_assets, "DATA_DIR", str(tmp_path))
|
||||
monkeypatch.setattr(demo_assets, "PINNED", {"a.mp4": _pin(_GOOD), "b.mp4": _pin(_GOOD + b"x")})
|
||||
monkeypatch.setattr(demo_assets, "_state", {"state": "idle", "downloaded_bytes": 0, "error": None})
|
||||
monkeypatch.setattr(demo_assets, "_tasks", set())
|
||||
monkeypatch.delenv("OMNIVOICE_DEMO_ASSETS_URL", raising=False)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _cached(demo_assets, env: Path) -> list[str]:
|
||||
d = demo_assets.cache_dir()
|
||||
return sorted(p.name for p in d.iterdir()) if d.exists() else []
|
||||
|
||||
|
||||
def test_download_verifies_and_caches_every_file(env, demo_assets):
|
||||
server = Server({"a.mp4": _GOOD, "b.mp4": _GOOD + b"x"})
|
||||
result = asyncio.run(demo_assets.download_all(server.client()))
|
||||
assert result["state"] == "ready"
|
||||
assert _cached(demo_assets, env) == ["a.mp4", "b.mp4"]
|
||||
assert demo_assets.cache_dir() == env / "demo_cache" / "dubbing-v1"
|
||||
assert all(u.startswith(demo_assets.base_url() + "/") for u in server.requests)
|
||||
assert demo_assets.status()["files"] == {"a.mp4": True, "b.mp4": True}
|
||||
|
||||
|
||||
def test_hash_mismatch_is_rejected_and_never_cached(demo_assets, env):
|
||||
tampered = b"X" + _GOOD[1:] # same size, different bytes
|
||||
server = Server({"a.mp4": tampered, "b.mp4": _GOOD + b"x"})
|
||||
result = asyncio.run(demo_assets.download_all(server.client()))
|
||||
assert result["state"] == "error"
|
||||
assert "sha256" in result["error"]
|
||||
assert "a.mp4" not in _cached(demo_assets, env)
|
||||
assert not [n for n in _cached(demo_assets, env) if n.endswith(".part")]
|
||||
assert demo_assets.cached_path("a.mp4") is None
|
||||
|
||||
|
||||
def test_truncated_download_is_not_cached(demo_assets, env):
|
||||
server = Server({"a.mp4": _GOOD[:-10], "b.mp4": _GOOD + b"x"})
|
||||
result = asyncio.run(demo_assets.download_all(server.client()))
|
||||
assert result["state"] == "error"
|
||||
assert "truncated" in result["error"]
|
||||
assert _cached(demo_assets, env) == []
|
||||
|
||||
|
||||
def test_oversized_download_is_cut_off_at_the_pinned_size(env, demo_assets):
|
||||
server = Server({"a.mp4": _GOOD + b"extra", "b.mp4": _GOOD + b"x"})
|
||||
result = asyncio.run(demo_assets.download_all(server.client()))
|
||||
assert result["state"] == "error"
|
||||
assert "size cap" in result["error"]
|
||||
assert _cached(demo_assets, env) == []
|
||||
|
||||
|
||||
def test_http_error_reports_and_retry_succeeds(env, demo_assets):
|
||||
bad = Server({}, status=503)
|
||||
assert asyncio.run(demo_assets.download_all(bad.client()))["state"] == "error"
|
||||
good = Server({"a.mp4": _GOOD, "b.mp4": _GOOD + b"x"})
|
||||
assert asyncio.run(demo_assets.download_all(good.client()))["state"] == "ready"
|
||||
|
||||
|
||||
def test_a_file_with_the_wrong_size_on_disk_is_not_treated_as_cached(demo_assets, env):
|
||||
demo_assets.cache_dir().mkdir(parents=True)
|
||||
(demo_assets.cache_dir() / "a.mp4").write_bytes(b"short")
|
||||
assert demo_assets.cached_path("a.mp4") is None
|
||||
assert demo_assets.cached_path("../../etc/passwd") is None
|
||||
|
||||
|
||||
def test_status_offline_reads_local_state_only(env, demo_assets):
|
||||
# No client is ever created: this would raise if status() reached the network.
|
||||
def boom(*a, **k):
|
||||
raise AssertionError("status() must not use the network")
|
||||
|
||||
import api.http_client as hc
|
||||
|
||||
original = hc.get_http_client
|
||||
hc.get_http_client = boom
|
||||
try:
|
||||
s = demo_assets.status()
|
||||
finally:
|
||||
hc.get_http_client = original
|
||||
assert s["state"] == "idle"
|
||||
assert s["total_bytes"] == len(_GOOD) * 2 + 1
|
||||
assert s["downloaded_bytes"] == 0
|
||||
assert s["files"] == {"a.mp4": False, "b.mp4": False}
|
||||
|
||||
|
||||
def test_base_url_env_override(env, monkeypatch, demo_assets):
|
||||
assert demo_assets.base_url() == (
|
||||
"https://github.com/debpalash/omnivoice-gallery/releases/download/dub-demo-v1"
|
||||
)
|
||||
monkeypatch.setenv("OMNIVOICE_DEMO_ASSETS_URL", "http://127.0.0.1:9/demo/")
|
||||
assert demo_assets.base_url() == "http://127.0.0.1:9/demo"
|
||||
|
||||
|
||||
def test_nothing_is_fetched_at_import_or_by_status_or_get(env, monkeypatch, demo_assets):
|
||||
"""Only an explicit POST may start a download."""
|
||||
from fastapi import FastAPI
|
||||
|
||||
from api.routers import demo_assets as router_module
|
||||
|
||||
server = Server({"a.mp4": _GOOD, "b.mp4": _GOOD + b"x"})
|
||||
import api.http_client as hc
|
||||
|
||||
monkeypatch.setattr(hc, "get_http_client", server.client)
|
||||
finished = threading.Event()
|
||||
real_download_all = demo_assets.download_all
|
||||
|
||||
async def tracked(client=None):
|
||||
try:
|
||||
return await real_download_all(client)
|
||||
finally:
|
||||
finished.set()
|
||||
|
||||
monkeypatch.setattr(demo_assets, "download_all", tracked)
|
||||
app = FastAPI()
|
||||
app.include_router(router_module.router)
|
||||
app.dependency_overrides.update(
|
||||
{
|
||||
router_module.require_admin: lambda: None,
|
||||
router_module.require_consumer: lambda: None,
|
||||
}
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/demo/dubbing/status").json()["state"] == "idle"
|
||||
assert client.get("/demo/dubbing/status").json()["state"] == "idle"
|
||||
assert server.requests == []
|
||||
assert client.post("/demo/dubbing/download").status_code == 200
|
||||
# Explicit POST is the only trigger; wait on the task's completion event.
|
||||
assert finished.wait(5), "background download never completed"
|
||||
assert demo_assets.status()["state"] == "ready"
|
||||
assert server.requests
|
||||
|
||||
|
||||
def test_service_does_not_start_work_at_import(demo_assets):
|
||||
src = Path(demo_assets.__file__).read_text(encoding="utf-8")
|
||||
top_level = [ln for ln in src.splitlines() if ln and not ln[0].isspace()]
|
||||
assert not any("create_task" in ln or "get_http_client()" in ln for ln in top_level)
|
||||
|
||||
|
||||
def test_cached_file_is_served_with_ranges_and_missing_is_404(env, tmp_path, demo_assets):
|
||||
samples = tmp_path / "samples"
|
||||
(samples / "demo" / "dubbing").mkdir(parents=True)
|
||||
(samples / "demo" / "dubbing" / "a.jpg").write_bytes(b"\xff\xd8poster")
|
||||
demo_assets.cache_dir().mkdir(parents=True)
|
||||
(demo_assets.cache_dir() / "a.mp4").write_bytes(_GOOD)
|
||||
app = Starlette(routes=[Mount("/demo_audio", demo_assets.make_demo_mount(str(samples)))])
|
||||
client = TestClient(app)
|
||||
|
||||
ok = client.get("/demo_audio/demo/dubbing/a.mp4")
|
||||
assert ok.status_code == 200 and ok.content == _GOOD
|
||||
assert ok.headers["content-type"].startswith("video/")
|
||||
assert ok.headers["x-content-type-options"] == "nosniff"
|
||||
part = client.get("/demo_audio/demo/dubbing/a.mp4", headers={"Range": "bytes=0-3"})
|
||||
assert part.status_code == 206 and part.content == _GOOD[:4]
|
||||
# Bundled posters still come from the app bundle.
|
||||
assert client.get("/demo_audio/demo/dubbing/a.jpg").content == b"\xff\xd8poster"
|
||||
# Not cached yet / not pinned: plain 404, never a stray file.
|
||||
assert client.get("/demo_audio/demo/dubbing/b.mp4").status_code == 404
|
||||
assert client.get("/demo_audio/demo/dubbing/c.mp4").status_code == 404
|
||||
|
||||
|
||||
def test_pinned_table_covers_every_video_and_is_well_formed(demo_assets):
|
||||
table = json.loads(
|
||||
(Path(demo_assets.__file__).resolve().parents[1]
|
||||
/ "assets/samples/demo/dubbing/demo_assets.json").read_text(encoding="utf-8")
|
||||
)
|
||||
assert table["tag"] == "dub-demo-v1" and table["cache_dir"] == "dubbing-v1"
|
||||
for entry in table["files"]:
|
||||
assert len(entry["sha256"]) == 64 and int(entry["sha256"], 16) >= 0
|
||||
assert entry["bytes"] > 0
|
||||
assert entry["kind"] in {"video", "dev"}
|
||||
assert sum(e["bytes"] for e in table["files"] if e["kind"] == "video") < 12 << 20
|
||||
|
||||
|
||||
def test_windows_backslash_paths_still_resolve_the_cache(env, tmp_path, demo_assets):
|
||||
samples = tmp_path / "samples"
|
||||
(samples / "demo" / "dubbing").mkdir(parents=True)
|
||||
demo_assets.cache_dir().mkdir(parents=True)
|
||||
(demo_assets.cache_dir() / "a.mp4").write_bytes(_GOOD)
|
||||
mount = demo_assets.make_demo_mount(str(samples))
|
||||
scope = {"type": "http", "method": "GET", "headers": [], "path": "/"}
|
||||
|
||||
response = asyncio.run(mount.get_response("demo\\dubbing\\a.mp4", scope))
|
||||
assert response.status_code == 200
|
||||
# Traversal through either separator never reaches outside the pinned names.
|
||||
for evil in ("demo\\dubbing\\..\\..\\x.mp4", "demo/dubbing/../a.mp4", "demo\\dubbing\\sub\\a.mp4"):
|
||||
try:
|
||||
denied = asyncio.run(mount.get_response(evil, scope))
|
||||
except Exception as exc: # StaticFiles raises 404 for unknown paths
|
||||
assert getattr(exc, "status_code", None) == 404
|
||||
else:
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
def test_unsupported_proxy_scheme_becomes_a_clean_error_state(env, monkeypatch, demo_assets):
|
||||
import api.http_client as hc
|
||||
|
||||
def boom():
|
||||
raise ValueError("Unknown scheme for proxy URL 'socks4://user@host'")
|
||||
|
||||
monkeypatch.setattr(hc, "get_http_client", boom)
|
||||
result = asyncio.run(demo_assets.download_all())
|
||||
assert result["state"] == "error"
|
||||
assert "socks4" not in result["error"] and "user@host" not in result["error"]
|
||||
assert _cached(demo_assets, env) == []
|
||||
|
||||
|
||||
def test_error_status_never_carries_absolute_paths(env, monkeypatch, demo_assets):
|
||||
def boom(*args, **kwargs):
|
||||
raise PermissionError(13, "Permission denied", "/Users/someone/secret/demo_cache/x")
|
||||
|
||||
monkeypatch.setattr(demo_assets.tempfile, "mkstemp", boom)
|
||||
result = asyncio.run(demo_assets.download_all(Server({}).client()))
|
||||
assert result["state"] == "error"
|
||||
assert result["error"] == "PermissionError"
|
||||
assert "/Users" not in result["error"]
|
||||
@@ -109,7 +109,12 @@ def test_the_cloning_demo_pair_exists():
|
||||
|
||||
|
||||
def test_the_dubbing_demo_manifest_and_every_file_it_names_exist():
|
||||
"""The Dub workspace reads this manifest and plays what it lists."""
|
||||
"""The Dub workspace reads this manifest; the videos arrive on demand.
|
||||
|
||||
The bundle carries the manifest, subtitles and one poster still per clip.
|
||||
The mp4 files are release assets (``services/demo_assets.py``), so each
|
||||
manifest video must have a pinned sha256/size instead of a file on disk.
|
||||
"""
|
||||
manifest_path = _resolve("/demo_audio/demo/dubbing/manifest.json")
|
||||
assert os.path.isfile(manifest_path), (
|
||||
"The dubbing demo manifest is missing. Build it with "
|
||||
@@ -119,11 +124,21 @@ def test_the_dubbing_demo_manifest_and_every_file_it_names_exist():
|
||||
entries = [manifest["source"], *manifest["dubbed"]]
|
||||
assert len(entries) == 5, "one source plus four dubs"
|
||||
directory = os.path.dirname(manifest_path)
|
||||
pins = json.loads(open(os.path.join(directory, "demo_assets.json"), encoding="utf-8").read())
|
||||
pinned = {f["name"]: f for f in pins["files"]}
|
||||
for entry in entries:
|
||||
for key in ("video", "srt"):
|
||||
path = os.path.join(directory, entry[key])
|
||||
assert os.path.isfile(path), f"{entry['code']}: {entry[key]} missing"
|
||||
path = os.path.join(directory, entry["srt"])
|
||||
assert os.path.isfile(path), f"{entry['code']}: {entry['srt']} missing"
|
||||
stem = entry["video"].rsplit(".", 1)[0]
|
||||
poster = os.path.join(directory, f"{stem}.jpg")
|
||||
assert os.path.isfile(poster), f"{entry['code']}: poster {stem}.jpg missing"
|
||||
assert os.path.getsize(poster) < 40_000, f"{stem}.jpg is not a small still"
|
||||
pin = pinned.get(entry["video"])
|
||||
assert pin and pin["kind"] == "video", f"{entry['video']} has no pinned entry"
|
||||
assert len(pin["sha256"]) == 64 and pin["bytes"] > 0
|
||||
# A manifest that names a video whose subtitle says something else is
|
||||
# the one failure a viewer cannot tell from a bad dub.
|
||||
srt = open(os.path.join(directory, entry["srt"]), encoding="utf-8").read()
|
||||
srt = open(path, encoding="utf-8").read()
|
||||
assert entry["script"] in srt, f"{entry['code']}: subtitle does not match the script"
|
||||
heavy = [n for n in os.listdir(directory) if n.endswith((".mp4", ".wav"))]
|
||||
assert not heavy, f"{heavy} must ship as release assets, not in the bundle"
|
||||
Reference in new issue
Block a user