feat(demo): live Static Space — Whisper runs in the visitor's browser

HF's 2026 pricing gates Gradio/Docker Spaces behind PRO (create_repo came
back 402), so the demo ships as a free Static Space instead: transformers.js
runs Whisper ONNX q8 entirely client-side — RTL Persian UI, mic + file +
bundled benchmark sample clip, base/small selectable, nothing uploaded.

Verified end to end with a headless browser: it loaded the Space, fetched
the bundled Common Voice (fa) sample, downloaded the model and transcribed
the clip on-device (3.5 s clip in 5.0 s); screenshot embedded in the README.
One real bug found and fixed by that test: the sample path deadlocked on
the busy-guard before starting inference.

- space/: static demo (index.html/demo.js/worker.js) at the root; the
  Gradio app moves to space/gradio/ for self-hosting or PRO Spaces
- model card published to hf.co/Abol0pati/whisper-small-fa-sokhan with the
  measured numbers and honest caveats; demo paragraph updated to describe
  what actually runs where
- notebook: cell 10 now writes the model card only (a Colab-run Gradio
  Space would 402), new cell 11 uploads merged HF weights to unlock the
  ONNX/browser fine-tune path
- ROADMAP: v1.3 progress recorded with the pricing discovery; new item
  for pointing the browser demo at the fine-tuned ONNX
This commit is contained in:
Abolfazl Ranjbaran committed 2026-11-18 13:02:49 +00:00
1 parent 9f47d1da50
commit 9a2c2ba558
12 files changed
+511 -73

No files matched your search

