Spaces:
Running on Zero
Running on Zero
v0.3.1: smooth audio-reactive line and aligned multilingual examples
Browse filesFiles changed (15)
- CHANGELOG.md+8
- MANIFEST.sha256+14-12
- README.md+5-5
- VALIDATION.md+12-1
- app.py+15-6
- assets/player.html+2-2
- assets/player.js+102-130
- assets/settings.css+9-6
- assets/settings.html+1-1
- assets/settings.js+2-1
- assets/wave.js+39-34
- config.py+1-1
- examples.jsonAdded+11
- tests/test_examples.pyAdded+19
- tests/test_ui_js.py+29-30
12345# Changelog## 0.3.0 · 2026-11-10- Add a two-line HTML reader with audio-clock word highlighting, seek/replay synchronization and a preserved editable draft.12345678910111213# Changelog## 0.3.1 · 2026-11-10- Replace sample-based waveform rendering with a rounded, continuous curve whose amplitude follows actual playback energy. Use time-based attack/release and smooth edge fades; settle to a flat line on pause/end. Audio data and inference are unchanged.- Keep the pending-request activity indicator separate from playback, and respect reduced-motion preferences.- Replace uneven example buttons with a fixed three-column grid; neutralize the inherited 4-pixel margin that displaced the first button.- Add German, Spanish, Italian, Portuguese, Japanese, Mandarin and Korean examples alongside English and French. Examples select text, language and voice without generating audio.- Derive Play/Pause/Replay from the actual audio state, including a seek back from the end.## 0.3.0 · 2026-11-10- Add a two-line HTML reader with audio-clock word highlighting, seek/replay synchronization and a preserved editable draft.
123456789101112131415161718192021222324252627282930313233347 unmodified lines424344454647484950515253378f694f97eb755989fc6139455a58bc8c1bca7ae32c7a11be939a42ab27eeda .gitattributesf63fc2a4a5e19102c55cf01aa092aa8982403ef6ef808f4c2c65a9f766ccbf3e .gitignoref1f5e7deacbf04d6f82f6dc0db30e7de343d03fdc5c40baef40330c79fefe21a CHANGELOG.md3381fc95c5558560e1bb62d4cebea34bf6efa4adfbda7f4fe03bbf40bbcc55d3 LICENSE14ff7f6e037dae2f40983b6408a1570d587bbcdecd7a7b061f2d11f94044f812 NOTICE5ea53dcd52ecacb21ea6ae4fb94cc2ed7163fe02300f792a0ed35d09dcc0709c PROVENANCE.md68b70449f145477a6d0ce3a6376e8301f5afb9cb6fe6fa1781a0e65392ba7f50 README.md70748da69dc3c49bf9da5ba621888a8d796d12cfb07ba7ff1440568520b0d803 VALIDATION.mdc27fa4c518c35c000227a0a939c350999db6c4e45e71082ef32f74efb8ff3f92 alignment.py8827d945f3660298f3694eb070cb89685426f618cddde7c4d61c317bdec6bdd5 app.pyca28255ebe082f8104b27f52fcf5c05bf899e6edfe8fdaa853eb30adcfdd0e52 assets/generate.jsdd23ac0a74f0682218938cf387a037e89724e8bbfbdeb5ff35ecff289ebc24d4 assets/layout.jsecb1d25ae4aa218f69e269519fb68719a2c657ea1c24c0b6780df5f5dcf08259 assets/picker.js98d10bfcd45f9d3dfe3cf1e433a4a2829d253496a90daefd30819a0abd5a4347 assets/player.css95af93bc6375bcb3eca237c9fe0d7c5346b540f26b38516c18c89ba9ceb3458d assets/player.html7b93e8543fbcc963614161d8cfa9e57b3af396d120f5f7af6c84d15fc88f8c06 assets/player.js57347c4f3eb6f9aec59f1c8882c66e926e04acb87cc0154573594f063cf5df02 assets/reference.css03b2f8dbea4891f5ceb8990727473184118536720f439ffc69ef7d83d2f9a396 assets/reference.html697bc75149164c4737f1d07d1ba95cffcae9214fee3c6e7ba1210c497783c5f1 assets/reference.js74a71fe3c3cee7795fdd1e80f79b29f22c82c7bd27f2486c1a88578e5de1e821 assets/script.css9519e9e91bc74d23ef72c0e4e8b3c02f0d16fee8143910bff75c1731f163ed44 assets/script.htmlf7cfcf63e5622405ce6fe57d106231c1ce00bea379d995d74433ac854b5c099f assets/script.js4c33f5471865f012e4900961414877d3d18cb8bfc783d97f1266ab5e7e579af2 assets/settings.css06843a1901695e66d88c604a1c80605a15711cd55c4df582541794dc947b8e69 assets/settings.htmlcecc8107b91ca09af1acf60b41906b5f8705196a61d7cf245264c383ef68af7b assets/settings.js249fd190f8b58cf6e1b8f2582ed4afc40ce8ecf43292cbb409ee82f255604465 assets/style.css3c8b300235390c1ef9b3affdeb22afbdeaf0fd4b9c4beb28fb7f64cc81316f36 assets/wave.jsc476aa0fc7ed79b77cd6577d6e5efaf75dee8cccb6d5dc5f56fe92334b27d04d audio_files.py5467af2927d4ea4658c0d25c12571e82262906a61d13b5987c3c21863f62c9c8 config.py22cc095df3f023b95e4f7456f1b79144e341a33db6554db88ebe08a98c6b2f78 controller.py6aa124baba94d5961a439a9467325e14aec4306f1e1fbdb3fef9a7a0b9bd511b engine.py08396169ac070e226ebfdd11dbb2bf5469d475873e74680f91820f564ba803da lifecycle.py75b9cc83944e78c88496c205ee2b4734e85ed84ee4d1d02643aaf45b532e6695 logging_setup.py4c4ae63883d93e276095cea265e84224054a61f3c53666888708f79636df95bd packages.txt7 unmodified linese25f3dd0e11ec835e7db001c703825430e5c4745a538efb8d445fe650821cf1b tests/test_alignment.py70802a3c9077443d6e7c8e9d354f799981f96a321cca5b40f5f307fa364b2924 tests/test_audio.py89a62cbb880d9495634fce62a659e531dba74a1efa8bb5db4dbfeb1b8d5bf44b tests/test_contracts.py9c2d7b6aad84fa56d891bb7f79bedc8386b5cfca86f80a282c41777d9cd1a61b tests/test_http.pya20f4145d11561ab4caeabd51952c9f9b14088d5d330a4549e79f6a32310221c tests/test_lifecycle.py0889b93f4d83986372f5dbc72ad902ebb076bfd730c6ad07f3232b01b5ed1ee9 tests/test_logging.py31bfd349c66c1c31c06a7fc7d6cd1c94257679029bd512ddb4f133bfc4f6ccc8 tests/test_package.pybeae97c67f31cc89d948a5293bc820348cae1117e2f626ba97e7706819318ac8 tests/test_requests.pybb6c8fe808b96cee18fd8a406e73a182591d0be176434418087e93b92a3a6e51 tests/test_ui_js.py98216c34413fa17aeaaba8aeec41d157609b6b8f6c07cf6250239128cf616bb5 vendor/ZYPHRA_LICENSE5dd0692aae95e02965462827ccdd0fb1fc4f9762552e1cf979c4dc789cc34fc5 vendor/ZYPHRA_NOTICEcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 vendor/third_party/licenses/fusealign-multilingual-Apache-2.0.txt12345678910111213141516171819202122232425262728293031323334357 unmodified lines43444546474849505152535455378f694f97eb755989fc6139455a58bc8c1bca7ae32c7a11be939a42ab27eeda .gitattributesf63fc2a4a5e19102c55cf01aa092aa8982403ef6ef808f4c2c65a9f766ccbf3e .gitignorec8635c735b9f6dc0e4927ed607b6192be8536321a2e693d287af9c9822fcb048 CHANGELOG.md3381fc95c5558560e1bb62d4cebea34bf6efa4adfbda7f4fe03bbf40bbcc55d3 LICENSE14ff7f6e037dae2f40983b6408a1570d587bbcdecd7a7b061f2d11f94044f812 NOTICE5ea53dcd52ecacb21ea6ae4fb94cc2ed7163fe02300f792a0ed35d09dcc0709c PROVENANCE.mded674c9c8eb005cf69e51955d0fe6cb2f83ce22f89dfc370b24b84dc92f49ad6 README.mdec991525358dd3d5a89efdb67526f6c51e87b25f6712686d9722d0b1420c9266 VALIDATION.mdc27fa4c518c35c000227a0a939c350999db6c4e45e71082ef32f74efb8ff3f92 alignment.pyd37f555428e5506798c579213b3e7db08fcaa37e5856976061f1006f9ca8c6d8 app.pyca28255ebe082f8104b27f52fcf5c05bf899e6edfe8fdaa853eb30adcfdd0e52 assets/generate.jsdd23ac0a74f0682218938cf387a037e89724e8bbfbdeb5ff35ecff289ebc24d4 assets/layout.jsecb1d25ae4aa218f69e269519fb68719a2c657ea1c24c0b6780df5f5dcf08259 assets/picker.js98d10bfcd45f9d3dfe3cf1e433a4a2829d253496a90daefd30819a0abd5a4347 assets/player.css08722bf8146befa0b2acc859ff8130235a9dfe2ca2c7fc1d66fb2fe34c8efb4c assets/player.htmldd739d27e9317bf9534e872c67b060e0d3f5c490bbb2923b28748beebb6a9386 assets/player.js57347c4f3eb6f9aec59f1c8882c66e926e04acb87cc0154573594f063cf5df02 assets/reference.css03b2f8dbea4891f5ceb8990727473184118536720f439ffc69ef7d83d2f9a396 assets/reference.html697bc75149164c4737f1d07d1ba95cffcae9214fee3c6e7ba1210c497783c5f1 assets/reference.js74a71fe3c3cee7795fdd1e80f79b29f22c82c7bd27f2486c1a88578e5de1e821 assets/script.css9519e9e91bc74d23ef72c0e4e8b3c02f0d16fee8143910bff75c1731f163ed44 assets/script.htmlf7cfcf63e5622405ce6fe57d106231c1ce00bea379d995d74433ac854b5c099f assets/script.jsb379b615bb1f52b355b60bdde94a9fde4ef732f635a1ed56adbdfb7e279baca7 assets/settings.css11205e51e46d238be4958947cb0bebd35eb3cb69903b38903ab624ba25a40f32 assets/settings.htmlbd82d406c7554e4f0f7410b9dec78b85c0f3aea5b4eba028add750a4e9dd928c assets/settings.js249fd190f8b58cf6e1b8f2582ed4afc40ce8ecf43292cbb409ee82f255604465 assets/style.css3aaf1734e4a4122d4968b2ff1cd7124a6aad8fe243f364cd5f1d4ff6b3b7065a assets/wave.jsc476aa0fc7ed79b77cd6577d6e5efaf75dee8cccb6d5dc5f56fe92334b27d04d audio_files.py219e8fa0a84356f1c9c1ff589d23a38e7c4b0f1164404da8e880cc04adca1400 config.py22cc095df3f023b95e4f7456f1b79144e341a33db6554db88ebe08a98c6b2f78 controller.py6aa124baba94d5961a439a9467325e14aec4306f1e1fbdb3fef9a7a0b9bd511b engine.pye419cf08810b1fb969523c597a03c728d2f697b03a3e5e9a2ef81e63620d4046 examples.json08396169ac070e226ebfdd11dbb2bf5469d475873e74680f91820f564ba803da lifecycle.py75b9cc83944e78c88496c205ee2b4734e85ed84ee4d1d02643aaf45b532e6695 logging_setup.py4c4ae63883d93e276095cea265e84224054a61f3c53666888708f79636df95bd packages.txt7 unmodified linese25f3dd0e11ec835e7db001c703825430e5c4745a538efb8d445fe650821cf1b tests/test_alignment.py70802a3c9077443d6e7c8e9d354f799981f96a321cca5b40f5f307fa364b2924 tests/test_audio.py89a62cbb880d9495634fce62a659e531dba74a1efa8bb5db4dbfeb1b8d5bf44b tests/test_contracts.py8133a4f9345f726307b0cac6530b948faa710e9d0405b1021b6d72b006d71ea1 tests/test_examples.py9c2d7b6aad84fa56d891bb7f79bedc8386b5cfca86f80a282c41777d9cd1a61b tests/test_http.pya20f4145d11561ab4caeabd51952c9f9b14088d5d330a4549e79f6a32310221c tests/test_lifecycle.py0889b93f4d83986372f5dbc72ad902ebb076bfd730c6ad07f3232b01b5ed1ee9 tests/test_logging.py31bfd349c66c1c31c06a7fc7d6cd1c94257679029bd512ddb4f133bfc4f6ccc8 tests/test_package.pybeae97c67f31cc89d948a5293bc820348cae1117e2f626ba97e7706819318ac8 tests/test_requests.pyaf5fbdeb7451697c35a2ba85ed2e585e5e9322bd2fd5873e724b9a5cc4f766ed tests/test_ui_js.py98216c34413fa17aeaaba8aeec41d157609b6b8f6c07cf6250239128cf616bb5 vendor/ZYPHRA_LICENSE5dd0692aae95e02965462827ccdd0fb1fc4f9762552e1cf979c4dc789cc34fc5 vendor/ZYPHRA_NOTICEcfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 vendor/third_party/licenses/fusealign-multilingual-Apache-2.0.txt
14 unmodified lines151617181920212223243 unmodified lines282930313233343536373839404114 unmodified linesshort_description: A voice, a line, and your words.---# ZONOS3 Mini · 0.3.0A minimal Hugging Face Space for [Zyphra's ZONOS3-Mini](https://huggingface.co/Zyphra/ZONOS3-Mini).Centered editable text, a fine audio waveform, and one Generate button. The interface follows the supplied Zyphra presentation references. Model: Zyphra. UI/UX: [Sylvain Filoni / fffiloni](https://huggingface.co/fffiloni).**Deployed on [Hugging Face ZeroGPU](https://huggingface.co/spaces/fffiloni/ZONOS3-Mini).** Short French/English generations, a synthetic reference clip, cancellation/retry and browser playback have passed live checks. See [VALIDATION.md](VALIDATION.md) for the evidence and remaining limits; this is not a comprehensive audio-quality benchmark.3 unmodified lines2. Select **Generate speech**. The native Gradio/ZeroGPU progress and quota notices remain available.3. Play, seek or download the completed WAV. Generation does not autoplay.The waveform starts flat. Voice settings use documented Gradio HTML props, watch callbacks, custom example events and a custom audio upload/record/trim child. The generation event snapshots the custom controls into the unchanged public API inputs. After generation it displays samples from the output; during playback it uses the actual audio signal when Web Audio is available. A separate animated activity indicator appears while a request is pending; it is not an audio preview or a completion estimate. Native Gradio progress retains the real preparation/allocation/inference stages. Visual gain and edge fades affect only the drawing, never the audio.**Voice options** contains an optional reference clip, consent checkbox, seed, normalization, speaking rate and sampling. Selecting a preset selects its default text language; the language can then be changed independently. Examples only fill inputs. The English interface retains French text without requiring an interface language switch.## Deploy to Hugging Face1. Create a **Gradio** Space under an account with ZeroGPU access. Select **ZeroGPU** hardware in its settings. Consult the [current HF ZeroGPU instructions](https://huggingface.co/docs/hub/spaces-zerogpu).2. Upload this directory's contents at the repository root, including `vendor`, `assets`, `voices.json`, `requirements.txt` and `packages.txt`. `app.py` must be at the root, not inside an additional archive folder.3. Keep `sdk_version: 6.30.0` aligned with `gradio==6.30.0`. The Space installs the pinned runtime dependencies plus FFmpeg and libsndfile. Do not set `ZONOS_UI_ONLY` in production.4. Wait for startup loading to finish. The app imports `spaces` first, downloads the pinned model assets, and places the LM, decoder and speaker encoder on CUDA **at startup**, as required by the SDK's CUDA emulation.5. Run the live checks in [VALIDATION.md](VALIDATION.md) before public release. A green Space badge alone does not validate an inference or GPU lease release.14 unmodified lines151617181920212223243 unmodified lines282930313233343536373839404114 unmodified linesshort_description: A voice, a line, and your words.---# ZONOS3 Mini · 0.3.1A minimal Hugging Face Space for [Zyphra's ZONOS3-Mini](https://huggingface.co/Zyphra/ZONOS3-Mini).Centered editable text, a fine audio-reactive line, and one Generate button. The interface follows the supplied Zyphra presentation references. Model: Zyphra. UI/UX: [Sylvain Filoni / fffiloni](https://huggingface.co/fffiloni).**Deployed on [Hugging Face ZeroGPU](https://huggingface.co/spaces/fffiloni/ZONOS3-Mini).** Short French/English generations, a synthetic reference clip, cancellation/retry and browser playback have passed live checks. See [VALIDATION.md](VALIDATION.md) for the evidence and remaining limits; this is not a comprehensive audio-quality benchmark.3 unmodified lines2. Select **Generate speech**. The native Gradio/ZeroGPU progress and quota notices remain available.3. Play, seek or download the completed WAV. Generation does not autoplay.The waveform starts flat. Voice settings use documented Gradio HTML props, watch callbacks, custom example events and a custom audio upload/record/trim child. The generation event snapshots the custom controls into the unchanged public API inputs. During playback the line follows the actual audio energy when Web Audio is available. Its rounded shape is an illustration rather than a sample-by-sample oscilloscope: a continuous phase and time-based attack/release avoid jagged peaks and abrupt jumps. It returns smoothly to flat when paused or finished; no frozen full-take waveform remains. Reduced-motion mode keeps the playback line still, without disabling word synchronization. A separate animated activity indicator appears while a request is pending; it is not an audio preview or a completion estimate. Native Gradio progress retains the real preparation/allocation/inference stages. Visual gain and edge fades affect only the drawing, never the audio.**Voice options** contains an optional reference clip, consent checkbox, seed, normalization, speaking rate and sampling. Selecting a preset selects its default text language; the language can then be changed independently. Nine examples fill text, language and voice without starting inference: English, French, German, Spanish, Italian, Portuguese, Japanese, Mandarin and Korean. The Japanese example uses Savannah across languages because the exposed catalog has no native Japanese preset. The buttons use a fixed three-column grid with equal touch targets and underline positions. The English interface retains French text without requiring an interface language switch.## Deploy to Hugging Face1. Create a **Gradio** Space under an account with ZeroGPU access. Select **ZeroGPU** hardware in its settings. Consult the [current HF ZeroGPU instructions](https://huggingface.co/docs/hub/spaces-zerogpu).2. Upload this directory's contents at the repository root, including `vendor`, `assets`, `voices.json`, `examples.json`, `requirements.txt` and `packages.txt`. `app.py` must be at the root, not inside an additional archive folder.3. Keep `sdk_version: 6.30.0` aligned with `gradio==6.30.0`. The Space installs the pinned runtime dependencies plus FFmpeg and libsndfile. Do not set `ZONOS_UI_ONLY` in production.4. Wait for startup loading to finish. The app imports `spaces` first, downloads the pinned model assets, and places the LM, decoder and speaker encoder on CUDA **at startup**, as required by the SDK's CUDA emulation.5. Run the live checks in [VALIDATION.md](VALIDATION.md) before public release. A green Space badge alone does not validate an inference or GPU lease release.
1234567# Validation · 0.3.0 · 2026-11-10## Current release- 58 local tests passed, including exact Unicode transcript preservation, rejection of invalid timestamps, alignment failure retaining the new WAV, cancellation between allocations, session isolation, the original 13/5 public API, HTTP transport and complete archive imports. The pinned Qwen processor was loaded and prepared actual 16 kHz features locally; GPU inference was tested separately below.- Chromium UI tests used a clearly identified CPU fixture for simulated synthesis and timing. Checked at 320, 390, 768 and 1440 px: no horizontal overflow; two-line viewport and automatic page changes; seek/replay; preserving a draft while replaying an old take; custom upload, 2-second trim, reset/remove; microphone capture using Chromium's simulated device; no JavaScript errors. No real microphone or physical iPhone/Safari test is implied.- Simulated delayed microphone permission: switching back to Preset re-enabled submission, prevented recording, and ended all acquired tracks when the pending permission request resolved.123456789101112131415161718# Validation · 0.3.1 · 2026-11-10## Current release- 59 local tests passed: examples and preset/language mappings, unchanged public API, wave energy/geometry, time-based attack and release, generation lifecycle, session isolation and complete source-package imports. The existing protobuf deprecation warning remains visible.- The live v0.3.0 baseline at `ba8c1f3fd8218768930ce6ab5bf372657908cc05` reproduced the example-button mismatch: English inherited a 4 px bottom margin and measured 44 px high; Français measured 48 px. The replacement grid has nine 44 px buttons, zero margins and equal underline positions within each row.- Actual Chromium rendering at 320, 390, 768 and 1440 CSS px: no horizontal overflow; all nine example buttons update text, language and preset without publishing an audio result or requesting synthesis. English, French, German, Spanish, Italian, Portuguese, Japanese, Mandarin and Korean are included.- A single live English/Savannah request on the unchanged v0.3.0 engine produced a 3.933-second WAV with ready alignment. The v0.3.1 UI fixture replayed this actual WAV; fixture request progress was simulated, not a new GPU inference.- In that browser fixture, the activity curve starts while the request is pending. Playback changes the curve using the actual signal; pause and end settle to the exact flat baseline. Seeking back after the end restores Play instead of leaving Replay. Reduced-motion playback stays flat. No JavaScript errors were observed. Mobile and desktop screenshots were inspected.- Models, runtime revisions, inference parameters, dependencies, GPU lifecycle and public 13-input / 5-output contract are unchanged. The waveform is now explicitly an audio-reactive illustration; its shape is not a literal PCM plot.Remaining limits: physical Safari/iPhone testing and acoustic review of the seven new language examples. Browser checks above used Chromium with responsive viewports, not actual mobile hardware. Earlier live GPU-release evidence below applies to the unchanged engine, and is not replaced by a green Space badge.## v0.3.0 evidence- 58 local tests passed, including exact Unicode transcript preservation, rejection of invalid timestamps, alignment failure retaining the new WAV, cancellation between allocations, session isolation, the original 13/5 public API, HTTP transport and complete archive imports. The pinned Qwen processor was loaded and prepared actual 16 kHz features locally; GPU inference was tested separately below.- Chromium UI tests used a clearly identified CPU fixture for simulated synthesis and timing. Checked at 320, 390, 768 and 1440 px: no horizontal overflow; two-line viewport and automatic page changes; seek/replay; preserving a draft while replaying an old take; custom upload, 2-second trim, reset/remove; microphone capture using Chromium's simulated device; no JavaScript errors. No real microphone or physical iPhone/Safari test is implied.- Simulated delayed microphone permission: switching back to Preset re-enabled submission, prevented recording, and ended all acquired tracks when the pending permission request resolved.
1234528 unmodified lines34353637383919 unmodified lines59606162636465666731 unmodified lines9910010110210310410518 unmodified lines124125126127128129130131"""ZONOS3 Mini · a minimal, session-isolated ZeroGPU Space."""import htmlimport jsonimport osfrom pathlib import Path28 unmodified linesRUNTIME = Path(os.environ.get("ZONOS_RUNTIME_DIR", str(Path(tempfile.gettempdir()) / "zonos3-mini")))controller = Controller(engine, RUNTIME, [v["name"] for v in CATALOG], aligner=aligner)ASSETS = ROOT / "assets"DEFAULT_PICKER = json.dumps({"language":"en_us", "voice":"Savannah", "custom":False})19 unmodified linesdef load_example(language):if language == "fr":return "Un seul modèle.\nUne voix pour chaque idée.", json.dumps({"voice":"Gaspard","language":"fr_fr","custom":False}), "Preset"return DEFAULT_TEXT, DEFAULT_PICKER, "Preset"theme = gr.themes.Base(primary_hue="neutral", secondary_hue="neutral", neutral_hue="neutral",31 unmodified linesgenerate = gr.Button("Generate speech", variant="primary", elem_id="generate-speech")cancel = gr.Button("Cancel", visible=False, elem_id="cancel-speech")status = gr.HTML(message(""), elem_id="request-status")with gr.HTML(value="{}", source="Preset", html_template=(ASSETS / "settings.html").read_text(),css_template=(ASSETS / "settings.css").read_text(),js_on_load=(ASSETS / "settings.js").read_text(), elem_id="voice-options") as settings:reference = gr.HTML(value="null", html_template=(ASSETS / "reference.html").read_text(),18 unmodified linesscript, voice, _ = load_example(language)return script, voice, gr.HTML(source="Preset")settings.example_en(lambda: example("en"), outputs=[text, picker, settings], queue=False, api_visibility="private")settings.example_fr(lambda: example("fr"), outputs=[text, picker, settings], queue=False, api_visibility="private")event = generate.click(controller.generate,[text, picker, source, clip, consent, normalize, seed, randomize, temperature, top_p, top_k, repetition, rate],12345628 unmodified lines3536373839404119 unmodified lines6162636465666768697071727374757631 unmodified lines10810911011111211311418 unmodified lines133134135136137138139140"""ZONOS3 Mini · a minimal, session-isolated ZeroGPU Space."""import htmlfrom functools import partialimport jsonimport osfrom pathlib import Path28 unmodified linesRUNTIME = Path(os.environ.get("ZONOS_RUNTIME_DIR", str(Path(tempfile.gettempdir()) / "zonos3-mini")))controller = Controller(engine, RUNTIME, [v["name"] for v in CATALOG], aligner=aligner)ASSETS = ROOT / "assets"EXAMPLES = json.loads((ROOT / "examples.json").read_text())DEFAULT_PICKER = json.dumps({"language":"en_us", "voice":"Savannah", "custom":False})19 unmodified linesdef load_example(language):example = EXAMPLES[language]return example["text"], json.dumps({"voice":example["voice"], "language":example["language"], "custom":False}), "Preset"def settings_markup():buttons = "".join(f'<button type="button" class="example-button" data-example="{html.escape(code, quote=True)}"><span>{html.escape(item["label"])}</span></button>'for code, item in EXAMPLES.items())return (ASSETS / "settings.html").read_text().replace("<!-- example-buttons -->", buttons)theme = gr.themes.Base(primary_hue="neutral", secondary_hue="neutral", neutral_hue="neutral",31 unmodified linesgenerate = gr.Button("Generate speech", variant="primary", elem_id="generate-speech")cancel = gr.Button("Cancel", visible=False, elem_id="cancel-speech")status = gr.HTML(message(""), elem_id="request-status")with gr.HTML(value="{}", source="Preset", html_template=settings_markup(),css_template=(ASSETS / "settings.css").read_text(),js_on_load=(ASSETS / "settings.js").read_text(), elem_id="voice-options") as settings:reference = gr.HTML(value="null", html_template=(ASSETS / "reference.html").read_text(),18 unmodified linesscript, voice, _ = load_example(language)return script, voice, gr.HTML(source="Preset")for code in EXAMPLES:getattr(settings, "example_" + code)(partial(example, code), outputs=[text, picker, settings], queue=False, api_visibility="private")event = generate.click(controller.generate,[text, picker, source, clip, consent, normalize, seed, randomize, temperature, top_p, top_k, repetition, rate],
123456<div class="voice-player"><svg class="wave" viewBox="0 0 1000 140" preserveAspectRatio="none" role="img" aria-label="Audio waveform"><path d="M0 70 L1000 70" fill="none" stroke="currentColor" stroke-width="1.25" vector-effect="non-scaling-stroke"></path></svg><audio controls preload="metadata" hidden></audio><div class="playback" hidden>123456<div class="voice-player"><svg class="wave" viewBox="0 0 1000 140" preserveAspectRatio="none" role="img" aria-label="Voice-reactive visualization"><path d="M0 70 L1000 70" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"></path></svg><audio controls preload="metadata" hidden></audio><div class="playback" hidden>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148const host = document.getElementById('speech-player');// Gradio 6.30 HTML API: element, props, watch. The template has no user HTML.let dispose = () => {};let activityFrame = 0, active = false, restoreWave = () => {};const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');function setActivity(busy) {active = busy;cancelAnimationFrame(activityFrame);const svg = element.querySelector('.wave');svg.setAttribute('aria-label', busy ? 'Request activity indicator; not an audio preview' : 'Audio waveform');host.dataset.busy = String(busy);if (!busy) {const generate = document.getElementById('generate-speech');if (generate) generate.disabled = document.getElementById('voice-options')?.dataset.clip === 'true' && document.getElementById('reference-clip')?.dataset.busy === 'true';restoreWave(); return;}const values = new Float32Array(240);function animate(now) {if (!active || !element.isConnected) return;const time = reducedMotion.matches ? 0 : now / 1000;for (let i = 0; i < values.length; i++) {const x = i / (values.length - 1);values[i] = (.24 + .09 * Math.sin(time * 1.3)) *(Math.sin(x * Math.PI * 18 - time * 2.5) + .32 * Math.sin(x * Math.PI * 31 + time));}svg.querySelector('path').setAttribute('d', wavePath(values, 1));if (!reducedMotion.matches) activityFrame = requestAnimationFrame(animate);}animate(performance.now());}host.addEventListener('zonos:activity', event => setActivity(event.detail === true));const statusObserver = new MutationObserver(() => {if (!element.isConnected) { dispose(); cancelAnimationFrame(activityFrame); statusObserver.disconnect(); return; }const status = document.getElementById('status-state');if (status) {const busy = status.dataset.busy === 'true';if (busy !== active) setActivity(busy);}});statusObserver.observe(document.getElementById('request-status') || document.documentElement,{childList:true, subtree:true, attributes:true, attributeFilter:['data-busy']});window.addEventListener('pagehide', () => { dispose(); cancelAnimationFrame(activityFrame); statusObserver.disconnect(); }, {once:true});const minutes = seconds => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;function mount() {dispose();dispose = () => {};let data;try { data = JSON.parse(props.value || "{}"); } catch { return; }// A media element can only acquire one MediaElementAudioSourceNode, even if// its former AudioContext was closed. Each take gets a fresh native element.const previousPlayer = element.querySelector("audio");const player = previousPlayer.cloneNode(false);player.removeAttribute("src");previousPlayer.replaceWith(player);const controls = element.querySelector(".playback");const svg = element.querySelector(".wave");const path = svg.querySelector("path");const button = element.querySelector("[data-play]");const seek = element.querySelector("[data-seek]");const notice = element.querySelector(".audio-notice");const listeners = new AbortController();const on = (target, name, handler) => target.addEventListener(name, handler, {signal:listeners.signal});controls.hidden = true; notice.hidden = true; player.hidden = true;button.textContent = "Play"; button.setAttribute("aria-label", "Play generated speech");seek.value = "0"; element.querySelector("[data-time]").textContent = "0:00";if (!data.url) {restoreWave = () => path.setAttribute('d', 'M0 70 L1000 70');restoreWave(); return;}document.getElementById('script-input')?.dispatchEvent(new CustomEvent('zonos:take', {detail:data}));document.getElementById('voice-options')?.dispatchEvent(new CustomEvent('zonos:seed', {detail:data.seed}));const url = new URL(data.url, document.baseURI);// Files are generated by this Space only. Never accept arbitrary remote sources.if (url.origin !== location.origin || !url.pathname.includes("/gradio_api/file=")) return;player.src = url.href;player.hidden = false; // Native controls survive if initialization below fails.const link = element.querySelector("[data-download]");link.href = url.href;link.download = data.download_name || "zonos3.wav";element.querySelector("[data-duration]").textContent = minutes(data.duration || 0);let context = null, analyser = null, source = null, frame = 0, observer = null;const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");const samples = new Float32Array(2048);const preview = Array.isArray(data.wave) ? data.wave : [];let gain = visualGain(preview);function draw(values, adaptive = false) {if (active) return;const target = visualGain(values);gain = adaptive ? gain * .9 + target * .1 : target;path.setAttribute('d', wavePath(values, gain));}restoreWave = () => draw(preview);function sendClock() {document.getElementById('script-input')?.dispatchEvent(new CustomEvent('zonos:clock', {detail:{time:player.currentTime || 0,playing:!player.paused}}));}on(host, 'zonos:pause', () => player.pause());function tick() {if (player.paused || player.ended) return;if (analyser && !reduced.matches) { analyser.getFloatTimeDomainData(samples); draw(samples, true); }sendClock();frame = requestAnimationFrame(tick);}function updateTime() {sendClock();element.querySelector("[data-time]").textContent = minutes(player.currentTime || 0);if (Number.isFinite(player.duration) && player.duration > 0) seek.value = String(Math.round(player.currentTime / player.duration * 1000));}async function play() {try {if (!player.paused) { player.pause(); return; }const AudioContextClass = window.AudioContext || window.webkitAudioContext;if (!context && AudioContextClass) {context = new AudioContextClass();analyser = context.createAnalyser(); analyser.fftSize = 2048;source = context.createMediaElementSource(player);source.connect(analyser); analyser.connect(context.destination);}if (context?.state === "suspended") await context.resume();await player.play();notice.hidden = true;} catch {// Preserve a usable native player if a browser blocks Web Audio or playback.player.hidden = false; player.controls = true;notice.textContent = "Playback needs another click. You can also download the WAV.";notice.hidden = false;}}on(button, "click", play);on(player, "play", () => { button.textContent = "Pause"; button.setAttribute("aria-label", "Pause generated speech"); cancelAnimationFrame(frame); tick(); });on(player, "pause", () => { button.textContent = "Play"; button.setAttribute("aria-label", "Play generated speech"); cancelAnimationFrame(frame); draw(preview); });on(player, "ended", () => { button.textContent = "Replay"; button.setAttribute("aria-label", "Replay generated speech"); cancelAnimationFrame(frame); draw(preview); updateTime(); });on(player, "timeupdate", updateTime);on(player, "seeked", updateTime);on(player, "loadedmetadata", () => { element.querySelector("[data-duration]").textContent = minutes(player.duration); });on(player, "error", () => { notice.hidden = false; notice.textContent = "This audio is no longer available. Generate a new take."; });on(seek, "input", () => { if (Number.isFinite(player.duration)) player.currentTime = Number(seek.value) / 1000 * player.duration; });player.controls = false; player.hidden = true; controls.hidden = false; draw(preview);dispose = () => {listeners.abort(); cancelAnimationFrame(frame); observer?.disconnect(); player.pause();player.removeAttribute("src"); player.load(); source?.disconnect(); analyser?.disconnect();if (context && context.state !== "closed") context.close().catch(() => {});};observer = new MutationObserver(() => { if (!element.isConnected) dispose(); });observer.observe(document.documentElement, {childList:true, subtree:true});}watch("value", mount);mount();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120const host=document.getElementById('speech-player');// Documented Gradio HTML API; all external events use our own component ID.const reducedMotion=window.matchMedia('(prefers-reduced-motion: reduce)');const motion=new WaveMotion();let dispose=()=>{}, activityFrame=0, lastFrame=0, active=false;let energy=()=>0, playing=()=>false, clock=()=>{};function animate(now) {activityFrame=0;if(!element.isConnected)return;const dt=lastFrame?Math.min(.05,(now-lastFrame)/1000):1/60;lastFrame=now;const isPlaying=playing();if(isPlaying)clock();const target=active ? .32+.055*Math.sin(now/1300): isPlaying ? energy() : 0;const path=element.querySelector('.wave path');if(reducedMotion.matches) {// A still activity curve; playback never animates when motion is reduced.motion.level=0;path.setAttribute('d',wavePath(active ? .27 : 0,.6));} else {motion.step(target,dt);path.setAttribute('d',wavePath(motion.level,motion.phase));}if(isPlaying || (active && !reducedMotion.matches) || motion.level>0)activityFrame=requestAnimationFrame(animate);else lastFrame=0;}function scheduleWave() { if(!activityFrame)activityFrame=requestAnimationFrame(animate); }function setActivity(busy) {active=busy;element.querySelector('.wave').setAttribute('aria-label',busy?'Request activity indicator; not an audio preview':'Voice-reactive visualization');host.dataset.busy=String(busy);if(!busy) {const generate=document.getElementById('generate-speech');if(generate)generate.disabled=document.getElementById('voice-options')?.dataset.clip==='true' && document.getElementById('reference-clip')?.dataset.busy==='true';}scheduleWave();}const globalListeners=new AbortController();host.addEventListener('zonos:activity',event=>setActivity(event.detail===true),{signal:globalListeners.signal});const statusObserver=new MutationObserver(()=>{if(!element.isConnected){cleanup();return;}const status=document.getElementById('status-state');if(status && (status.dataset.busy==='true')!==active)setActivity(status.dataset.busy==='true');});statusObserver.observe(document.getElementById('request-status')||document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:['data-busy']});const removalObserver=new MutationObserver(()=>{if(!element.isConnected)cleanup();});removalObserver.observe(document.documentElement,{childList:true,subtree:true});function cleanup(){dispose();cancelAnimationFrame(activityFrame);statusObserver.disconnect();removalObserver.disconnect();globalListeners.abort();}window.addEventListener('pagehide',cleanup,{once:true,signal:globalListeners.signal});reducedMotion.addEventListener('change',scheduleWave,{signal:globalListeners.signal});const minutes=seconds=>`${Math.floor(seconds/60)}:${String(Math.floor(seconds%60)).padStart(2,'0')}`;function mount() {dispose();dispose=()=>{};let data;try{data=JSON.parse(props.value||'{}');}catch{return;}const previousPlayer=element.querySelector('audio');const player=previousPlayer.cloneNode(false);player.removeAttribute('src');previousPlayer.replaceWith(player);const controls=element.querySelector('.playback'), button=element.querySelector('[data-play]');const seek=element.querySelector('[data-seek]'),notice=element.querySelector('.audio-notice');const listeners=new AbortController();const on=(target,name,handler)=>target.addEventListener(name,handler,{signal:listeners.signal});controls.hidden=true;notice.hidden=true;player.hidden=true;button.textContent='Play';button.setAttribute('aria-label','Play generated speech');seek.value='0';element.querySelector('[data-time]').textContent='0:00';if(!data.url){scheduleWave();return;}const url=new URL(data.url,document.baseURI);if(url.origin!==location.origin || !url.pathname.includes('/gradio_api/file='))return;document.getElementById('script-input')?.dispatchEvent(new CustomEvent('zonos:take',{detail:data}));document.getElementById('voice-options')?.dispatchEvent(new CustomEvent('zonos:seed',{detail:data.seed}));player.src=url.href;player.hidden=false;const link=element.querySelector('[data-download]');link.href=url.href;link.download=data.download_name||'zonos3.wav';element.querySelector('[data-duration]').textContent=minutes(data.duration||0);let context=null,analyser=null,source=null;const samples=new Float32Array(2048);playing=()=>!player.paused && !player.ended;energy=()=>{if(!analyser)return 0;analyser.getFloatTimeDomainData(samples);return voiceEnergy(samples);};clock=()=>document.getElementById('script-input')?.dispatchEvent(new CustomEvent('zonos:clock',{detail:{time:player.currentTime||0,playing:playing()}}));function transport() {const ended=player.ended || (Number.isFinite(player.duration) && player.duration>0 && player.currentTime>=player.duration-.01);const label=playing()?'Pause':ended?'Replay':'Play';button.textContent=label;button.setAttribute('aria-label',label+' generated speech');}function updateTime() {clock();transport();element.querySelector('[data-time]').textContent=minutes(player.currentTime||0);if(Number.isFinite(player.duration)&&player.duration>0)seek.value=String(Math.round(player.currentTime/player.duration*1000));}async function play() {try {if(playing()){player.pause();return;}if(player.ended || (player.duration>0 && player.currentTime>=player.duration-.01))player.currentTime=0;const AudioContextClass=window.AudioContext||window.webkitAudioContext;if(!context && AudioContextClass) {context=new AudioContextClass();analyser=context.createAnalyser();analyser.fftSize=2048;source=context.createMediaElementSource(player);source.connect(analyser);analyser.connect(context.destination);}if(context?.state==='suspended')await context.resume();await player.play();transport();scheduleWave();notice.hidden=true;} catch {player.hidden=false;player.controls=true;notice.textContent='Playback needs another click. You can also download the WAV.';notice.hidden=false;}}on(button,'click',play);on(host,'zonos:pause',()=>player.pause());for(const event of ['play','playing','pause','ended','seeked'])on(player,event,()=>{updateTime();scheduleWave();});on(player,'timeupdate',updateTime);on(player,'loadedmetadata',()=>{element.querySelector('[data-duration]').textContent=minutes(player.duration);updateTime();});on(player,'error',()=>{notice.hidden=false;notice.textContent='This audio is no longer available. Generate a new take.';scheduleWave();});on(seek,'input',()=>{if(Number.isFinite(player.duration)){player.currentTime=Number(seek.value)/1000*player.duration;updateTime();}});player.controls=false;player.hidden=true;controls.hidden=false;scheduleWave();dispose=()=>{listeners.abort();player.pause();player.removeAttribute('src');player.load();source?.disconnect();analyser?.disconnect();if(context && context.state!=='closed')context.close().catch(()=>{});playing=()=>false;energy=()=>0;clock=()=>{};};}watch('value',mount);mount();
30 unmodified lines313233343536373839404142431 unmodified line454647484950511 unmodified line53545556575830 unmodified lines.sampling-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:12px 30px; padding-bottom:12px; }.sampling-grid label { display:flex; align-items:center; justify-content:space-between; gap:8px; color:#aaa; font-size:12px; }.text-button { min-height:44px; padding:8px 0; color:#ccc; background:transparent; border:0; text-decoration:underline; text-underline-offset:5px; font:11px ui-monospace,monospace; }.examples { display:flex; align-items:center; justify-content:space-between; gap:15px; padding:22px 0 12px; }.examples > div:last-child { display:flex; gap:24px; }.retention { color:#8f8f8f; font:10px/1.7 ui-monospace,monospace; margin:14px 0 0; }.consent-row { display:flex; align-items:center; gap:10px; min-height:44px; font-size:12px; color:#bbb; }.consent-row input { accent-color:#ddd; width:18px; height:18px; }:focus-visible { outline:2px solid #eee; outline-offset:4px; }@media(max-width:600px) { .setting-row { gap:12px; } .seed-controls { gap:10px; } .rate-row { align-items:flex-start; flex-direction:column; gap:4px; } .range-control { width:100%; } .sampling-grid { grid-template-columns:1fr; gap:8px; } .examples { flex-wrap:wrap; gap:6px; } .retention { font-size:10px; } }@media(prefers-reduced-motion:reduce) { svg, input::after { transition:none; } }/* Controls follow the label row, independently of wrapping help text. */.setting-row { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:start; gap:18px; }1 unmodified line.setting-row > input[role=switch] { margin-top:12px; }.seed-controls { justify-content:flex-end; min-height:44px; }.source-switch button { min-height:40px; }.examples { align-items:flex-start; }@media(max-width:600px) {.setting-row { column-gap:12px; }.seed-row, .rate-row { grid-template-columns:1fr; gap:8px; }1 unmodified line#take-seed { flex:1; width:auto; max-width:180px; text-align:left; }input[type=number] { font-size:16px; min-height:44px; }.source-switch button { font-size:14px; padding:6px 12px; }.examples { display:grid; grid-template-columns:1fr; gap:4px; }.examples > div:last-child { gap:24px; }}30 unmodified lines31323334353637383940411 unmodified line4344454647481 unmodified line50515253545556575859606130 unmodified lines.sampling-grid { display:grid; grid-template-columns:repeat(2,1fr); gap:12px 30px; padding-bottom:12px; }.sampling-grid label { display:flex; align-items:center; justify-content:space-between; gap:8px; color:#aaa; font-size:12px; }.text-button { min-height:44px; padding:8px 0; color:#ccc; background:transparent; border:0; text-decoration:underline; text-underline-offset:5px; font:11px ui-monospace,monospace; }.retention { color:#8f8f8f; font:10px/1.7 ui-monospace,monospace; margin:14px 0 0; }.consent-row { display:flex; align-items:center; gap:10px; min-height:44px; font-size:12px; color:#bbb; }.consent-row input { accent-color:#ddd; width:18px; height:18px; }:focus-visible { outline:2px solid #eee; outline-offset:4px; }@media(max-width:600px) { .setting-row { gap:12px; } .seed-controls { gap:10px; } .rate-row { align-items:flex-start; flex-direction:column; gap:4px; } .range-control { width:100%; } .sampling-grid { grid-template-columns:1fr; gap:8px; } .retention { font-size:10px; } }@media(prefers-reduced-motion:reduce) { svg, input::after { transition:none; } }/* Controls follow the label row, independently of wrapping help text. */.setting-row { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:start; gap:18px; }1 unmodified line.setting-row > input[role=switch] { margin-top:12px; }.seed-controls { justify-content:flex-end; min-height:44px; }.source-switch button { min-height:40px; }@media(max-width:600px) {.setting-row { column-gap:12px; }.seed-row, .rate-row { grid-template-columns:1fr; gap:8px; }1 unmodified line#take-seed { flex:1; width:auto; max-width:180px; text-align:left; }input[type=number] { font-size:16px; min-height:44px; }.source-switch button { font-size:14px; padding:6px 12px; }}.examples { display:grid; grid-template-columns:1fr; gap:12px; padding:22px 0 12px; }.example-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:4px 16px; align-items:start; }.example-button { appearance:none; -webkit-appearance:none; display:flex; align-items:center; justify-content:flex-start; box-sizing:border-box; height:44px; min-height:44px; margin:0!important; padding:0; border:0; border-radius:0; color:#ccc; background:transparent; font:12px/20px ui-monospace,monospace; text-align:left; }.example-button span { display:block; height:22px; line-height:20px; border-bottom:1px solid currentColor; }.example-button:hover { color:#fff; }@media(max-width:360px) { .example-grid { gap:4px 10px; } .example-button { font-size:11px; } }
15 unmodified lines16171819202115 unmodified lines<label>Top-k <input type="number" min="1" max="400" step="1" data-setting="top_k"></label><label>Repetition penalty <input type="number" min="1" max="4" step="0.1" data-setting="repetition"></label></div><button type="button" class="text-button" data-reset>Reset sampling</button></details><div class="examples"><div><span class="setting-label">Try a text</span><p class="setting-help">Loads the inputs. Does not generate audio.</p></div><div><button type="button" class="text-button" data-example="en">English</button><button type="button" class="text-button" data-example="fr">Français</button></div></div><p class="retention">600 characters per take · Download your audio to keep it beyond 24 hours.</p></div>15 unmodified lines16171819202115 unmodified lines<label>Top-k <input type="number" min="1" max="400" step="1" data-setting="top_k"></label><label>Repetition penalty <input type="number" min="1" max="4" step="0.1" data-setting="repetition"></label></div><button type="button" class="text-button" data-reset>Reset sampling</button></details><section class="examples" aria-labelledby="examples-title"><div><span class="setting-label" id="examples-title">Try a text</span><p class="setting-help">Loads text, language and voice. Does not generate audio.</p></div><div class="example-grid" role="group" aria-labelledby="examples-title"><!-- example-buttons --></div></section><p class="retention">600 characters per take · Download your audio to keep it beyond 24 hours.</p></div>
3 unmodified lines45678928 unmodified lines383940414243443 unmodified linesconst defaults = {source:'Preset',consent:false,seed:0,randomize:true,normalize:true,rate:0,temperature:.75,top_p:.69,top_k:80,repetition:2.4};let state = {...defaults, ...JSON.parse(props.value || '{}')};let open = false;const listeners = new AbortController();function publish() { props.value = JSON.stringify(state); host.dataset.settings = props.value; }function sync() {28 unmodified linesif (button.matches('.settings-toggle')) { open = !open; sync(); }if (button.dataset.source) { state.source = button.dataset.source; props.source = state.source; sync(); sourceChanged(); }if (button.hasAttribute('data-reset')) { for (const key of ['temperature','top_p','top_k','repetition']) state[key] = defaults[key]; sync(); }if (button.dataset.example) trigger(button.dataset.example === 'fr' ? 'example_fr' : 'example_en');}, {signal:listeners.signal});host.addEventListener('zonos:seed', event => { state.seed = event.detail; sync(); }, {signal:listeners.signal});watch('source', () => { state.source = props.source; sync(); sourceChanged(); });3 unmodified lines4567891028 unmodified lines394041424344453 unmodified linesconst defaults = {source:'Preset',consent:false,seed:0,randomize:true,normalize:true,rate:0,temperature:.75,top_p:.69,top_k:80,repetition:2.4};let state = {...defaults, ...JSON.parse(props.value || '{}')};let open = false;const exampleEvents={en:'example_en',fr:'example_fr',de:'example_de',es:'example_es',it:'example_it',pt:'example_pt',ja:'example_ja',zh:'example_zh',ko:'example_ko'};const listeners = new AbortController();function publish() { props.value = JSON.stringify(state); host.dataset.settings = props.value; }function sync() {28 unmodified linesif (button.matches('.settings-toggle')) { open = !open; sync(); }if (button.dataset.source) { state.source = button.dataset.source; props.source = state.source; sync(); sourceChanged(); }if (button.hasAttribute('data-reset')) { for (const key of ['temperature','top_p','top_k','repetition']) state[key] = defaults[key]; sync(); }if (exampleEvents[button.dataset.example]) trigger(exampleEvents[button.dataset.example]);}, {signal:listeners.signal});host.addEventListener('zonos:seed', event => { state.seed = event.detail; sync(); }, {signal:listeners.signal});watch('source', () => { state.source = props.source; sync(); sourceChanged(); });
123456789101112131415161718192021222324252627282930313233343536373839// Smooth display geometry only. Playback and exported PCM remain untouched.function visualGain(values) {let sum = 0;for (const value of values) sum += value * value;const rms = Math.sqrt(sum / Math.max(1, values.length));return rms < .0005 ? 1 : Math.min(10, Math.max(1, .32 / rms));}function wavePath(values, gain = 1) {if (values.length < 2) return 'M0 70 L1000 70';// Low-pass the display signal before interpolation: no sharp PCM corners.const count = 72, filtered = [];const radius = Math.max(2, values.length / count * .7);for (let i=0; i<count; i++) {const center = i / (count-1) * (values.length-1);let sum=0, weight=0;for (let j=Math.max(0,Math.floor(center-radius*2)); j<=Math.min(values.length-1,Math.ceil(center+radius*2)); j++) {const w=Math.exp(-.5*((j-center)/radius)**2);sum+=(Number(values[j])||0)*w; weight+=w;}filtered.push(sum/weight);}const filteredRms = Math.sqrt(filtered.reduce((sum,v)=>sum+v*v,0)/count);const displayGain = Math.max(gain, Math.min(70, .22/Math.max(.001,filteredRms)));const points = filtered.map((sample,i) => {const t=i/(count-1), e=Math.min(1,t/.13,(1-t)/.13);const fade=e*e*e*(e*(e*6-15)+10);return [24+952*t,70-58*Math.tanh(sample*displayGain*1.7)*fade];});// Monotone Hermite tangents prevent cubic overshoot at peaks.const slopes=points.slice(1).map((p,i)=>(p[1]-points[i][1])/(p[0]-points[i][0]));const tangent=points.map((_,i)=>i===0||i===count-1?0:slopes[i-1]*slopes[i]<=0?0:2*slopes[i-1]*slopes[i]/(slopes[i-1]+slopes[i]));let d='M0 70 L24 70';for(let i=1;i<count;i++) {const a=points[i-1],b=points[i],h=(b[0]-a[0])/3;d+=` C${(a[0]+h).toFixed(2)} ${(a[1]+tangent[i-1]*h).toFixed(2)} ${(b[0]-h).toFixed(2)} ${(b[1]-tangent[i]*h).toFixed(2)} ${b[0].toFixed(2)} ${b[1].toFixed(2)}`;}return d+' L1000 70';}1234567891011121314151617181920212223242526272829303132333435363738394041424344// An audio-reactive illustration, not an oscilloscope or a PCM preview.// Energy comes from the playing audio; shape and continuous phase are visual.function voiceEnergy(values) {if (!values.length) return 0;let sum=0, squares=0;for (const value of values) { const v=Number.isFinite(value)?value:0; sum+=v; squares+=v*v; }const rms=Math.sqrt(Math.max(0,squares/values.length-(sum/values.length)**2));return Math.sqrt(1-Math.exp(-18*Math.max(0,rms-.003)));}class WaveMotion {constructor() { this.level=0; this.phase=0; }step(target,seconds) {const dt=Math.min(.05,Math.max(0,seconds));target=Math.min(1,Math.max(0,Number.isFinite(target)?target:0));// Time-based attack/release behaves alike at 30, 60 and 120 Hz.const tau=target > this.level ? .09 : .24;this.level+=(target-this.level)*(1-Math.exp(-dt/tau));this.phase=(this.phase+dt*(1.15+.3*this.level))%(Math.PI*20);if(target===0 && this.level<.001)this.level=0;return this;}}function wavePath(level,phase=0) {level=Math.min(1,Math.max(0,Number.isFinite(level)?level:0));if(level<.001)return 'M0 70 L1000 70';function y(t) {const edge=Math.min(1,t/.16,(1-t)/.16);const fade=edge*edge*edge*(edge*(edge*6-15)+10);const broad=.72+.28*Math.sin(Math.PI*t)**2;const carrier=(Math.sin(Math.PI*2*6.2*t+phase)+.23*Math.sin(Math.PI*2*3.1*t-phase*.7+.7))/1.23;return 70-56*level*fade*broad*carrier;}const derivative=t=>t<=0||t>=1?0:(y(t+.0001)-y(t-.0001))/.0002;// Cubics follow the analytic curve, without saturation or flattened peaks.const count=128, width=960;let d='M0 70 L20 70';for(let i=1;i<=count;i++) {const a=(i-1)/count,b=i/count,h=(b-a)/3;d+=` C${(20+width*(a+h)).toFixed(2)} ${(y(a)+derivative(a)*h).toFixed(2)} ${(20+width*(b-h)).toFixed(2)} ${(y(b)-derivative(b)*h).toFixed(2)} ${(20+width*b).toFixed(2)} ${y(b).toFixed(2)}`;}return d+' L1000 70';}
1234567"""Release contract. Changing a revision requires rerunning the contract tests."""from pathlib import PathVERSION = "0.3.0"ROOT = Path(__file__).resolve().parentMODEL_ID = "Zyphra/ZONOS3-Mini"MODEL_REVISION = "eaac314642440e8f1f497f1505ca376f8e618f2a"1234567"""Release contract. Changing a revision requires rerunning the contract tests."""from pathlib import PathVERSION = "0.3.1"ROOT = Path(__file__).resolve().parentMODEL_ID = "Zyphra/ZONOS3-Mini"MODEL_REVISION = "eaac314642440e8f1f497f1505ca376f8e618f2a"
1234567891011{ "en": {"label":"English", "language":"en_us", "voice":"Savannah", "text":"Some stories begin with a voice.\nThis one begins with yours."}, "fr": {"label":"Français", "language":"fr_fr", "voice":"Gaspard", "text":"Un seul modèle.\nUne voix pour chaque idée."}, "de": {"label":"Deutsch", "language":"de", "voice":"Liesel", "text":"Manche Geschichten beginnen mit einer Stimme.\nDiese beginnt mit deiner."}, "es": {"label":"Español", "language":"es", "voice":"Ximena", "text":"Algunas historias comienzan con una voz.\nEsta empieza con la tuya."}, "it": {"label":"Italiano", "language":"it", "voice":"Ginevra", "text":"Alcune storie iniziano con una voce.\nQuesta comincia con la tua."}, "pt": {"label":"Português", "language":"pt_br", "voice":"Thiago", "text":"Algumas histórias começam com uma voz.\nEsta começa com a sua."}, "ja": {"label":"日本語", "language":"ja", "voice":"Savannah", "text":"物語は、ひとつの声から始まります。\nこの物語は、あなたの声から。"}, "zh": {"label":"中文", "language":"cmn", "voice":"Meilin", "text":"有些故事,从一个声音开始。\n这个故事,从你的声音开始。"}, "ko": {"label":"한국어", "language":"ko", "voice":"Seoyeon", "text":"어떤 이야기는 목소리에서 시작됩니다.\n이 이야기는 당신의 목소리로 시작됩니다."}}12345678910111213141516171819import jsonfrom config import ROOT, LANGUAGES, MAX_CHARS
def test_examples_cover_all_languages_and_use_real_presets(monkeypatch): monkeypatch.setenv("ZONOS_UI_ONLY", "1") import app catalog={v["name"] for v in app.CATALOG} assert len(app.EXAMPLES)==9 assert {v["language"] for v in app.EXAMPLES.values()}==set(LANGUAGES)-{"en_gb"} for code in app.EXAMPLES: text,picker,source=app.load_example(code) voice=json.loads(picker) assert 0<len(text)<=MAX_CHARS and voice["voice"] in catalog and source=="Preset" assert voice["language"]==app.EXAMPLES[code]["language"] and voice["custom"] is False assert set(app.demo.get_api_info()["named_endpoints"])=={"/generate","/cancel"} assert app.settings_markup().count('class="example-button"')==9 example_events=[e for e in app.demo.config["dependencies"] if any(t[1].startswith("example_") for t in e["targets"])] assert len(example_events)==9 and all(e["queue"] is False for e in example_events)2 unmodified lines3456789101112131415161718192021222324252627282930313218 unmodified lines515253545556575859603 unmodified lines6465666768697071727374752 unmodified linesfrom config import ROOTdef test_wave_baseline_gain_and_smooth_edges():source = (ROOT / 'assets/wave.js').read_text()script = source + r'''const assert = require('node:assert/strict');const zeros = Array(240).fill(0);assert.equal(visualGain(zeros), 1);const quiet = Array.from({length:240}, (_,i)=>.035*Math.sin(i*.2));assert.ok(visualGain(quiet) > 8);const input = Array(240).fill(1);const d = wavePath(input, 3);assert.ok(d.startsWith('M0 70 L24 70 C'));assert.ok(d.endsWith('976.00 70.00 L1000 70'));const curves=[...d.matchAll(/C([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+)/g)].map(x=>x.slice(1).map(Number));assert.equal(curves.length,71);assert.equal(curves[0][1],70); // horizontal starting tangentassert.equal(curves.at(-1)[3],70); // horizontal ending tangentassert.ok(Math.min(...curves.map(p=>p[5]))<15);assert.ok(Math.min(...curves.flatMap(p=>[p[1],p[3],p[5]]))>=12);const flat=wavePath(zeros);assert.ok([...flat.matchAll(/C([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+)/g)].every(p=>+p[2]===70 && +p[4]===70 && +p[6]===70));const low=wavePath(Array.from({length:2048},(_,i)=>.008*Math.sin(i*.04)),10);const lowY=[...low.matchAll(/C([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+)/g)].map(p=>+p[6]);assert.ok(Math.max(...lowY)-Math.min(...lowY)>45);assert.ok(!d.includes('NaN'));'''subprocess.run(['node','-e',script], check=True)18 unmodified linesdef test_activity_completion_restores_submit_after_validation_error():# Gradio may leave an imperative disabled property untouched when its# interactive prop stays True across a validation failure.source = (ROOT / 'assets/wave.js').read_text()source += (ROOT / 'assets/player.js').read_text().split("host.addEventListener('zonos:activity'")[0]script = r'''const assert = require('node:assert/strict');const generate = {disabled:true};3 unmodified linesglobal.element = {querySelector:()=>svg,isConnected:true};global.document = {getElementById:id=>id==='generate-speech'?generate:hostNode};global.window = {matchMedia:()=>({matches:true})};global.cancelAnimationFrame=()=>{};''' + source + r'''setActivity(true);assert.equal(hostNode.dataset.busy,'true');setActivity(false);assert.equal(generate.disabled,false);assert.equal(hostNode.dataset.busy,'false');'''subprocess.run(['node','-e',script], check=True)2 unmodified lines345678910111213141516171819202122232425262728293031323334353618 unmodified lines55565758596061623 unmodified lines6667686970717273742 unmodified linesfrom config import ROOTdef test_wave_energy_geometry_and_temporal_continuity():source = (ROOT / 'assets/wave.js').read_text()script = source + r'''const assert = require('node:assert/strict');assert.equal(voiceEnergy(Array(200).fill(0)),0);assert.equal(voiceEnergy(Array(200).fill(.8)),0); // DC is not audible energy.const tone=a=>Array.from({length:2048},(_,i)=>a*Math.sin(i*.18));assert.ok(voiceEnergy(tone(.1))>voiceEnergy(tone(.015)));assert.equal(wavePath(0),'M0 70 L1000 70');for(const phase of [0,1,3,12]) {const d=wavePath(1,phase);assert.ok(d.startsWith('M0 70 L20 70 C'));assert.ok(d.endsWith('980.00 70.00 L1000 70'));const c=[...d.matchAll(/C([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+) ([\d.]+)/g)].map(x=>x.slice(1).map(Number));assert.equal(c[0][1],70);assert.equal(c.at(-1)[3],70);assert.ok(c.flatMap(p=>[p[1],p[3],p[5]]).every(y=>y>=13 && y<=127));}const motion=new WaveMotion();motion.step(1,1/60);assert.ok(motion.level>0 && motion.level<.2);for(let i=0;i<60;i++)motion.step(1,1/60);assert.ok(motion.level>.99);const before=motion.level;motion.step(0,1/60);assert.ok(motion.level<before && motion.level>.9);for(let i=0;i<120;i++)motion.step(0,1/60);assert.equal(motion.level,0);assert.equal(wavePath(motion.level,motion.phase),'M0 70 L1000 70');const m30=new WaveMotion(),m120=new WaveMotion();for(let i=0;i<30;i++)m30.step(.6,1/30);for(let i=0;i<120;i++)m120.step(.6,1/120);assert.ok(Math.abs(m30.level-m120.level)<.0001);'''subprocess.run(['node','-e',script], check=True)18 unmodified linesdef test_activity_completion_restores_submit_after_validation_error():source = (ROOT / 'assets/wave.js').read_text()source += (ROOT / 'assets/player.js').read_text().split("const globalListeners=")[0]script = r'''const assert = require('node:assert/strict');const generate = {disabled:true};3 unmodified linesglobal.element = {querySelector:()=>svg,isConnected:true};global.document = {getElementById:id=>id==='generate-speech'?generate:hostNode};global.window = {matchMedia:()=>({matches:true})};global.cancelAnimationFrame=()=>{};global.requestAnimationFrame=()=>1;''' + source + r'''setActivity(true);assert.equal(hostNode.dataset.busy,'true');setActivity(false);assert.equal(generate.disabled,false);assert.equal(hostNode.dataset.busy,'false');'''subprocess.run(['node','-e',script], check=True)
CHANGELOG.md+8
MANIFEST.sha256+14-12
README.md+5-5
VALIDATION.md+12-1
app.py+15-6
assets/player.html+2-2
assets/player.js+102-130
assets/settings.css+9-6
assets/settings.html+1-1
assets/settings.js+2-1
assets/wave.js+39-34
config.py+1-1
examples.jsonAdded+11
tests/test_examples.pyAdded+19
tests/test_ui_js.py+29-30