Spaces:
Running on Zero

lomasub-open / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
0ce7c91 verified
Raw History Blame Contribute Delete
22.8 kB
import spaces # must come before any torch / CUDA-touching import
import os
import tempfile
import time
import gradio as gr
import torch
from transformers import pipeline
MODEL_ID = "lomasub/lomasub-open"
MODEL_URL = f"https://huggingface.co/{MODEL_ID}"
DATASET_URL = "https://huggingface.co/datasets/lomasub/thai_asr_corrected"
THEME = gr.themes.Citrus()
# NOTE: Gradio 6 rewrites every selector in `css=` to
# `.gradio-container.gradio-container-X .contain <selector>`, which means
# top-level selectors like `:root` and `.dark` never match and any custom
# property defined there resolves to nothing. This sheet is injected through
# `launch(head=...)` instead, which lands in <head> verbatim and un-scoped.
CSS = """
:root {
--thai-indigo: #4338ca;
--thai-royal: #6366f1;
--thai-gold: #fbbf24;
--panel-bg: rgba(255, 255, 255, 0.75);
--panel-line: rgba(30, 27, 75, 0.12);
--panel-shadow: 0 18px 40px -28px rgba(30, 27, 75, 0.5);
--pill-fg: #eef2ff;
}
.dark {
--panel-bg: rgba(23, 23, 42, 0.62);
--panel-line: rgba(129, 140, 248, 0.18);
--panel-shadow: 0 18px 44px -30px rgba(0, 0, 0, 0.9);
--pill-fg: #eef2ff;
}
/* Citrus dark mode leaves the container text color unset; restore it. */
.dark .gradio-container { color: var(--body-text-color); }
main, .gradio-container {
max-width: 1100px !important;
margin-left: auto !important;
margin-right: auto !important;
}
/* ---------- hero ---------- */
#hero {
position: relative;
overflow: hidden;
border-radius: 26px;
padding: 34px 34px 26px;
margin-bottom: 22px;
color: #f5f3ff;
background: linear-gradient(118deg, #1e1b4b 0%, #3730a3 34%, #6366f1 68%, #b45309 130%);
background-size: 240% 240%;
animation: thai-drift 26s ease-in-out infinite;
box-shadow: 0 30px 70px -40px rgba(30, 27, 75, 0.9);
}
@keyframes thai-drift {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
#hero::after {
content: "";
position: absolute;
inset: 0;
background:
radial-gradient(60% 90% at 12% 8%, rgba(255, 255, 255, 0.2), transparent 60%),
radial-gradient(50% 80% at 88% 92%, rgba(251, 191, 36, 0.32), transparent 65%);
pointer-events: none;
}
#hero > * { position: relative; z-index: 1; }
.hero-eyebrow {
font-size: 0.72rem !important;
letter-spacing: 0.32em;
text-transform: uppercase;
opacity: 0.78;
margin: 0 0 12px !important;
color: #f5f3ff !important;
}
/* Gradio ships `.gradio-container-X h1 { font-size: inherit }`, which outranks
a bare class selector from <head> — hence the !important here. */
.hero-title {
margin: 0 !important;
font-size: clamp(1.9rem, 4.4vw, 2.9rem) !important;
font-weight: 700 !important;
line-height: 1.12 !important;
letter-spacing: -0.02em;
color: #f5f3ff !important;
text-wrap: balance;
}
.hero-title em {
font-style: normal;
background: linear-gradient(92deg, #fde68a, #fbbf24);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.hero-sub {
margin: 12px 0 0 !important;
max-width: 62ch;
font-size: 1rem !important;
line-height: 1.6 !important;
color: #f5f3ff !important;
opacity: 0.9;
}
.hero-sub a { color: #fde68a; text-decoration: none; border-bottom: 1px solid rgba(253, 230, 138, 0.45); }
.hero-sub a:hover { border-bottom-color: #fde68a; }
.pills { display: flex; flex-wrap: wrap; gap: 9px; margin-top: 22px; }
.pill {
display: inline-flex;
align-items: baseline;
gap: 7px;
padding: 7px 14px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.13);
border: 1px solid rgba(255, 255, 255, 0.22);
backdrop-filter: blur(9px);
-webkit-backdrop-filter: blur(9px);
color: var(--pill-fg);
font-size: 0.82rem;
}
.pill b { font-size: 1rem; font-weight: 700; letter-spacing: -0.01em; }
.pill span { opacity: 0.72; text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.64rem; }
.wave { display: flex; align-items: flex-end; gap: 4px; height: 34px; margin-top: 26px; opacity: 0.75; }
.wave i {
width: 4px;
border-radius: 3px;
background: linear-gradient(180deg, #fde68a, #a5b4fc);
animation: wave-bounce 1.5s ease-in-out infinite;
}
@keyframes wave-bounce {
0%, 100% { height: 7px; }
50% { height: 32px; }
}
/* ---------- panels ----------
`elem_classes` is dropped on gr.Column in Gradio 6, so these hang off
elem_id instead, which renders reliably. */
#panel-in, #panel-out {
background: var(--panel-bg) !important;
border: 1px solid var(--panel-line) !important;
border-radius: 20px !important;
padding: 18px !important;
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
box-shadow: var(--panel-shadow);
}
.panel-title {
display: flex;
align-items: center;
gap: 9px;
font-size: 0.76rem;
font-weight: 600;
letter-spacing: 0.16em;
text-transform: uppercase;
opacity: 0.6;
margin: 2px 2px 14px;
}
.panel-title::before {
content: "";
width: 7px; height: 7px;
border-radius: 50%;
background: var(--thai-royal);
box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.18);
}
/* ---------- primary button ---------- */
#go-btn {
background: linear-gradient(96deg, #3730a3, var(--thai-royal) 55%, #b45309) !important;
background-size: 180% 100% !important;
border: none !important;
color: #fff !important;
font-weight: 700 !important;
letter-spacing: 0.01em;
font-size: 1rem !important;
padding: 13px 20px !important;
box-shadow: 0 12px 30px -14px rgba(99, 102, 241, 0.85);
transition: background-position 0.5s ease, transform 0.15s ease, box-shadow 0.25s ease;
}
#go-btn:hover {
background-position: 100% 0 !important;
transform: translateY(-1px);
box-shadow: 0 18px 38px -14px rgba(180, 83, 9, 0.8);
}
#go-btn:active { transform: translateY(0); }
/* ---------- transcript ---------- */
#transcript textarea {
font-size: 1.06rem !important;
line-height: 1.75 !important;
background: transparent !important;
border: none !important;
box-shadow: none !important;
}
#stats { min-height: 34px; }
.stat-row { display: flex; flex-wrap: wrap; gap: 8px; }
.stat {
display: inline-flex;
align-items: baseline;
gap: 6px;
padding: 6px 12px;
border-radius: 10px;
border: 1px solid var(--panel-line);
background: rgba(99, 102, 241, 0.08);
font-size: 0.8rem;
}
.stat b { font-family: var(--font-mono); font-weight: 700; }
.stat span { opacity: 0.62; text-transform: uppercase; letter-spacing: 0.07em; font-size: 0.64rem; }
.stat-idle { opacity: 0.5; font-size: 0.82rem; padding: 7px 2px; }
/* ---------- footer ---------- */
#foot {
margin-top: 26px;
padding-top: 18px;
border-top: 1px solid var(--panel-line);
text-align: center;
font-size: 0.8rem;
opacity: 0.62;
line-height: 1.7;
}
#foot a { color: inherit; }
@media (prefers-reduced-motion: reduce) {
#hero { animation: none; }
.wave i { animation: none; height: 18px; }
}
@media (max-width: 560px) {
.gradio-container, .main.fillable {
max-width: 100% !important;
overflow-x: hidden;
}
#hero {
padding: 26px 20px 22px;
border-radius: 20px;
}
.hero-eyebrow { letter-spacing: 0.22em; }
.wave { margin-top: 18px; height: 26px; }
}
"""
device = "cuda" if torch.cuda.is_available() else "cpu"
# Reference usage from the model card:
# asr = pipeline("automatic-speech-recognition", model="lomasub/lomasub-open")
# result = asr("audio.wav", generate_kwargs={"language": "th", "task": "transcribe"})
# (device/dtype handling adapted for ZeroGPU; decoding params kept identical.)
asr_pipe = pipeline(
"automatic-speech-recognition",
model=MODEL_ID,
device=device,
)
MAX_AUDIO_SECONDS = 300 # 5 minutes
def _audio_seconds(path):
"""Best-effort read of an audio file's duration, in seconds."""
try:
import soundfile as sf
info = sf.info(path)
return info.frames / float(info.samplerate)
except Exception:
pass
try:
import torchaudio
info = torchaudio.info(path)
return info.num_frames / float(info.sample_rate)
except Exception:
pass
return None
def _duration_estimate(audio, *args, **kwargs):
"""Estimate GPU seconds from the audio length.
Measured on ZeroGPU (RTX PRO 6000): ~1.0 s GPU for a 7 s clip, ~0.5 s
for a 29 s clip — the 4-layer decoder is fast, and long inputs mostly
pay decode time per 30 s chunk. This formula covers that with headroom
for the first-call cold start on a fresh worker (capped at 20 s for
the 5-minute input limit).
`audio` arrives as a filepath; `*args`/`**kwargs` swallow the extra
Gradio parameters (progress) safely.
"""
seconds = _audio_seconds(audio)
if seconds is None:
seconds = 60.0
return int(round(min(20, 4 + 0.25 * seconds)))
def _write(name, content):
"""Write `content` into a fresh temp dir and return the file path.
A fresh directory per call keeps concurrent requests from clobbering each
other's downloads on ZeroGPU.
"""
path = os.path.join(tempfile.mkdtemp(), name)
with open(path, "w", encoding="utf-8") as fh:
fh.write(content)
return path
def _stats_html(text, audio_seconds, elapsed):
"""Render the stat pills shown under the transcript."""
chars = len(text)
items = []
if audio_seconds:
items.append(("เสียง / audio", f"{audio_seconds:.1f}s"))
items.append(("ตัวอักษร / chars", str(chars)))
items.append(("เวลา / compute", f"{elapsed:.1f}s"))
# Guard against a near-zero elapsed time producing an absurd multiplier.
if audio_seconds and elapsed >= 0.05:
items.append(("ความเร็ว / speed", f"{audio_seconds / elapsed:.1f}×"))
cells = "".join(f"<div class='stat'><b>{v}</b><span>{k}</span></div>" for k, v in items)
return f"<div class='stat-row'>{cells}</div>"
IDLE_STATS = (
"<div class='stat-idle'>อัปโหลดไฟล์เสียงหรืออัดเสียงจากไมโครโฟน "
"— Upload an audio file or record from your microphone.</div>"
)
# Reference transcripts for the bundled example clips, from the test split of
# the authors' benchmark dataset (CC-BY-4.0).
REFERENCE_TRANSCRIPTS = {
"samples/fleurs_moon.mp3": (
"พื้นผิวของดวงจันทร์ประกอบด้วยหินและฝุ่น พื้นผิวชั้นนอกของดวงจันทร์เรียกว่าเปลือก"
),
"samples/fleurs_history.mp3": (
"พวกเขาเดินทางกลับปารีสไปในรถม้าซึ่งรายล้อมด้วยฝูงชนที่ตะคอกและข่มขู่พระมหากษัตริย์และพระราชินี"
),
"samples/fleurs_genetics.mp3": (
"เฉพาะการกลายพันธุ์ในเซลล์ถ่ายทอดสารพันธุกรรมเท่านั้น ที่จะสามารถถ่ายทอดไปยังบุตรหลานได้ "
"ในขณะที่การกลายพันธุ์ที่อื่นอาจทำให้เกิดเซลล์ตายหรือกลายเป็นเซลล์มะเร็ง"
),
"samples/tvspeech_media.mp3": (
"การใช้สื่อในรุ่นใหม่ ในการหาเสียง ทำให้พรรคที่ไม่ต้องใช้ต้นทุนมากสามารถที่จะเข้าถึงประชาชนได้กว้าง "
"แล้วก็ได้คะแนนเสียงเป็นกอบเป็นกำ นั่นบริบทที่หนึ่ง"
),
}
# Runs in the browser before `transcribe`. The Audio component only gets a value
# once a recording (or upload) has been sent to the server, and there are two
# ways to click Transcribe before that happens:
# * the microphone is still recording or paused — Gradio never uploads until
# Stop, so press Stop for the user (the recorder resumes a paused take first);
# * Stop was pressed a moment ago and the upload is still in flight — the
# recorder is already unmounted but the player is not there yet, so the
# component shows nothing at all ("limbo") for the whole upload.
# In both cases wait for the value: the recorder sets it only after the upload
# resolves, and the player then renders its download link with a
# `/gradio_api/file=` href, which is the earliest reliable "ready" signal in the
# DOM. If the component is simply empty (idle record button visible) return at
# once and let the server raise its explanatory error. The `recorderMounted`
# guard makes this a no-op if a future Gradio renames the recorder's classes,
# so the click falls through to the server instead of hanging.
STOP_RECORDING_JS = """
async () => {
const root = document.querySelector('#panel-in') || document;
const q = s => root.querySelector(s);
const vis = el => !!(el && el.offsetParent !== null);
const ready = () => !!q('a.download-link[href*="gradio_api/file="]');
const idle = () => vis(q('button.record_button'));
const recorderMounted = !!q('button.record_button') || !!q('button.stop-button');
if (ready()) return;
if (!recorderMounted) return;
if (vis(q('button.stop-button')) || vis(q('#stop-paused')) || vis(q('button.resume-button'))) {
q('button.stop-button').click(); // handles both recording and paused
} else if (idle()) {
return;
}
// The upload to the Space can take a few seconds; say so on the button meanwhile.
const btn = document.querySelector('#go-btn');
const label = btn ? btn.textContent : null;
if (btn) { btn.textContent = 'กำลังอัปโหลดเสียง… · Uploading audio…'; btn.disabled = true; }
try {
const t0 = Date.now();
while (Date.now() - t0 < 30000) {
await new Promise(r => setTimeout(r, 100));
if (ready() || idle()) return;
}
} finally {
if (btn) { btn.textContent = label; btn.disabled = false; }
}
}
"""
@spaces.GPU(duration=_duration_estimate)
def transcribe(audio: str | None, progress=gr.Progress(track_tqdm=True)) -> tuple[str, str, str]:
"""Transcribe Thai speech to text.
Args:
audio: an audio recording (upload a WAV/MP3/OGG/FLAC file or record
from your microphone). Resampled to 16 kHz mono automatically.
progress: Gradio progress bar.
Returns:
The transcript, a stats HTML block, and a .txt download file.
"""
if audio is None:
raise gr.Error(
"ยังไม่มีไฟล์เสียง — กด ■ Stop เพื่อหยุดการอัดเสียง (Pause ไม่พอ) "
"หรืออัปโหลดไฟล์ แล้วจึงกดถอดเสียง — No audio yet: press ■ Stop to "
"finish the recording (Pause is not enough), or upload a file, then "
"transcribe."
)
audio_seconds = _audio_seconds(audio)
if audio_seconds is not None and audio_seconds > MAX_AUDIO_SECONDS:
raise gr.Error(
f"ไฟล์เสียงยาว {audio_seconds / 60:.1f} นาที — โปรดใช้ไฟล์ที่สั้นกว่า "
f"{MAX_AUDIO_SECONDS // 60} นาที — Audio is {audio_seconds / 60:.1f} min. "
f"Please keep it under {MAX_AUDIO_SECONDS // 60} minutes."
)
t0 = time.perf_counter()
# Exactly the model card's decoding recipe: force Thai transcription;
# 30 s chunks with a (5, 1) s stride for longer inputs.
result = asr_pipe(
audio,
generate_kwargs={"language": "th", "task": "transcribe"},
chunk_length_s=30,
stride_length_s=(5, 1),
)
elapsed = time.perf_counter() - t0
text = result["text"].strip()
# Return plain file paths, never component updates: changing a
# DownloadButton's config crashes Gradio 6 during example caching.
return (
text,
_stats_html(text, audio_seconds, elapsed),
_write("transcript.txt", text + "\n"),
)
with gr.Blocks(title="lomasub-open · Thai ASR", fill_width=False) as demo:
gr.HTML(
f"""
<div id="hero">
<p class="hero-eyebrow">ภาษาไทย &middot; Thai &middot; open source</p>
<h1 class="hero-title">ถอดเสียงพูดภาษาไทยเป็น<em>ข้อความ</em></h1>
<p class="hero-sub">
Thai speech&nbsp;&rarr;&nbsp;text with
<a href="{MODEL_URL}" target="_blank" rel="noopener">lomasub-open</a> —
a compact 166M-parameter ASR model distilled from OpenAI Whisper-small
(12-layer encoder, 4-layer decoder) with a 4,000-word Thai vocabulary,
evaluated on the authors'
<a href="{DATASET_URL}" target="_blank" rel="noopener">Thai ASR benchmark</a>.
</p>
<div class="pills">
<div class="pill"><b>2.51%</b><span>CER · FLEURS</span></div>
<div class="pill"><b>3.60%</b><span>CER · TVSpeech</span></div>
<div class="pill"><b>166M</b><span>params</span></div>
<div class="pill"><b>Apache-2.0</b><span>license</span></div>
</div>
<div class="wave" aria-hidden="true">
<i style="animation-delay:0s"></i><i style="animation-delay:.12s"></i>
<i style="animation-delay:.24s"></i><i style="animation-delay:.36s"></i>
<i style="animation-delay:.48s"></i><i style="animation-delay:.6s"></i>
<i style="animation-delay:.72s"></i><i style="animation-delay:.84s"></i>
<i style="animation-delay:.96s"></i><i style="animation-delay:1.08s"></i>
<i style="animation-delay:1.2s"></i><i style="animation-delay:1.32s"></i>
</div>
</div>
"""
)
with gr.Row(equal_height=False):
with gr.Column(scale=1, elem_id="panel-in"):
gr.HTML("<div class='panel-title'>เสียง &middot; input</div>")
audio_in = gr.Audio(
label="ไฟล์เสียง · Audio — WAV / MP3 / OGG / FLAC, up to 5 min",
type="filepath",
sources=["upload", "microphone"],
format="wav",
waveform_options=gr.WaveformOptions(
waveform_color="#a5b4fc",
waveform_progress_color="#4338ca",
trim_region_color="#fbbf24",
),
)
run_btn = gr.Button("ถอดเสียงเป็นข้อความ · Transcribe", variant="primary", elem_id="go-btn")
with gr.Column(scale=1, elem_id="panel-out"):
gr.HTML("<div class='panel-title'>ข้อความถอดเสียง &middot; output</div>")
transcript_out = gr.Textbox(
label="ข้อความ / Transcript",
info="Thai transcription",
lines=9,
buttons=["copy"],
elem_id="transcript",
placeholder="ข้อความจะปรากฏที่นี่… / The transcription will appear here…",
)
stats_out = gr.HTML(IDLE_STATS, elem_id="stats")
txt_btn = gr.DownloadButton("⭳ .txt", size="sm")
with gr.Accordion("รายละเอียดและผลอ้างอิง · How it works & reference transcripts", open=False):
gr.Markdown(
f"""
Inference follows the [model card]({MODEL_URL}) exactly: the transformers
`automatic-speech-recognition` pipeline with
`generate_kwargs={{"language": "th", "task": "transcribe"}}`, and 30&nbsp;s
chunking (`chunk_length_s=30`, `stride_length_s=(5, 1)`) for longer inputs.
Upload any WAV / MP3 / OGG / FLAC file or speak into your microphone — audio is
resampled to 16&nbsp;kHz mono automatically. The model is Thai-only: timestamps,
English, and code-switching were **not** part of its evaluation.
| Benchmark | CER |
| :--- | :--- |
| FLEURS (th) | 2.51% |
| TVSpeech | 3.60% |
| GigaSpeech2 v2 | 6.00% |
**Reference transcripts** for the bundled examples (human-corrected labels from
the [{DATASET_URL.split('/')[-1]} benchmark]({DATASET_URL}) test split, CC-BY-4.0) — compare them
with the model output:
| Clip | Reference transcript |
| :--- | :--- |
| 🌙 FLEURS · moon | {REFERENCE_TRANSCRIPTS["samples/fleurs_moon.mp3"]} |
| 🏛 FLEURS · history | {REFERENCE_TRANSCRIPTS["samples/fleurs_history.mp3"]} |
| 🧬 FLEURS · genetics | {REFERENCE_TRANSCRIPTS["samples/fleurs_genetics.mp3"]} |
| 📺 TVSpeech · media | {REFERENCE_TRANSCRIPTS["samples/tvspeech_media.mp3"]} *(reference label covers the first ~20 s; the clip runs on, so the model also transcribes the following sentences)* |
"""
)
# Only the audio is bound as an example input — that is the single varied
# parameter, and binding just it keeps the examples table one column wide.
gr.Examples(
examples=[
["samples/fleurs_moon.mp3"],
["samples/fleurs_history.mp3"],
["samples/fleurs_genetics.mp3"],
["samples/tvspeech_media.mp3"],
],
inputs=[audio_in],
outputs=[transcript_out, stats_out, txt_btn],
fn=transcribe,
# Cache the examples: each one then costs GPU only once per container,
# so visitors get instant results without spending their ZeroGPU quota.
cache_examples=True,
cache_mode="lazy",
examples_per_page=4,
label="ตัวอย่าง · Examples",
)
gr.HTML(
f"""
<div id="foot">
<a href="{MODEL_URL}" target="_blank" rel="noopener">Model</a> ·
<a href="{DATASET_URL}" target="_blank" rel="noopener">Benchmark dataset</a> ·
Apache-2.0 &middot; example audio CC-BY-4.0
</div>
"""
)
# Two steps: first the client-side stop-and-wait (no-op when nothing is
# recording), then the model in a chained event that reads the Audio value
# only once the first step has finished.
run_btn.click(None, js=STOP_RECORDING_JS).then(
transcribe,
inputs=[audio_in],
outputs=[transcript_out, stats_out, txt_btn],
api_name="transcribe",
)
if __name__ == "__main__":
# In Gradio 6, `theme` belongs to launch(), not the Blocks constructor.
demo.launch(mcp_server=True, theme=THEME, head=f"<style>{CSS}</style>")