+12 -10
View File
@@ -7,16 +7,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
### Added
- A public **browser demo** (`space/`): a Gradio Space that serves the
fine-tuned checkpoint with the production engine (faster-whisper, CPU
int8) and lets anyone A/B the same clip against the untuned `small`
baseline; publishable from the Colab notebook in one cell (cell 10) with
the Space and its RTL Persian UI, plus a note that first inference
downloads the model
- A proper **Hugging Face model card** (`training/model_card.md`) with the
measured WER/CER, honest caveats (12-clip fixture, 500-clip training
set), usage snippet and full reproduction instructions — cell 10 writes
it onto the model repo as `README.md`
- A public **browser demo** (`space/`): a free Static Space where Whisper
runs entirely client-side (transformers.js, ONNX q8, base/small
selectable, RTL Persian UI, bundled benchmark sample clip — a headless
browser verified it end to end: 3.5 s clip transcribed in 5.0 s
on-device); plus `space/gradio/`, a self-hostable Gradio app serving the
fine-tuned checkpoint with the production engine config — HF's 2026
pricing gates hosted Gradio/Docker Spaces behind a PRO subscription
(402 on create), which is why the free Space is the static page
- A proper **Hugging Face model card** (`training/model_card.md`),
published to the whisper-small repo with the measured WER/CER, honest
caveats (12-clip fixture, 500-clip training set), usage snippet and full
reproduction instructions
- `docs/ROADMAP.md` — versioned phases (v1.3 public face, v1.4 engine
quality, v1.5 product surface, v2.0 candidates) under the
measurement-first rule
+12 -3
View File
@@ -4,9 +4,13 @@
**Persian-first speech-to-text toolkit.** Send a voice message — get back a transcript and a summary.
**Try it in the browser first:** the fine-tuned Persian checkpoint runs as a
public demo at [hf.co/spaces/Abol0pati/sokhan-fa-demo](https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo)
— mic or file upload, A/B against the untuned baseline, nothing to install.
**Try it in the browser first:** the public demo at
[hf.co/spaces/Abol0pati/sokhan-fa-demo](https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo)
runs Whisper entirely client-side (transformers.js, ONNX q8) — mic or file
upload, base/small selectable, nothing to install, nothing uploaded. The
**fine-tuned** checkpoint ships as a self-hostable Gradio app
([space/gradio/](space/gradio/)); HF's 2026 pricing gates hosted Gradio
Spaces behind PRO, so the free Space is the static page.
Sokhan runs entirely on your own hardware: a FastAPI service with a
faster-whisper engine, a Celery worker, a Next.js dashboard written
@@ -20,6 +24,11 @@ get the transcript (recorded against the actual app, no mockups):
![Sokhan demo — upload, transcription and archive search](docs/assets/demo.gif)
The same Space demo, after transcribing a real Common Voice (fa) clip in a
headless browser (3.5 s clip, 5.0 s on-device):
![Sokhan browser demo on a free Static Space — Whisper runs on the visitor's machine](docs/assets/demo-space.png)
## Why
Most speech-to-text tooling treats Persian as an afterthought. Sokhan is
+19 -6
View File
@@ -7,12 +7,20 @@ reproduces it). Dated entries move to `CHANGELOG.md` when they land.
## v1.3 — public face (current work)
- [x] Gradio demo app (`space/`) — A/B radio: fine-tuned checkpoint vs
untuned baseline, Persian RTL UI, CPU int8
- [ ] Publish the Space (`Abol0pati/sokhan-fa-demo`) and link it from the
README — notebook cell 10 does it in ~2 minutes
- [ ] Model card on both fine-tuned repos (notebook cell 10 writes it;
`training/model_card.md` is the source of truth for numbers)
- [x] Demo app (`space/`) — RTL Persian UI, mic + file + bundled sample
clip. Shipped in two flavors: the free **Static Space** runs Whisper
client-side (transformers.js, ONNX q8, base/small selectable,
nothing uploaded), and the **Gradio app** (`space/gradio/`) serves
the fine-tuned checkpoint with the production faster-whisper config
for self-hosting — HF's 2026 pricing gates hosted Gradio/Docker
Spaces behind a PRO subscription, which is what made the split
necessary (discovered live: `402 Payment Required` on
`create_repo(sdk="gradio")`)
- [x] Space published and verified end to end: a headless browser loaded
it, transcribed a real Common Voice (fa) clip on-device (3.5 s clip,
5.0 s wall) — https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo
- [x] Model card on the whisper-small repo (the tiny repo already had
one): measured numbers, honest caveats, usage snippet
- [ ] **The scaled fine-tune.** The v1.2.0 run (500 clips) beat the
baseline by 1.2 WER points — at the edge of the fixture's noise
floor. The same notebook at `MAX_SAMPLES = 0` (~10 h of speech,
@@ -20,6 +28,11 @@ reproduces it). Dated entries move to `CHANGELOG.md` when they land.
the training kit. After it: re-benchmark, update the model card,
and publish the new checkpoint — then the 500-clip run becomes the
ablation row.
- [ ] **Fine-tuned checkpoint in the browser.** Upload the merged HF
weights (notebook cell 11; the merged folder only exists right
after a training run), export ONNX, and point the client-side demo
at it — the free Static Space would then demo the *fine-tuned*
model with zero hosting cost.
- [ ] A bigger eval fixture (target: 200 clips, stratified by age/gender
and accent bands) so WER deltas stop being noise-limited
Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

