diff --git a/CHANGELOG.md b/CHANGELOG.md index c768bab..8d7be1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 0a880be..2535138 100644 --- a/README.md +++ b/README.md @@ -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):  +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): + + + ## Why Most speech-to-text tooling treats Persian as an afterthought. Sokhan is diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 116eda9..91f3fcb 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -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 diff --git a/docs/assets/demo-space.png b/docs/assets/demo-space.png new file mode 100644 index 0000000..a4f23fe Binary files /dev/null and b/docs/assets/demo-space.png differ diff --git a/space/README.md b/space/README.md index 6a7ddbc..0a17ac9 100644 --- a/space/README.md +++ b/space/README.md @@ -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. diff --git a/space/demo.js b/space/demo.js new file mode 100644 index 0000000..22ad51c --- /dev/null +++ b/space/demo.js @@ -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 = `متن مرجع (انسان): ${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 = ""; +}; diff --git a/space/app.py b/space/gradio/app.py similarity index 100% rename from space/app.py rename to space/gradio/app.py diff --git a/space/requirements.txt b/space/gradio/requirements.txt similarity index 100% rename from space/requirements.txt rename to space/gradio/requirements.txt diff --git a/space/index.html b/space/index.html new file mode 100644 index 0000000..8ecc279 --- /dev/null +++ b/space/index.html @@ -0,0 +1,127 @@ + + +
+ + +دموی زندهی موتور Sokhan — مدل Whisper روی دستگاهِ خودِ شما اجرا میشود.
++ صادقانه: این دمو چکپوینتهای پایهی Whisper را در مرورگر اجرا میکند + (Common Voice فارسی محاورهای و پرنویز است؛ انتظار خطا داشته باشید). + چکپوینت ریزتنظیمشدهی Sokhan روی Hub + موجود است و اپ Gradio آن برای اجرای روی سرور خودتان در + space/gradio/ + قرار دارد — HF از ۲۰۲۶ میزبانی Spaceهای Gradio را پشت اشتراک PRO گذاشته و + Spaceهای Static مثل همین صفحه رایگان ماندهاند. +
+ + +