diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0eb9174..852fb3c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,7 +34,7 @@ jobs: run: | dirs="backend" if [ -d bot ]; then dirs="$dirs bot"; fi - for extra in training benchmarks; do + for extra in training benchmarks space; do if [ -d "$extra" ]; then dirs="$dirs $extra"; fi done ruff check $dirs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..d8be609 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,14 @@ +# Contributor hygiene: `pip install pre-commit && pre-commit install` +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.8.4 + hooks: + - id: ruff + args: [--fix] + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-yaml + - id: check-added-large-files diff --git a/CHANGELOG.md b/CHANGELOG.md index 11f9654..3f804f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,25 @@ All notable changes to Sokhan are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/) and the project versions with [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### 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` +- `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 +- `.pre-commit-config.yaml` for contributors (ruff + hygiene hooks) + ## [1.2.0] - 2026-11-18 ### Added diff --git a/README.md b/README.md index 84982fd..0a880be 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ **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. + Sokhan runs entirely on your own hardware: a FastAPI service with a faster-whisper engine, a Celery worker, a Next.js dashboard written Persian-first (RTL), and an optional Telegram bot. No cloud account, no @@ -205,6 +209,9 @@ docs/ architecture notes and decision records (ADRs) - Persian punctuation restoration post-pass - Webhooks/notifications when a job finishes +Full versioned roadmap with acceptance criteria (and the measurement-first +rule everything is held to): [docs/ROADMAP.md](docs/ROADMAP.md). + ## License MIT — see [LICENSE](LICENSE). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..116eda9 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,61 @@ +# Sokhan roadmap + +Versioned, measurable phases. The project rule applies to everything +below: **a claim ships only with a measurement** (WER from +`benchmarks/benchmark_wer.py` on the fixed fixture, or a test that +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) +- [ ] **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, + ~2 h on a free T4) is the single highest-value experiment left in + 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. +- [ ] A bigger eval fixture (target: 200 clips, stratified by age/gender + and accent bands) so WER deltas stop being noise-limited + +## v1.4 — engine quality + +- Streaming/chunked decode in the worker: today the whole file is decoded + to memory before the 30-second window split; multi-hour recordings need + RAM proportional to file size +- Persian punctuation restoration as a post-pass (rule-based first, LLM + behind `SUMMARY_ENABLED` as the optional upgrade) +- Initial-prompt lexicon: pass project/domain vocab to the engine so + names and technical terms survive +- Benchmark regression gate in CI: nightly run over the fixture, fail if + `small` WER degrades > 1 point (guards engine/dependency upgrades) + +## v1.5 — product surface + +- Webhooks / notification when a job finishes (plus the Telegram bot + notifying on completion of long files) +- Confidence-aware SRT: low-confidence segments flagged for human review +- Speaker identification on top of diarization (ADR 0003/0004 define the + interface; pyannote is the default neural engine today) +- Docker image publish to GHCR so self-hosting skips the build step + +## v2.0 — direction candidates (decide by measurement, not vibes) + +- Persian TTS — the mirror of STT, completing "speech" in the name +- Real-time streaming transcription (mic-in, text-out live) +- Own-voice adaptation: LoRA adapters per speaker on top of the + Persian checkpoint +- distil-large-v3 distillation for Persian: quality of `large` at a + CPU-servable footprint + +## Release hygiene (ongoing) + +- SemVer + Keep-a-Changelog; a GitHub Release per minor version +- Never bump a model version without re-running the benchmark; archived + sessions in `benchmarks/results/` are the paper trail +- CI stays green; ruff/mypy/pytest are blocking, not advisory diff --git a/space/README.md b/space/README.md new file mode 100644 index 0000000..6a7ddbc --- /dev/null +++ b/space/README.md @@ -0,0 +1,28 @@ +--- +title: Sokhan سخن +emoji: "\U0001F3A4" +colorFrom: indigo +colorTo: purple +sdk: gradio +app_file: app.py +pinned: false +license: mit +short_description: تبدیل گفتار فارسی به نوشتار — مدل ریزتنظیم‌شده Whisper +--- + +# Sokhan — Persian speech-to-text demo + +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). + +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. + +Self-hosting the full product (web dashboard, Telegram bot, API, archive): +see the repository README. diff --git a/space/app.py b/space/app.py new file mode 100644 index 0000000..d6eddd5 --- /dev/null +++ b/space/app.py @@ -0,0 +1,140 @@ +"""Sokhan live demo — Persian speech-to-text in the browser. + +Runs the exact engine Sokhan serves in production (faster-whisper on CPU, +int8) over the LoRA fine-tuned Whisper checkpoint published on the Hub. + +Designed to be deployed as a Hugging Face Space (sdk: gradio), but it is a +plain Gradio app: `python app.py` runs it locally too. The A/B radio lets +anyone transcribe the same clip through the fine-tuned model and the +untuned baseline, which is the honest way to hear what 500 fine-tune clips +change. + +Numbers first: the fine-tuned checkpoint measures WER 79.3% vs 80.5% for +the baseline on the 12-clip Common Voice (fa) fixture +(benchmarks/README.md). Persian Common Voice is colloquial and noisy, so +both models make plenty of mistakes — this demo exists so people can try +the engine without self-hosting anything. +""" + +from __future__ import annotations + +import os +import time +from pathlib import Path + +import gradio as gr +from faster_whisper import WhisperModel + +# The fine-tuned checkpoint to showcase; override for forked Spaces. +SOKHAN_MODEL_ID = os.environ.get("SOKHAN_MODEL_ID", "Abol0pati/whisper-small-fa-sokhan") +BASELINE_MODEL_ID = os.environ.get("BASELINE_MODEL_ID", "small") + +MODELS: dict[str, WhisperModel] = {} + +# Display label -> internal key. Plain strings keep this app portable +# across Gradio versions (no (value, label) tuple magic). +CHOICE_LABELS = { + "finetuned": "مدل ریزتنظیم‌شده (Sokhan)", + "baseline": "مدل پایه (whisper-small)", +} +MODEL_IDS = { + "finetuned": SOKHAN_MODEL_ID, + "baseline": BASELINE_MODEL_ID, +} +LABEL_TO_KEY = {label: key for key, label in CHOICE_LABELS.items()} + + +def get_model(key: str) -> WhisperModel: + """Lazily build one WhisperModel per choice; reused across requests.""" + if key not in MODELS: + MODELS[key] = WhisperModel(MODEL_IDS[key], device="cpu", compute_type="int8") + return MODELS[key] + + +def transcribe(audio_path: str | None, label: str) -> tuple[str, str]: + """Transcribe one clip; returns (transcript, stats line).""" + if not audio_path or not Path(audio_path).exists(): + return "", "یک فایل صوتی انتخاب یا ضبط کنید." + + audio_path = str(Path(audio_path)) + model = get_model(LABEL_TO_KEY.get(label, "finetuned")) + + start = time.perf_counter() + segments, info = model.transcribe(audio_path, language="fa", beam_size=5) + parts: list[str] = [] + for segment in segments: + parts.append(segment.text.strip()) + elapsed = time.perf_counter() - start + + transcript = " ".join(parts).strip() + if not transcript: + transcript = "(متنی تشخیص داده نشد — شاید صدا بیش‌ازحد کوتاه یا نویزی بود.)" + + audio_s = info.duration + rtf = elapsed / audio_s if audio_s else 0.0 + stats = ( + f"مدت صدا: {audio_s:.1f} ثانیه | زمان پردازش: {elapsed:.1f} ثانیه " + f"(≈ {rtf:.1f} برابرِ زمان واقعی، CPU int8)" + ) + return transcript, stats + + +TITLE = "سخن · تبدیل گفتار فارسی به نوشتار" +DESCRIPTION = """ +دموی زنده‌ی موتور **Sokhan** — همان موتور faster-whisper که در خودِ محصول +روی CPU سرو می‌شود، اینجا با چک‌پوینت ریزتنظیم‌شده با LoRA روی ۵۰۰ کلیپ +Common Voice فارسی (آموزش رایگان روی T4 کولب). + +مدل ریزتنظیم‌شده در اندازه‌گیری ثابت پروژه به **WER 79.3%** رسیده +(پایه: 80.5%) — اما داده‌ی آموزش کم است و Common Voice فارسی محاوره‌ای و +پرنویز است؛ هر دو مدل اشتباه می‌کنند. برای مقایسه، همان صدا را با هر دو +مدل اجرا کنید. +کد کامل: [github.com/Abolfazlrwm/sokhan](https://github.com/Abolfazlrwm/sokhan) +""" + +CSS = """ +.gradio-container {direction: rtl; text-align: right;} +.transcript textarea {font-size: 1.05rem; line-height: 1.9;} +""" + +# Gradio 6.0 moved the css parameter from Blocks() to launch(); support both +# so the Space builds on whatever SDK version HF ships. +GRADIO_MAJOR = int(gr.__version__.split(".")[0]) +BLOCKS_CSS = {"css": CSS} if GRADIO_MAJOR < 6 else {} +LAUNCH_KWARGS = {"css": CSS} if GRADIO_MAJOR >= 6 else {} + +with gr.Blocks(title=TITLE, **BLOCKS_CSS) as demo: + gr.Markdown(f"# {TITLE}") + gr.Markdown(DESCRIPTION) + + with gr.Row(): + audio_in = gr.Audio( + sources=["microphone", "upload"], + type="filepath", + label="صدا — ضبط با میکروفن یا انتخاب فایل", + ) + model_choice = gr.Radio( + choices=list(CHOICE_LABELS.values()), + value=CHOICE_LABELS["finetuned"], + label="کدام مدل؟", + ) + + transcribe_btn = gr.Button("پیاده‌سازی", variant="primary") + + transcript_out = gr.Textbox( + label="متن پیاده‌شده", + lines=6, + rtl=True, + elem_classes=["transcript"], + placeholder="بعد از پردازش اینجا نوشته می‌شود…", + ) + stats_out = gr.Markdown("(نخستین اجرا مدل را دانلود می‌کند — چند دقیقه صبر کنید.)") + + transcribe_btn.click( + fn=transcribe, + inputs=[audio_in, model_choice], + outputs=[transcript_out, stats_out], + ) + +if __name__ == "__main__": + demo.launch(**LAUNCH_KWARGS) diff --git a/space/requirements.txt b/space/requirements.txt new file mode 100644 index 0000000..222236a --- /dev/null +++ b/space/requirements.txt @@ -0,0 +1 @@ +faster-whisper==1.2.1 diff --git a/training/finetune_fa_colab.ipynb b/training/finetune_fa_colab.ipynb index 2660bb4..f317054 100644 --- a/training/finetune_fa_colab.ipynb +++ b/training/finetune_fa_colab.ipynb @@ -268,12 +268,64 @@ " print(\"uploaded to:\", f\"https://huggingface.co/{repo_id}\")" ] }, + { + "cell_type": "code", + "execution_count": null, + "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", + "from pathlib import Path\n", + "\n", + "if not HF_TOKEN:\n", + " print(\"skip: no HF token — run cell 4 first\")\n", + "else:\n", + " from huggingface_hub import login, create_repo, upload_file, upload_folder\n", + " login(token=HF_TOKEN)\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" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "## بعدش چی؟ (Next steps)\n", "\n", + "- **دموی زنده:** سلول ۱۰ یک Space عمومی با همین مدل می‌سازد؛ لینکش را در README پروژه و کارت مدل می‌گذاریم — کسی برای تست، نصب لازم ندارد.\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", @@ -282,4 +334,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/training/model_card.md b/training/model_card.md new file mode 100644 index 0000000..01b3700 --- /dev/null +++ b/training/model_card.md @@ -0,0 +1,100 @@ +--- +language: + - fa +license: mit +base_model: + - openai/whisper-small +tags: + - asr + - whisper + - persian + - lora + - peft + - faster-whisper + - ctranslate2 +datasets: + - mozilla-foundation/common_voice_17_0 +metrics: + - wer + - cer +model-index: + - name: whisper-small-fa-sokhan + results: + - task: + type: automatic-speech-recognition + name: Automatic Speech Recognition + dataset: + name: Common Voice fa — Sokhan 12-clip fixture (CC-0) + type: mozilla-foundation/common_voice_17_0 + metrics: + - type: wer + value: 0.793 + name: WER (fixture, CPU int8) + - type: cer + value: 0.249 + name: CER (fixture, CPU int8) +--- + +# whisper-small-fa-sokhan + +A Persian-adapted `whisper-small`: LoRA fine-tune (r=16, alpha=32, +dropout=0.05 on `q_proj`/`v_proj`, lr 1e-4, 3 epochs) on **500 Common +Voice (fa) clips (~45 minutes of speech)**, trained in ~7 minutes on a +free Colab T4, then merged and converted to CTranslate2 so +[faster-whisper](https://github.com/SYSTRAN/faster-whisper) can serve it +on CPU int8 — the same config the +[Sokhan](https://github.com/Abolfazlrwm/sokhan) product uses in production. + +## Measured results + +Every number below comes from a reproducible run +(`benchmarks/benchmark_wer.py`): 12 real Common Voice (fa) clips with +human-verified references, beam_size=5, the same Persian normalization +applied to reference and hypothesis. Session 2026-11-18, +faster-whisper 1.2.1 / CTranslate2 4.9.0, CPU int8. + +| model | WER | CER | +| --- | --- | --- | +| openai whisper-small (baseline) | 80.5% | 26.7% | +| **whisper-small-fa-sokhan** | **79.3%** | **24.9%** | + +In-training held-out eval (10 clips): WER 85.1% → 81.6%; training loss +3.63 → 1.75. + +**Honest caveats.** A 12-clip fixture puts the -1.2 WER margin near the +noise floor; the direction matches the in-training eval but the ceiling +is unknown until the same notebook runs over the full ~10-hour manifest +(`MAX_SAMPLES=0`, ~2 h on a free T4). Common Voice fa is colloquial and +noisy — these WER numbers are much higher than typical read-speech +benchmarks. Do not cite this model as production-ready Persian ASR yet. + +## Usage + +```python +from faster_whisper import WhisperModel + +model = WhisperModel("Abol0pati/whisper-small-fa-sokhan", + device="cpu", compute_type="int8") +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 +[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). + +## Training & reproduction + +- Pipeline and one-click Colab notebook: + [`training/`](https://github.com/Abolfazlrwm/sokhan/tree/main/training) + + [docs/free-gpu.md](https://github.com/Abolfazlrwm/sokhan/blob/main/docs/free-gpu.md) +- Data: public CC-0 Common Voice (fa) mirror, `train` split, 500 clips / + ~45 min speech +- Method: parameter-efficient LoRA (PEFT) on whisper-small, adapter only — + base weights untouched, merged after training, then converted with + `ct2-transformers-converter --quantization float16` (serving quantizes + to int8) + +Persian Common Voice files are no longer re-published as downloads by +Mozilla; the pipeline uses the public parquet mirror instead. Licensing +follows CC-0 for the data and MIT for the code.