+20 -15
View File
@@ -3,26 +3,31 @@ title: Sokhan سخن
emoji: "\U0001F3A4"
colorFrom: indigo
colorTo: purple
sdk: gradio
app_file: app.py
sdk: static
pinned: false
license: mit
short_description: تبدیل گفتار فارسی به نوشتار — مدل ریزتنظیم‌شده Whisper
short_description: تبدیل گفتار فارسی به نوشتار — اجرا کامل درون مرورگر
---
# Sokhan — Persian speech-to-text demo
# Sokhan — Persian speech-to-text, in your browser
A live demo of [Sokhan](https://github.com/Abolfazlrwm/sokhan)'s speech
engine: faster-whisper on CPU (int8) serving a LoRA fine-tuned
`whisper-small` checkpoint trained on 500 Common Voice (fa) clips on a
free Colab T4 —
[`Abol0pati/whisper-small-fa-sokhan`](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan).
engine that runs **entirely client-side**: Whisper (ONNX, q8) executes on
the visitor's own machine via
[transformers.js](https://huggingface.co/docs/transformers.js) — nothing
is uploaded, no backend, no compute cost. Persian RTL UI, mic recording,
file upload and a bundled benchmark sample clip.
The radio lets you A/B the same clip through the fine-tuned model and the
untuned `small` baseline. Measured on the project's fixed 12-clip fixture:
**WER 79.3%** (fine-tuned) vs **80.5%** (baseline) — a real but small
margin, honestly at the edge of noise on a fixture this size. Persian
Common Voice is colloquial and noisy; expect mistakes.
Two untuned checkpoints are selectable (base / small) so anyone can hear
the difference. The **fine-tuned** checkpoint
([`Abol0pati/whisper-small-fa-sokhan`](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan),
LoRA on 500 Common Voice fa clips, measured WER 79.3% vs 80.5% baseline)
is served by the same engine Sokhan runs in production — the app for that
lives in [`space/gradio/`](https://github.com/Abolfazlrwm/sokhan/tree/main/space/gradio)
for self-hosting, because HF's 2026 pricing gates hosted Gradio/Docker
Spaces behind a PRO subscription and only **static** Spaces (like this
page) remain free. Porting the fine-tune to ONNX for the browser is on
the roadmap ([docs/ROADMAP.md](https://github.com/Abolfazlrwm/sokhan/blob/main/docs/ROADMAP.md)).
Self-hosting the full product (web dashboard, Telegram bot, API, archive):
see the repository README.
Persian Common Voice is colloquial and noisy — expect real mistakes, from
every Whisper size.
+205
View File
@@ -0,0 +1,205 @@
// Sokhan demo UI wiring — audio capture (mic / file / bundled sample),
// resampling to 16 kHz mono, and talking to the transformers.js worker.
// All inference happens client-side; see worker.js.
const SAMPLE_URL =
"https://raw.githubusercontent.com/Abolfazlrwm/sokhan/main/benchmarks/data/clips/cv_fa_00001501_39aee6016733.wav";
// Human-verified reference from the benchmark fixture, shown for honest
// comparison after the sample is transcribed.
const SAMPLE_REFERENCE = "معلومه حسابی قاطی کردی";
const $ = (id) => document.getElementById(id);
const modelSel = $("model");
const micBtn = $("mic");
const sampleBtn = $("sample");
const fileInput = $("file");
const statusEl = $("status");
const barEl = $("bar");
const barFill = barEl.firstElementChild;
const transcriptEl = $("transcript");
const metaEl = $("meta");
const refEl = $("ref");
const worker = new Worker("worker.js?v=2", { type: "module" });
let busy = false;
// ---------- worker plumbing ----------
const downloads = new Map(); // file -> { loaded, total }
worker.onmessage = (event) => {
const { type, payload } = event.data;
if (type === "progress") {
downloads.set(payload.file, payload);
const loaded = [...downloads.values()].reduce((s, d) => s + d.loaded, 0);
const total = [...downloads.values()].reduce((s, d) => s + d.total, 0);
if (total > 0) {
const pct = Math.round((loaded / total) * 100);
barEl.style.display = "block";
barFill.style.width = `${pct}%`;
statusEl.textContent = `در حال دانلود مدل … ${pct}%`;
}
} else if (type === "status" && payload === "ready") {
barEl.style.display = "none";
statusEl.textContent = "مدل آماده است — در حال پیاده‌سازی …";
} else if (type === "status") {
statusEl.textContent = payload;
} else if (type === "result") {
finish(payload.text, payload.elapsed);
} else if (type === "error") {
busy = false;
unlock();
barEl.style.display = "none";
statusEl.textContent = "خطا: " + payload;
}
};
function setStatus(text) {
statusEl.textContent = text;
}
function startWork(message) {
busy = true;
lock();
downloads.clear();
refEl.style.display = "none";
transcriptEl.textContent = "(در حال پردازش…)";
metaEl.textContent = "";
setStatus(message);
}
function finish(text, elapsedSeconds) {
setStatus("تمام شد — می‌توانید کلیپ دیگری امتحان کنید.");
transcriptEl.textContent = text || "(متنی تشخیص داده نشد — شاید صدا کوتاه یا نویزی بود.)";
const audioSeconds = window.__lastAudioSeconds || 0;
metaEl.textContent =
`زمان پردازش: ${elapsedSeconds.toFixed(1)} ثانیه` +
(audioSeconds ? ` برای ${audioSeconds.toFixed(1)} ثانیه صدا` : "") +
" — کاملاً روی دستگاه شما.";
busy = false;
unlock();
}
function lock() {
micBtn.disabled = true;
sampleBtn.disabled = true;
fileInput.disabled = true;
modelSel.disabled = true;
}
function unlock() {
micBtn.disabled = false;
sampleBtn.disabled = false;
fileInput.disabled = false;
modelSel.disabled = false;
}
// ---------- audio -> 16 kHz mono Float32 ----------
async function decodeTo16k(arrayBuffer) {
const ctx = new AudioContext({ sampleRate: 16000 });
try {
const buffer = await ctx.decodeAudioData(arrayBuffer);
// Mix down to mono if the clip has multiple channels.
let data = buffer.getChannelData(0);
if (buffer.numberOfChannels > 1) {
data = new Float32Array(buffer.length);
for (let c = 0; c < buffer.numberOfChannels; c++) {
const ch = buffer.getChannelData(c);
for (let i = 0; i < ch.length; i++) data[i] += ch[i] / buffer.numberOfChannels;
}
}
return { audio: data, seconds: buffer.duration };
} finally {
ctx.close();
}
}
async function transcribeArrayBuffer(arrayBuffer, sourceLabel) {
if (busy) return;
await transcribeRaw(arrayBuffer, sourceLabel);
}
// Core flow without the busy guard — for callers that manage `busy`
// themselves (the sample button fetches first, then starts the pipeline).
async function transcribeRaw(arrayBuffer, sourceLabel) {
startWork(`در حال آماده‌سازی صدا (${sourceLabel}) …`);
try {
const { audio, seconds } = await decodeTo16k(arrayBuffer);
if (seconds < 0.3) {
busy = false;
unlock();
transcriptEl.textContent = "(صدا خیلی کوتاه است.)";
return;
}
window.__lastAudioSeconds = seconds;
worker.postMessage({ kind: "transcribe", audio, modelId: modelSel.value });
} catch (err) {
console.error(err);
busy = false;
unlock();
setStatus("خطا در خواندن فایل صوتی: " + err.message);
}
}
// ---------- inputs ----------
sampleBtn.onclick = async () => {
if (busy) return;
busy = true;
lock();
downloads.clear();
refEl.style.display = "none";
transcriptEl.textContent = "(در حال پردازش…)";
metaEl.textContent = "";
setStatus("در حال دریافت کلیپ نمونه (از فیکسچر بنچمارک پروژه) …");
try {
const res = await fetch(SAMPLE_URL);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
refEl.innerHTML = `<b>متن مرجع (انسان):</b> ${SAMPLE_REFERENCE}`;
refEl.style.display = "block";
await transcribeRaw(await res.arrayBuffer(), "نمونه");
} catch (err) {
busy = false;
unlock();
setStatus("دریافت نمونه ناموفق بود: " + err.message);
}
};
let recorder = null;
let recordChunks = [];
micBtn.onclick = async () => {
if (busy) return;
if (recorder) {
recorder.stop();
return;
}
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
recordChunks = [];
recorder = new MediaRecorder(stream);
recorder.ondataavailable = (e) => recordChunks.push(e.data);
recorder.onstop = async () => {
stream.getTracks().forEach((t) => t.stop());
micBtn.textContent = "ضبط با میکروفن";
micBtn.classList.remove("recording");
const blob = new Blob(recordChunks, { type: recorder.mimeType });
recorder = null;
await transcribeArrayBuffer(await blob.arrayBuffer(), "ضبط میکروفن");
};
recorder.start();
micBtn.textContent = "پایان ضبط";
micBtn.classList.add("recording");
setStatus("در حال ضبط — دکمه را دوباره بزنید تا تمام شود.");
} catch (err) {
setStatus("دسترسی به میکروفن داده نشد: " + err.message);
}
};
fileInput.onchange = async () => {
const file = fileInput.files && fileInput.files[0];
if (!file) return;
await transcribeArrayBuffer(await file.arrayBuffer(), "فایل");
fileInput.value = "";
};
File renamed without changes.
File renamed without changes.
+127
View File
@@ -0,0 +1,127 @@
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>سخن · تبدیل گفتار فارسی به نوشتار</title>
<meta name="description" content="دموی زنده‌ی Sokhan — مدل Whisper کاملاً داخل مرورگر شما اجرا می‌شود؛ هیچ صدایی به هیچ سروری فرستاده نمی‌شود.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;800&display=swap" rel="stylesheet">
<style>
:root {
--ink: #1c2333; --muted: #5b6472; --line: #e3e7ee;
--bg: #f6f7fa; --card: #ffffff; --accent: #4f46e5; --accent-2: #7c3aed;
--ok: #0e9f6e; --err: #cf2440;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--ink);
font-family: 'Vazirmatn', 'Noto Sans Arabic', sans-serif;
line-height: 1.9;
}
.wrap { max-width: 860px; margin: 0 auto; padding: 24px 16px 64px; }
header h1 { font-size: 1.7rem; font-weight: 800; margin: 8px 0 2px; }
header h1 .brand { color: var(--accent); }
header p.sub { margin: 0 0 18px; color: var(--muted); font-size: 0.95rem; }
.card {
background: var(--card); border: 1px solid var(--line); border-radius: 14px;
padding: 18px 20px; margin-bottom: 16px; box-shadow: 0 1px 2px rgba(16,24,40,.04);
}
.row { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
label.field { font-size: 0.85rem; color: var(--muted); display: block; margin-bottom: 4px; }
select {
font-family: inherit; font-size: 0.95rem; padding: 8px 12px; border-radius: 10px;
border: 1px solid var(--line); background: #fff; color: var(--ink);
}
button {
font-family: inherit; font-size: 1rem; font-weight: 600; padding: 10px 18px;
border-radius: 10px; border: 1px solid var(--line); background: #fff;
color: var(--ink); cursor: pointer; transition: all .15s ease;
}
button:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
button:disabled { opacity: .45; cursor: not-allowed; }
button.primary {
background: linear-gradient(135deg, var(--accent), var(--accent-2));
border: none; color: #fff; font-size: 1.05rem;
}
button.primary:hover:not(:disabled) { color: #fff; filter: brightness(1.07); }
button.recording { background: var(--err); border: none; color: #fff; }
#status { font-size: 0.92rem; color: var(--muted); min-height: 1.6em; margin: 14px 0 6px; }
.bar { height: 8px; background: #eef0f5; border-radius: 99px; overflow: hidden; display: none; }
.bar > div { height: 100%; width: 0%; border-radius: 99px;
background: linear-gradient(90deg, var(--accent), var(--accent-2)); transition: width .2s ease; }
#transcript {
min-height: 120px; font-size: 1.08rem; padding: 12px 14px; border-radius: 10px;
border: 1px dashed var(--line); background: #fcfcfd; white-space: pre-wrap;
}
#meta { font-size: 0.85rem; color: var(--muted); margin-top: 8px; min-height: 1.4em; }
#ref { font-size: 0.85rem; color: var(--muted); margin-top: 6px; display: none; }
#ref b { color: var(--ok); font-weight: 600; }
.note { font-size: 0.88rem; color: var(--muted); }
.note a { color: var(--accent); text-decoration: none; font-weight: 600; }
.privacy { display: flex; gap: 8px; align-items: center; font-size: 0.9rem;
color: var(--ok); background: #ecfdf5; border: 1px solid #a7f3d0;
border-radius: 10px; padding: 8px 12px; margin-bottom: 16px; }
footer { margin-top: 26px; font-size: 0.85rem; color: var(--muted); text-align: center; }
footer a { color: var(--accent); text-decoration: none; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>سخن <span class="brand">·</span> تبدیل گفتار فارسی به نوشتار</h1>
<p class="sub">دموی زنده‌ی موتور Sokhan — مدل Whisper روی دستگاهِ خودِ شما اجرا می‌شود.</p>
</header>
<div class="privacy">🔒 حریم خصوصی کامل: صدا فقط در مرورگر شما پردازش می‌شود — به هیچ سروری ارسال نمی‌شود.</div>
<div class="card">
<div class="row">
<div>
<label class="field" for="model">کدام مدل؟ (اولین بار دانلود می‌شود)</label>
<select id="model">
<option value="Xenova/whisper-base" selected>پایه (base) — سریع، دانلود ~۷۵ مگابایت</option>
<option value="Xenova/whisper-small">کوچک (small) — دقیق‌تر اما کندتر</option>
</select>
</div>
<div style="flex:1"></div>
<button id="sample">نمونه‌ی آماده</button>
<button id="mic">ضبط با میکروفن</button>
</div>
<div class="row" style="margin-top:12px">
<input type="file" id="file" accept="audio/*,.wav,.mp3,.m4a,.ogg,.webm"
style="font-family:inherit;font-size:.9rem;color:var(--muted)">
</div>
<div id="status">برای شروع، «نمونه‌ی آماده» را بزنید یا صدا ضبط/انتخاب کنید.</div>
<div class="bar" id="bar"><div></div></div>
</div>
<div class="card">
<label class="field">متن پیاده‌شده</label>
<div id="transcript" dir="rtl">(اینجا نوشته می‌شود…)</div>
<div id="meta"></div>
<div id="ref"></div>
</div>
<p class="note">
صادقانه: این دمو چک‌پوینت‌های <b>پایه‌ی</b> Whisper را در مرورگر اجرا می‌کند
(Common Voice فارسی محاوره‌ای و پرنویز است؛ انتظار خطا داشته باشید).
چک‌پوینت ریزتنظیم‌شده‌ی Sokhan روی <a href="https://huggingface.co/Abol0pati/whisper-small-fa-sokhan">Hub</a>
موجود است و اپ Gradio آن برای اجرای روی سرور خودتان در
<a href="https://github.com/Abolfazlrwm/sokhan/tree/main/space/gradio">space/gradio/</a>
قرار دارد — HF از ۲۰۲۶ میزبانی Spaceهای Gradio را پشت اشتراک PRO گذاشته و
Spaceهای Static مثل همین صفحه رایگان مانده‌اند.
</p>
<footer>
کد کامل: <a href="https://github.com/Abolfazlrwm/sokhan">github.com/Abolfazlrwm/sokhan</a>
· اندازه‌گیری‌ها: <a href="https://github.com/Abolfazlrwm/sokhan/tree/main/benchmarks">benchmarks/</a>
· اجرا با <a href="https://huggingface.co/docs/transformers.js">transformers.js</a>
</footer>
</div>
<script type="module" src="demo.js?v=2"></script>
</body>
</html>
+63
View File
@@ -0,0 +1,63 @@
// Sokhan demo worker — runs Whisper entirely in the browser via
// transformers.js. The worker keeps model download + inference off the UI
// thread. Nothing about this app calls a server: the model and the audio
// both live on the visitor's machine.
import { pipeline, env } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
// The model repos live on the HF Hub; never look for local copies.
env.allowLocalModels = false;
let asr = null;
let currentModelId = null;
async function loadModel(modelId) {
if (asr && currentModelId === modelId) return;
currentModelId = null;
asr = null;
post("status", `در حال دانلود مدل ${modelId} …`);
asr = await pipeline("automatic-speech-recognition", modelId, {
// q8 keeps whisper-base at ~75 MB and runs on plain WASM SIMD —
// deterministic on every browser, no WebGPU requirement.
dtype: { encoder_model: "q8", decoder_model_merged: "q8" },
progress_callback: (p) => {
if (p.status === "progress" && p.total) {
post("progress", { file: p.file, loaded: p.loaded, total: p.total });
}
},
});
currentModelId = modelId;
post("status", "ready");
}
async function transcribe(audioF32, modelId) {
await loadModel(modelId);
post("status", "در حال پیاده‌سازی …");
const start = performance.now();
const out = await asr(audioF32, {
language: "fa",
task: "transcribe",
chunk_length_s: 30,
stride_length_s: 5,
});
const elapsed = (performance.now() - start) / 1000;
post("result", { text: (out.text || "").trim(), elapsed });
}
function post(type, payload) {
self.postMessage({ type, payload });
}
self.onmessage = async (event) => {
const { kind, modelId, audio } = event.data;
try {
if (kind === "load") {
await loadModel(modelId);
} else if (kind === "transcribe") {
await transcribe(audio, modelId);
}
} catch (err) {
console.error(err);
post("error", String(err && err.message ? err.message : err));
}
};
+46 -37
View File
@@ -274,49 +274,58 @@
"metadata": {},
"outputs": [],
"source": [
"#@title 10. Publish: browser demo Space + model card (2 min) — needs the token from cell 4\n",
"# Builds a public Gradio Space that serves your fine-tuned model in the\n",
"# browser (A/B against the untuned baseline) and writes a proper model\n",
"# card onto the model repo. Skips gracefully if you saved as zip.\n",
"#@title 10. Write the model card to your model repo (needs cell 4's token)\n",
"# The public demo Space is already live (free Static Space, Whisper in the\n",
"# browser): https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo\n",
"# Hosting a *Gradio* Space now requires HF PRO, so this cell only publishes\n",
"# the model card — run it right after cell 9 (SAVE_MODE=\"hf_hub\").\n",
"from pathlib import Path\n",
"\n",
"if not HF_TOKEN:\n",
" print(\"skip: no HF token — run cell 4 first\")\n",
"elif SAVE_MODE != \"hf_hub\":\n",
" print(\"skip: no hub model (cell 9 ran in zip mode)\")\n",
"else:\n",
" from huggingface_hub import login, create_repo, upload_file, upload_folder\n",
" from huggingface_hub import login, upload_file\n",
" login(token=HF_TOKEN)\n",
" card = Path(\"training/model_card.md\").read_text(encoding=\"utf-8\")\n",
" if repo_id != \"Abol0pati/whisper-small-fa-sokhan\":\n",
" card = card.replace(\"Abol0pati/whisper-small-fa-sokhan\", repo_id)\n",
" upload_file(path_or_fileobj=card.encode(\"utf-8\"), path_in_repo=\"README.md\",\n",
" repo_id=repo_id, repo_type=\"model\",\n",
" commit_message=\"Model card: measured numbers and caveats\")\n",
" print(\"model card ->\", f\"https://huggingface.co/{repo_id}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#@title 11. (Optional) Upload merged HF weights — unlocks the ONNX/browser path\n",
"# Only meaningful right after a training run: the merged folder lives at\n",
"# training/runs/whisper-small-fa-lora/merged in this VM. Once it is on the\n",
"# Hub, the repo's ROADMAP \"fine-tuned checkpoint in the browser\" step can\n",
"# export ONNX and point the free Static demo at it.\n",
"import os\n",
"from pathlib import Path\n",
"\n",
" if SAVE_MODE == \"hf_hub\":\n",
" model_repo_id = repo_id\n",
" else:\n",
" owner = input(\"HF username (e.g. Abol0pati): \").strip()\n",
" model_repo_id = f\"{owner}/whisper-small-fa-sokhan\"\n",
"\n",
" # a) model card -> README.md of the model repo (only if it exists)\n",
" if SAVE_MODE == \"hf_hub\":\n",
" card = Path(\"training/model_card.md\").read_text(encoding=\"utf-8\")\n",
" if model_repo_id != \"Abol0pati/whisper-small-fa-sokhan\":\n",
" card = card.replace(\"Abol0pati/whisper-small-fa-sokhan\", model_repo_id)\n",
" upload_file(path_or_fileobj=card.encode(\"utf-8\"), path_in_repo=\"README.md\",\n",
" repo_id=model_repo_id, repo_type=\"model\")\n",
" print(\"model card ->\", f\"https://huggingface.co/{model_repo_id}\")\n",
" else:\n",
" print(\"model card skipped: no hub model (cell 9 ran in zip mode)\")\n",
"\n",
" # b) public browser demo Space (sdk: gradio)\n",
" space_id = model_repo_id.split(\"/\")[0] + \"/sokhan-fa-demo\"\n",
" create_repo(space_id, repo_type=\"space\", space_sdk=\"gradio\",\n",
" private=False, exist_ok=True)\n",
" # point the demo app and its README at your checkpoint\n",
" if model_repo_id != \"Abol0pati/whisper-small-fa-sokhan\":\n",
" for fname in (\"space/app.py\", \"space/README.md\"):\n",
" text = Path(fname).read_text(encoding=\"utf-8\")\n",
" Path(fname).write_text(\n",
" text.replace(\"Abol0pati/whisper-small-fa-sokhan\", model_repo_id),\n",
" encoding=\"utf-8\")\n",
" upload_folder(repo_id=space_id, folder_path=\"space\", repo_type=\"space\")\n",
" print(\"demo Space ->\", f\"https://huggingface.co/spaces/{space_id}\")\n",
" print(\"first build takes ~5-10 min; then anyone can try your model in the browser\")\n"
"merged = Path(\"training/runs/whisper-small-fa-lora/merged\")\n",
"if not HF_TOKEN:\n",
" print(\"skip: no HF token — run cell 4 first\")\n",
"elif not merged.is_dir():\n",
" print(\"skip:\", merged, \"does not exist (run cell 6/7 first in this VM)\")\n",
"else:\n",
" from huggingface_hub import login, upload_folder\n",
" login(token=HF_TOKEN)\n",
" weights_id = input(\"repo id for the HF weights, e.g. \"\n",
" \"Abol0pati/whisper-small-fa-sokhan-weights: \").strip()\n",
" from huggingface_hub import create_repo\n",
" create_repo(weights_id, private=False, exist_ok=True)\n",
" upload_folder(repo_id=weights_id, folder_path=str(merged))\n",
" print(\"weights ->\", f\"https://huggingface.co/{weights_id}\")\n",
" print(\"next: ONNX export (optimum) -> swap the demo's model ids\")\n"
]
},
{
@@ -325,7 +334,7 @@
"source": [
"## بعدش چی؟ (Next steps)\n",
"\n",
"- **دموی زنده:** سلول ۱۰ یک Space عمومی با همین مدل می‌سازد؛ لینکش را در README پروژه و کارت مدل می‌گذاریم — کسی برای تست، نصب لازم ندارد.\n",
"- **دموی زنده:** https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo — Whisper داخل مرورگر اجرا می‌شود (Space رایگان static). سرو کردن همین مدل ریزتنظیم‌شده روی سرور خودت: اپ Gradio در `space/gradio/` ریپو.\n",
"- **سرو کردن:** فولدر `whisper-small-fa-ct2` را در سرور خودت بگذار و `WHISPER_MODEL_SIZE` را به مسیرش بده (deploy/docker-compose.yml).\n",
"- **بنچمارک واقعی:** کپی این فولدر را کنار `benchmarks/benchmark_wer.py` بگذار و اجرا کن:\n",
" `python benchmarks/benchmark_wer.py --models whisper-small-fa-ct2` — بعد جدول اندازه‌گیری‌شده را با یک PR کنار baseline در `benchmarks/` اضافه کن.\n",
+7 -2
View File
@@ -79,9 +79,14 @@ segments, info = model.transcribe("audio.wav", language="fa", beam_size=5)
print(" ".join(s.text.strip() for s in segments))
```
A live browser demo (this model vs. the untuned baseline, A/B) runs at
A free in-browser demo runs at
[hf.co/spaces/Abol0pati/sokhan-fa-demo](https://huggingface.co/spaces/Abol0pati/sokhan-fa-demo)
— app source in [`space/`](https://github.com/Abolfazlrwm/sokhan/tree/main/space).
— Whisper executes entirely client-side there (transformers.js, ONNX q8,
nothing uploaded), with the untuned base/small checkpoints selectable.
Serving **this fine-tuned checkpoint** needs a real engine: the Gradio app
in [`space/gradio/`](https://github.com/Abolfazlrwm/sokhan/tree/main/space/gradio)
runs it with the same faster-whisper config as production, self-hosted or
on a PRO Space (HF gates hosted Gradio Spaces behind PRO since 2026).
## Training & reproduction