Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download embeddings_ui.py from Pendrokar/xVASynth-TTS: direct link, hf CLI and curl.
- Browser
- Download file 7.2 kB
-
https://huggingface.co/spaces/Pendrokar/xVASynth-TTS/resolve/main/embeddings_ui.py
- Command line
-
hf download hf://spaces/Pendrokar/xVASynth-TTS/embeddings_ui.py
-
curl -L -o embeddings_ui.py https://huggingface.co/spaces/Pendrokar/xVASynth-TTS/resolve/main/embeddings_ui.py
7.2 kB
| """Second Gradio tab: the xVASynth voice-embeddings visualiser in an iframe. | |
| The iframe stays unloaded until the Embeddings tab is selected. Plot | |
| positions are the xVASynth app's own layout from allData.json. Previews are | |
| the .wav samples downloaded from the model repos. /predict on the | |
| synthesizer tab is left unchanged. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import gradio as gr | |
| from fastapi import HTTPException | |
| from fastapi.responses import FileResponse, JSONResponse, RedirectResponse | |
| from embeddings_catalog import collect_voice_embeddings | |
| _ROOT = os.path.dirname(os.path.abspath(__file__)) | |
| _PAGE_DIR = os.path.join(_ROOT, "static", "embeddings") | |
| _LIB_DIR = os.path.join(_ROOT, "resources", "app", "lib") | |
| _LIB_FILES = { | |
| "Three.min.js": "application/javascript", | |
| "OrbitControls.js": "application/javascript", | |
| "TrackballControls.js": "application/javascript", | |
| "Three.texture.js": "application/javascript", | |
| "Three.sprite.js": "application/javascript", | |
| } | |
| _PAGE_FILES = { | |
| "visualizer.js": "application/javascript", | |
| "visualizer.css": "text/css", | |
| "reduce.js": "application/javascript", | |
| } | |
| _ARPABET_CSS = ( | |
| ".arpabet {background-color: gray; border-radius: 5px; font-size: 120%; " | |
| "padding: 0 0.1em; margin: 0 0.1em; text-align: center}" | |
| ) | |
| _HOST_CSS = """ | |
| #xvasynth-embeddings-host, | |
| #xvasynth-embeddings-host .prose { | |
| max-width: none !important; | |
| width: 100%; | |
| } | |
| #xvasynth-embeddings-frame { | |
| width: 100%; | |
| height: calc(100vh - 140px); | |
| min-height: 640px; | |
| border: 0; | |
| display: block; | |
| background: #383838; | |
| } | |
| """ | |
| _IFRAME_HTML = ( | |
| '<iframe id="xvasynth-embeddings-frame" data-src="/embeddings/" ' | |
| 'title="Voice embeddings visualiser" allow="autoplay"></iframe>' | |
| ) | |
| # Gradio runs this on page load as `await (${js})()`. It must be a function | |
| # expression. The iframe src is set once, the first time the tab is selected. | |
| _LAZY_JS = r""" | |
| () => { | |
| const tabByName = (name) => Array.from(document.querySelectorAll('[role="tab"]')) | |
| .find((tab) => (tab.textContent || "").trim() === name); | |
| const arm = () => { | |
| const frame = document.getElementById("xvasynth-embeddings-frame"); | |
| if (!frame || frame.getAttribute("src")) return; | |
| const tab = tabByName("Embeddings"); | |
| if (!tab || tab.getAttribute("aria-selected") !== "true") return; | |
| frame.src = frame.dataset.src || "/embeddings/"; | |
| }; | |
| const watchTab = () => { | |
| const tab = tabByName("Embeddings"); | |
| if (!tab || tab.dataset.xvaWatch) return false; | |
| tab.dataset.xvaWatch = "1"; | |
| arm(); | |
| const observer = new MutationObserver(arm); | |
| observer.observe(tab, {attributes: true, attributeFilter: ["aria-selected"]}); | |
| tab.addEventListener("click", () => setTimeout(arm, 0)); | |
| return true; | |
| }; | |
| if (!watchTab()) { | |
| const rootObserver = new MutationObserver(() => { | |
| if (watchTab()) rootObserver.disconnect(); | |
| }); | |
| rootObserver.observe(document.body, {childList: true, subtree: true}); | |
| } | |
| const pickVoice = (voiceId, tries, openedMore) => { | |
| const radios = Array.from(document.querySelectorAll('input[type="radio"]')); | |
| const target = radios.find((input) => input.value === voiceId); | |
| if (target) { | |
| target.click(); | |
| return; | |
| } | |
| if (!openedMore) { | |
| const more = radios.find((input) => input.value === "more"); | |
| if (more) { | |
| more.click(); | |
| openedMore = true; | |
| } | |
| } | |
| if (tries < 20) setTimeout(() => pickVoice(voiceId, tries + 1, openedMore), 100); | |
| }; | |
| window.addEventListener("message", (event) => { | |
| const data = event.data; | |
| if (!data || data.type !== "xvasynth-load-voice" || !data.voiceId) return; | |
| if (event.origin !== window.location.origin) return; | |
| const synth = tabByName("Text to Speech"); | |
| if (synth) synth.click(); | |
| pickVoice(String(data.voiceId), 0, false); | |
| }); | |
| } | |
| """ | |
| _index = None | |
| _synth_ids = () | |
| def set_catalog(index, synth_ids): | |
| global _index, _synth_ids | |
| _index = index | |
| _synth_ids = tuple(synth_ids or ()) | |
| def _page_file(name): | |
| path = os.path.join(_PAGE_DIR, name) | |
| if not os.path.isfile(path): | |
| raise HTTPException(status_code=404) | |
| return path | |
| def mount_embeddings(app): | |
| """Attach /embeddings routes to one FastAPI app. Safe to call again.""" | |
| if getattr(app, "_xva_embeddings", False): | |
| return app | |
| app._xva_embeddings = True | |
| def embeddings_redirect(): | |
| return RedirectResponse(url="/embeddings/") | |
| def embeddings_index(): | |
| return FileResponse(_page_file("index.html"), media_type="text/html") | |
| def embeddings_data(): | |
| if _index is None: | |
| return JSONResponse({"games": [], "voices": []}) | |
| return JSONResponse(_index.payload(_synth_ids)) | |
| def embeddings_preview(voice_id: str): | |
| path = _index.preview_file(voice_id) if _index is not None else None | |
| if not path: | |
| raise HTTPException(status_code=404) | |
| return FileResponse(path, media_type="audio/wav") | |
| def embeddings_lib(name: str): | |
| media = _LIB_FILES.get(name) | |
| if media is None: | |
| raise HTTPException(status_code=404) | |
| path = os.path.join(_LIB_DIR, name) | |
| if not os.path.isfile(path): | |
| raise HTTPException(status_code=404) | |
| return FileResponse(path, media_type=media) | |
| for page_name, media in _PAGE_FILES.items(): | |
| def _send(page_name=page_name, media=media): | |
| return FileResponse(_page_file(page_name), media_type=media) | |
| app.add_api_route( | |
| "/embeddings/" + page_name, | |
| _send, | |
| methods=["GET"], | |
| name="embeddings_asset_" + page_name.replace(".", "_"), | |
| ) | |
| return app | |
| def install_embedding_routes(): | |
| """Re-apply /embeddings on every Gradio app, including the one launch() builds.""" | |
| import gradio.routes as routes | |
| current = routes.App.create_app | |
| if getattr(current, "_xva_patched", False): | |
| return | |
| def create_app(*args, **kwargs): | |
| app = current(*args, **kwargs) | |
| mount_embeddings(app) | |
| return app | |
| create_app._xva_patched = True | |
| routes.App.create_app = create_app | |
| def _synth_voice_ids(): | |
| import gr_client | |
| found = [] | |
| for choice in list(gr_client.voice_models) + list(gr_client.voice_models_more): | |
| if isinstance(choice, (list, tuple)) and len(choice) >= 2: | |
| value = choice[1] | |
| else: | |
| value = choice | |
| if value and value != "more" and value not in found: | |
| found.append(value) | |
| return found | |
| def _merged_css(synth_blocks): | |
| base = getattr(synth_blocks, "css", None) or _ARPABET_CSS | |
| if ".arpabet" not in base: | |
| base = _ARPABET_CSS + "\n" + base | |
| return base + "\n" + _HOST_CSS | |
| def with_embeddings_tab(synth_blocks, directories): | |
| """Return a TabbedInterface: synthesizer, then the embeddings iframe.""" | |
| install_embedding_routes() | |
| index = collect_voice_embeddings(directories) | |
| set_catalog(index, _synth_voice_ids()) | |
| print("embeddings visualiser: %s voices" % len(index.voices), flush=True) | |
| with gr.Blocks() as embeddings_blocks: | |
| gr.HTML(value=_IFRAME_HTML, elem_id="xvasynth-embeddings-host") | |
| tabbed = gr.TabbedInterface( | |
| [synth_blocks, embeddings_blocks], | |
| ["Text to Speech", "Embeddings"], | |
| css=_merged_css(synth_blocks), | |
| js=_LAZY_JS, | |
| ) | |
| # title= would also render a second heading above the tabs. | |
| tabbed.title = "xVASynth TTS" | |
| return tabbed | |