"""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 @spaces.GPU(duration=60) 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'
{len(text):,} / {MAX_CHARS:,}
' 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'Text to speech · 16 languages · 8 voices · 0.3B parameters
""") 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('Latin-script text is read as English unless you pick its language.
') gr.HTML('