Download app.py from Ekam/Libra-TTS: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/Ekam/Libra-TTS/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ekam/Libra-TTS/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ekam/Libra-TTS/resolve/main/app.py
15 kB
| """Libra TTS demo: type text, pick a voice, hear it. The ONNX release on this Space's CPU, read utterance by utterance | |
| with progress shown, then played whole with its waveform in the language's colour. The look follows the ODIN app: warm | |
| paper, one centred column, plain glass buttons, a floating player.""" | |
| import html | |
| import io | |
| import json | |
| import os | |
| import time | |
| import gradio as gr | |
| import numpy as np | |
| import soundfile as sf | |
| from libra_tts import LibraTTS | |
| from libra_tts.frontend import detect_language, language_runs | |
| from libra_tts.prompt import build_prompt | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| # the model's ONNX files ship with the Space (model/); LIBRA_MODEL points elsewhere, e.g. a local folder or a Hub repo | |
| MODEL = os.environ.get("LIBRA_MODEL") or (os.path.join(HERE, "model") if os.path.isdir(os.path.join(HERE, "model")) else None) | |
| THREADS = int(os.environ.get("LIBRA_THREADS", "2")) | |
| MAX_CHARS = 2000 | |
| LOGO = open(os.path.join(HERE, "assets", "logo.svg"), encoding="utf-8").read().strip() | |
| VOICES = [("Nina", "nina"), ("Sofia", "sofia"), ("Aliya", "aliya"), ("Maya", "maya"), ("Omar", "omar"), ("Jon", "jon"), | |
| ("Bob", "bob"), ("Sam", "sam")] | |
| LANGS = [("Automatic", "auto"), ("English", "en"), ("Chinese", "zh"), ("Japanese", "ja"), ("Korean", "ko"), | |
| ("German", "de"), ("French", "fr"), ("Spanish", "es"), ("Italian", "it"), ("Portuguese", "pt"), | |
| ("Russian", "ru"), ("Arabic", "ar"), ("Hindi", "hi"), ("Punjabi", "pa"), ("Bengali", "bn"), ("Urdu", "ur"), | |
| ("Indonesian", "id")] | |
| LANG_NAME = {c: n for n, c in LANGS} | |
| STYLES = ["warm", "cheerful", "excited", "sad", "frightened", "calm", "serious", "wry", "tender", | |
| "whispering", "dramatic", "documentary"] | |
| # the opening sample: its text fills the box and its reading is in the player when the page opens | |
| FEATURED = {"text": "Some days, the smallest moments are the ones we remember. A familiar voice, a shared laugh, " | |
| "a little good news.", "voice": "nina", "audio": os.path.join(HERE, "assets", "featured.mp3")} | |
| EXAMPLES = [ # text, voice, language, style, pace | |
| ["Take your time. There's tea on the stove, the window is open, and nobody needs anything from you for the rest " | |
| "of the evening.", "sofia", "auto", "", "normal"], | |
| ["The lighthouse keeper climbed the last stair, lit the lamp, and watched the storm roll in across the bay.", | |
| "bob", "auto", "documentary", "slow"], | |
| ["It can keep a secret. Can you?", "nina", "auto", "whispering", "normal"], | |
| ["今天天气很好,我们去公园散步吧。路上遇到了一位老朋友,聊了很久。", "aliya", "auto", "", "normal"], | |
| ["駅前の小さなカフェで、毎朝コーヒーを飲みながら新聞を読むのが好きです。", "maya", "auto", "", "normal"], | |
| ["오늘은 날씨가 정말 좋네요. 점심 먹고 같이 산책할까요?", "sam", "auto", "", "normal"], | |
| ["ਅੱਜ ਮੌਸਮ ਬਹੁਤ ਸੋਹਣਾ ਹੈ, ਇਸ ਲਈ ਸ਼ਾਮ ਨੂੰ ਅਸੀਂ ਸਾਰੇ ਪਾਰਕ ਵਿੱਚ ਸੈਰ ਕਰਨ ਚੱਲਾਂਗੇ।", "bob", "auto", "", "normal"], | |
| ["आज शाम को हम सब मिलकर खाना बनाएंगे और फिर छत पर बैठकर बातें करेंगे।", "omar", "auto", "", "normal"], | |
| ["صباح الخير، هل تريد أن نشرب القهوة معاً قبل الاجتماع؟", "aliya", "auto", "", "normal"], | |
| ["Mañana por la mañana salimos temprano hacia la montaña, así que lleva agua y una chaqueta.", "jon", "es", "", | |
| "normal"], | |
| ["Le petit marché du samedi sent le pain chaud, les fraises et le café.", "nina", "fr", "", "normal"], | |
| ["Der Zug nach Berlin hat heute leider zwanzig Minuten Verspätung.", "omar", "de", "", "normal"], | |
| ] | |
| # each language as its own script writes it, in a colour of its own | |
| GLYPH = {"en": "En", "zh": "中", "ja": "あ", "ko": "한", "de": "De", "fr": "Fr", "es": "Es", "it": "It", "pt": "Pt", | |
| "ru": "Ру", "ar": "ع", "hi": "हि", "pa": "ਪੰ", "bn": "বা", "ur": "ار", "id": "Id"} | |
| HUE = {"en": 42, "zh": 25, "ja": 350, "ko": 255, "de": 85, "fr": 268, "es": 60, "it": 150, "pt": 165, "ru": 230, | |
| "ar": 185, "hi": 55, "pa": 295, "bn": 125, "ur": 205, "id": 15} | |
| # On ZeroGPU (Hugging Face's shared GPUs) the reading runs on the GPU with the PyTorch backend, built in the GPU worker | |
| # on its first call; elsewhere ONNX Runtime on the CPU. | |
| ZERO_GPU = bool(os.environ.get("SPACES_ZERO_GPU")) | |
| tts = gpu_tts = None | |
| try: | |
| if ZERO_GPU: | |
| import spaces | |
| from libra_tts.config import model_dir | |
| MODEL_DIR = model_dir(MODEL, "cuda") # weights fetched here, on the CPU, not in GPU time | |
| def read_gpu(text, voice, lang, style, pace): | |
| global gpu_tts | |
| if gpu_tts is None: | |
| gpu_tts = LibraTTS(MODEL_DIR, backend="cuda", compile=False) | |
| t0 = time.time() | |
| audio = gpu_tts.synthesize(text, voice=voice, lang=lang, style=style or None, | |
| pace=pace if style and pace != "normal" else None, seed=0) | |
| return audio, time.time() - t0 | |
| else: | |
| tts = LibraTTS(MODEL, backend="onnx", threads=THREADS) | |
| LOAD_ERROR = None | |
| except Exception as e: # e.g. the model repo is not reachable from this Space | |
| LOAD_ERROR = f"{type(e).__name__}: {e}" | |
| try: # fetch the Japanese dictionary now rather than on the first Japanese request | |
| from libra_tts.frontend import to_kana | |
| to_kana("日本語") | |
| except Exception: | |
| pass | |
| def oklch_hex(L, C, h): | |
| """An OKLCH colour as #rrggbb (the waveform is drawn on a canvas, which takes plain colours).""" | |
| import math | |
| a, b = C * math.cos(math.radians(h)), C * math.sin(math.radians(h)) | |
| l_, m_, s_ = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3, (L - 0.1055613458 * a - 0.0638541728 * b) ** 3, \ | |
| (L - 0.0894841775 * a - 1.2914855480 * b) ** 3 | |
| rgb = (4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_, -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_, | |
| -0.0041960863 * l_ - 0.7034186147 * m_ + 1.7076147010 * s_) | |
| gamma = [12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055 for c in rgb] | |
| return "#" + "".join(f"{round(min(1, max(0, c)) * 255):02x}" for c in gamma) | |
| def waveform(lang): | |
| """The player's waveform in a language's own colour, as its example row.""" | |
| return gr.WaveformOptions(waveform_color=oklch_hex(0.84, 0.04, HUE[lang]), | |
| waveform_progress_color=oklch_hex(0.62, 0.13, HUE[lang])) | |
| # the player keeps the waveform colours it was made with (English's), so the page turns them to the language just | |
| # read: a hue rotation from English's hue to the language's, keyed by the (first) language name in the status line | |
| RECOLOR = """(status) => { | |
| const hue = %s, name = (status || "").split(/ · |, /).find(p => p in hue); | |
| if (name) document.documentElement.style.setProperty("--wave-turn", (hue[name] - hue.English) + "deg"); | |
| }""" % json.dumps({LANG_NAME[c]: h for c, h in HUE.items()}) | |
| # the character count under the text, kept in the page as it is typed or an example fills it | |
| COUNT = """(text) => { | |
| const n = (text || "").length, el = document.getElementById("chars"); | |
| if (el) { el.textContent = n.toLocaleString("en-US") + " / %s"; el.classList.toggle("full", n >= %d); } | |
| }""" % (f"{MAX_CHARS:,}", MAX_CHARS) | |
| def count_line(text): | |
| return f'<p id="chars">{len(text):,} / {MAX_CHARS:,}</p>' | |
| def example_row(ex): | |
| text, voice, lang, style, _ = ex | |
| lang = detect_language(text) if lang == "auto" else lang | |
| title = f"{LANG_NAME[lang]} · {voice.capitalize()}" + (f" · {style}" if style else "") | |
| return (f'<div class="ex" style="--c: oklch(62% 0.13 {HUE[lang]})"><div class="lg" aria-hidden="true">{GLYPH[lang]}' | |
| f'</div><div class="exbody"><b>{html.escape(title)}</b><span>{html.escape(text)}</span></div></div>') | |
| # an ID3 tag (one frame, TSSE "Libra TTS") ahead of the MP3: Gradio names the file .mp3 by an ID3 tag or an MPEG-1 | |
| # frame, and 24 kHz audio is MPEG-2 | |
| ID3 = b"ID3\x03\x00\x00\x00\x00\x00\x14" + b"TSSE\x00\x00\x00\x0a\x00\x00" + b"\x00Libra TTS" | |
| def mp3(sr, audio): | |
| """The reading as MP3 at a constant 96 kbps, a quarter of the WAV's size: the player loads the whole file before it | |
| plays, so a long reading arrives sooner. WAV if this soundfile cannot write MP3.""" | |
| pcm = (np.clip(audio, -1, 1) * 32767).astype(np.int16) | |
| try: | |
| buf = io.BytesIO() | |
| sf.write(buf, pcm, sr, format="MP3", bitrate_mode="CONSTANT", compression_level=0.4) | |
| return ID3 + buf.getvalue() | |
| except Exception: | |
| return sr, pcm | |
| def speak(text, voice, lang, style, pace, seed=0): | |
| """Utterance by utterance, as LibraTTS.synthesize reads them (same seeds), with progress as it goes; the reading | |
| then goes to the player whole (RECOLOR turns its waveform to the language's colour).""" | |
| if LOAD_ERROR: | |
| raise gr.Error(f"The model could not be loaded: {LOAD_ERROR}") | |
| text = (text or "").strip() | |
| if not text: | |
| raise gr.Error("Type something for Libra to read.") | |
| if len(text) > MAX_CHARS: | |
| raise gr.Error(f"This demo reads up to {MAX_CHARS:,} characters at a time (yours: {len(text):,}).") | |
| # with Automatic, each sentence in its own script's language (as LibraTTS.synthesize reads it); the status names | |
| # them, most text first | |
| runs = language_runs(text) if lang == "auto" else [(lang, text)] | |
| share = {} | |
| for lg, t in runs: | |
| share[lg] = share.get(lg, 0) + len(t) | |
| names = ", ".join(LANG_NAME[lg] for lg in sorted(share, key=lambda lg: -share[lg])) | |
| if ZERO_GPU: | |
| audio, el = read_gpu(text, voice, lang, style, pace) | |
| yield mp3(24000, audio), f"{names} · {len(audio) / 24000:.1f} s of audio in {el:.1f} s on a GPU" | |
| return | |
| cfg, sr = tts.cfg, tts.sample_rate | |
| instruction = cfg.style_text(style or None, pace if style and pace != "normal" else None) | |
| style_ids = tts.tok.encode_style(instruction) if instruction else None | |
| utts = [(lg, u) for lg, t in runs for u in tts.front.utterances(t, lg)] | |
| pause = np.zeros(int(0.3 * sr), np.float32) | |
| t0, total, parts = time.time(), 0, [] | |
| for i, (lg, u) in enumerate(utts): | |
| prompt = build_prompt(cfg, tts.front.encode(u, lg), voice, lg, style_ids) | |
| cap = min(cfg.max_frames, int(len(u) / cfg.language(lg)["chars_per_second"] * cfg.frame_rate * 2.5) + 75) | |
| codes = tts.backend.generate(prompt, (int(seed) * 1000003 + 7919 * i) & 0x7FFFFFFF, cap, cfg.sampling) | |
| audio = tts.backend.decode(codes) | |
| audio = np.concatenate([pause, audio]) if i else audio | |
| parts.append(audio) | |
| total += len(audio) | |
| el = time.time() - t0 | |
| note = f"{names} · {total / sr:.1f} s of audio in {el:.1f} s on {THREADS} CPU cores" | |
| if i + 1 < len(utts): | |
| note = f"Reading {i + 1} of {len(utts)} · " + note | |
| if i + 1 < len(utts): | |
| yield gr.skip(), note | |
| yield mp3(sr, np.concatenate(parts)), note | |
| THEME = gr.themes.Base(primary_hue=gr.themes.colors.blue, neutral_hue=gr.themes.colors.stone, | |
| radius_size=gr.themes.sizes.radius_lg, | |
| font=[gr.themes.Font(f) for f in ("Helvetica Neue", "Arial", "sans-serif")], | |
| font_mono=[gr.themes.Font(f) for f in ("Menlo", "Consolas", "monospace")]) | |
| CSS = open(os.path.join(HERE, "assets", "odin.css"), encoding="utf-8").read() | |
| # icons: Lucide (ISC, lucide.dev), the set the ODIN app uses, drawn with its stroke | |
| def lucide(*paths, stroke=2): | |
| return ('<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="%s" stroke-linecap="round" ' | |
| 'stroke-linejoin="round">%s</svg>' % (stroke, "".join(f'<path d="{d}"/>' for d in paths))) | |
| ICON_MODEL = lucide("M12 15V3", "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", "m7 10 5 5 5-5") # download | |
| ICON_CODE = lucide("m16 18 6-6-6-6", "m8 6-6 6 6 6") # code | |
| with gr.Blocks(title="Libra TTS") as demo: | |
| gr.HTML(f"""<header id="row1"><div class="mark" aria-hidden="true"></div><div class="logo">{LOGO}</div><nav class="capsule glass"> | |
| <a href="https://huggingface.co/Ekam/Libra-TTS" target="_blank" title="Model" aria-label="Model">{ICON_MODEL}</a> | |
| <a href="https://github.com/ekambrar100/Libra-TTS" target="_blank" title="Code" aria-label="Code">{ICON_CODE}</a> | |
| </nav></header><p id="count">Text to speech · 16 languages · 8 voices · 0.3B parameters</p>""") | |
| text = gr.Textbox(value=FEATURED["text"], show_label=False, lines=4, max_lines=12, max_length=MAX_CHARS, | |
| placeholder="Type anything: numbers, dates, prices and times are read as written.", | |
| elem_id="sheet", container=False) | |
| gr.HTML(count_line(FEATURED["text"])) | |
| with gr.Row(elem_id="controls", equal_height=True): | |
| voice = gr.Dropdown(VOICES, value=FEATURED["voice"], label="Voice", elem_classes="pick", min_width=120) | |
| lang = gr.Dropdown(LANGS, value="auto", label="Language", elem_classes="pick", min_width=140) | |
| style = gr.Dropdown([("None", "")] + [(s.capitalize(), s) for s in STYLES], value="", label="Style", | |
| elem_classes="pick", min_width=130) | |
| pace = gr.Radio([("Normal", "normal"), ("Slow", "slow"), ("Fast", "fast")], value="normal", label="Pace", | |
| elem_classes="pick seg", min_width=210) | |
| with gr.Row(elem_id="go-row"): | |
| go = gr.Button("Read aloud", elem_id="go", elem_classes="glass") | |
| status = gr.Markdown(elem_id="status") | |
| audio = gr.Audio(value=FEATURED["audio"] if os.path.exists(FEATURED["audio"]) else None, label="Reading aloud", | |
| autoplay=True, buttons=["download"], elem_id="player", elem_classes="glass", | |
| waveform_options=waveform("en")) | |
| gr.HTML('<p class="hint">Latin-script text is read as English unless you pick its language.</p>') | |
| gr.HTML('<h2 id="more">More to try</h2>') | |
| ex = gr.Dataset(components=[gr.HTML(visible=False)], samples=[[example_row(e)] for e in EXAMPLES], | |
| type="index", layout="gallery", samples_per_page=len(EXAMPLES), elem_id="examples", | |
| show_label=False, container=False) | |
| gr.HTML('<footer id="foot">Libra TTS reads on ' + ("a GPU with PyTorch" if ZERO_GPU else | |
| "this Space’s CPU with ONNX Runtime") + '. Apache 2.0.</footer>') | |
| ex.click(lambda i: EXAMPLES[i], ex, [text, voice, lang, style, pace]) | |
| go.click(speak, [text, voice, lang, style, pace], [audio, status]) | |
| status.change(None, status, None, js=RECOLOR) | |
| text.change(None, text, None, js=COUNT) | |
| text.submit(speak, [text, voice, lang, style, pace], [audio, status]) | |
| demo.queue(default_concurrency_limit=1, max_size=32) | |
| if __name__ == "__main__": | |
| demo.launch(theme=THEME, css=CSS) | |