Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a29dae7f56
|
||
|
|
d254527881
|
||
|
|
4821d812dc | ||
|
|
601fed0766 |
No files matched your search
+15
-4
@@ -18,8 +18,10 @@ DATA_DIR=./data
|
||||
|
||||
# --- Whisper ---
|
||||
# Model size: tiny / base / small / medium / large-v3
|
||||
# "small" is a good trade-off for Persian on CPU.
|
||||
WHISPER_MODEL_SIZE=small
|
||||
# Default "medium": measured 56.2% WER on the Persian fixture vs 75.0%
|
||||
# for small (~1.1x realtime on 2 CPU cores, ~800 MB download).
|
||||
# Set to "small" for the speed-first profile (~3x faster, less RAM).
|
||||
WHISPER_MODEL_SIZE=medium
|
||||
|
||||
# cpu or cuda
|
||||
WHISPER_DEVICE=cpu
|
||||
@@ -30,10 +32,19 @@ WHISPER_COMPUTE_TYPE=int8
|
||||
# Decoder beam width. 5 matches the benchmark and Gradio demo config.
|
||||
WHISPER_BEAM_SIZE=5
|
||||
|
||||
# Optional domain lexicon passed to the decoder as an initial prompt, so
|
||||
# project names and technical terms survive transcription (v1.4 roadmap).
|
||||
# Initial prompt for the decoder. The default (empty here = code default)
|
||||
# nudges the decoder towards standard written Persian orthography with
|
||||
# ZWNJ; measured -1.3 WER points on small, -4.8 on the fine-tuned model.
|
||||
# Replace with your own domain lexicon (project names, technical terms) to
|
||||
# make those survive transcription (v1.4 roadmap).
|
||||
WHISPER_INITIAL_PROMPT=
|
||||
|
||||
# Orthographic Persian polish (ZWNJ repair, split imperatives like
|
||||
# "بی پوش" -> "بپوش", Arabic look-alikes, digits) applied to every finished
|
||||
# transcript. Measured -3.6 WER points on the fixture; never rewords.
|
||||
# Set to "false" for the raw model text.
|
||||
FA_POLISH=true
|
||||
|
||||
# Rule-based Persian punctuation restoration applied to every finished
|
||||
# transcript (question marks, commas, sentence periods, spacing). Set to
|
||||
# "false" for the raw Whisper word stream.
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Run the fixture benchmark with the regression gate
|
||||
run: |
|
||||
python benchmarks/benchmark_wer.py \
|
||||
--models small \
|
||||
--models small medium \
|
||||
--baseline benchmarks/results/baseline.json \
|
||||
--max-regression 1.0 \
|
||||
--archive
|
||||
|
||||
@@ -7,14 +7,64 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
### Added
|
||||
|
||||
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
|
||||
fa fixture, every number reproducible:
|
||||
- New `sokhan.core.fa_polish` module: orthographic-only Persian ASR
|
||||
repair (ZWNJ prefix/suffix fusion, split-imperative repair like
|
||||
"بی پوش" → "بپوش", Arabic look-alike code points, Latin→Persian
|
||||
digits, punctuation spacing). Wired into the pipeline behind
|
||||
`FA_POLISH=true` and ported verbatim to the browser demo
|
||||
(16-case parity test with the Python implementation). Measured
|
||||
−3.6 WER points; never rewords colloquial speech.
|
||||
- New default `whisper_initial_prompt`: a ZWNJ-correct Persian
|
||||
orthography prompt. whisper copies prompt script style — measured
|
||||
−1.3 WER points on `small`, −4.8 on the fine-tuned checkpoint.
|
||||
- **Default engine is now `medium`**: 56.2% WER vs 75.0% for `small`
|
||||
under the v2 harness — a −24.3-point jump at ~1.1x realtime on 2 CPU
|
||||
cores (int8, ~800 MB download). `WHISPER_MODEL_SIZE=small` remains
|
||||
the documented speed-first profile.
|
||||
- Browser demo: default model switched base → small (fixture 90.2% →
|
||||
75.0% under v2), output now passes through the same polish pass as
|
||||
the server, and the honesty note was updated.
|
||||
- `benchmarks/tune_decode.py`: the decode sweep harness the decisions
|
||||
above came from (prompt variants × beam × VAD ×
|
||||
condition_on_previous_text).
|
||||
- `training/export_web_onnx.py`: merge-LoRA → ONNX → int8 → HF Hub
|
||||
pipeline that produces a transformers.js-compatible repo of any
|
||||
Sokhan fine-tune, so the browser demo can run the project's own
|
||||
engine once the export runs on Colab.
|
||||
- `baseline.json` regenerated under the v2 harness (small 0.75 /
|
||||
fine-tuned 0.75 / medium 0.5625); the weekly benchmark workflow now
|
||||
guards `small` **and** `medium`; regression-gate test updated to the
|
||||
committed baseline.
|
||||
- Brand refresh: a hero banner in both READMEs (`docs/assets/banner.png`),
|
||||
a redesigned 1280x640 social preview (`docs/assets/social-preview.png` —
|
||||
upload it once in Settings → General → Social preview) and a 512px app
|
||||
icon (`docs/assets/icon-512.png`) usable as the HF Space avatar. The
|
||||
landing site og:image was regenerated in the same style.
|
||||
- Browser demo speed & UX overhaul (space/): WebGPU fast path (fp32
|
||||
encoder + q4 decoder) with automatic WASM/q8 fallback, per-window
|
||||
transcription progress with an ETA and elapsed timer, a real cancel
|
||||
button (terminates the worker; the model stays in browser cache), a
|
||||
timestamped line-by-line transcript toggle, a copy button and stage
|
||||
pills. The windowing (30 s window / 5 s overlap) now lives in the
|
||||
worker with timestamp-midpoint trimming, enabling the progress stream
|
||||
and duration caps: 30 min on WebGPU, 10 min on WASM, 60 MB per file —
|
||||
no input can wedge the demo at an eternal "processing" state anymore.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Demo hang fix**: audio was decoded inside an `AudioContext` forced to
|
||||
16 kHz; Chromium can hang forever on opus/webm (Telegram voice,
|
||||
MediaRecorder) in that configuration — the demo sat at "در حال
|
||||
آمادهسازی صدا" indefinitely. Decoding now happens at the context's
|
||||
natural rate and is resampled offline to 16 kHz, with a 45 s decode
|
||||
watchdog and clear format-error messages (e.g. OGG on Safari). The
|
||||
worker's origin guard also now accepts the EMPTY `event.origin`
|
||||
Chromium 158+ posts for same-origin dedicated-worker messages — the
|
||||
strict comparison silently rejected every command and left the demo
|
||||
at "در حال پردازش" forever.
|
||||
|
||||
- **License: MIT → PolyForm Noncommercial 1.0.0 (source-available).** The
|
||||
code stays readable and reviewable by anyone, and noncommercial use
|
||||
(personal projects, study, research, nonprofits) remains free; any
|
||||
@@ -24,6 +74,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
pyproject.toml files, web/package.json, the landing site copy, the demo
|
||||
Space metadata and the fine-tuned model card.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The punctuation post-pass no longer splits numbers written with a
|
||||
thousands separator: `1,000` stayed `1، 000` (Persian comma plus a
|
||||
space). A comma between digits followed by exactly three digits is now
|
||||
kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`.
|
||||
The edge cases from #30 (slash dates, Latin digits in Persian sentences,
|
||||
abbreviations, ellipses, repeated marks) are pinned by tests.
|
||||
|
||||
## [1.4.1] - 2026-11-26
|
||||
|
||||
### Security
|
||||
|
||||
+11
-8
@@ -288,14 +288,17 @@ site/ لندینگپیج GitHub Pages (دیپلوی خودکار)
|
||||
## وضعیت پروژه و محدودیتهای صادقانه
|
||||
|
||||
- دقت: اندازهگیریشده روی نمونهٔ ثابت عمومی — ۱۲ کلیپ واقعی Common Voice
|
||||
(فارسی)، ۶۱ ثانیه صدا، مرجعِ تأییدشدهٔ انسانی. با موتور پیشفرض `small`:
|
||||
**WER 80.5% / CER 26.7%** (`tiny` برابر 92.7%، `base` برابر 90.2%). اولین
|
||||
فاینتیون GPU — LoRA روی `whisper-small`، ۵۰۰ کلیپ، T4 رایگان Colab —
|
||||
اندازهگیریشده **WER 79.3% / CER 24.9%**
|
||||
([Abol0pati/whisper-small-fa-sokhan](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan)):
|
||||
یک بهبود کوچک اما واقعی که با بزرگتر شدن داده باید بزرگتر شود. این
|
||||
عددها بهخاطر عامیانه و پرنویز بودن Common Voice فارسی بالاست؛ گفتار
|
||||
بازخوانی خیلی سادهتر است. روش کامل و خروجیِ هر کلیپ:
|
||||
(فارسی)، ۶۱ ثانیه صدا، مرجعِ تأییدشدهٔ انسانی. پشتهٔ دقت v2 (پرامپت ارتوگرافی
|
||||
فارسی + پستپروسس `fa_polish`، هر دو در [benchmarks/](benchmarks/README.md)
|
||||
اندازهگیری شده) فیکسچر را از **WER 80.5% به 75.0% روی `small`** میرساند و
|
||||
**موتور پیشفرض حالا `medium` است: WER 56.2% / CER 18.5%** با سرعت ~۱٫۱×
|
||||
بلادرنگ روی ۲ هستهٔ CPU (int8، دانلود ~۸۰۰ مگابایت؛ برای حالت سرعتمحور
|
||||
`WHISPER_MODEL_SIZE=small` بگذارید). اولین فاینتیون GPU — LoRA روی
|
||||
`whisper-small`، ۵۰۰ کلیپ، T4 رایگان Colab — با همان هارنس v2 عدد
|
||||
**WER 75.0% / CER 31.0%** میگیرد
|
||||
([Abol0pati/whisper-small-fa-sokhan](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan)).
|
||||
این عددها همچنان بهخاطر عامیانه و پرنویز بودن Common Voice فارسی بالاست؛
|
||||
گفتار بازخوانی خیلی سادهتر است. روش کامل و خروجیِ هر کلیپ:
|
||||
[benchmarks/README.md](benchmarks/README.md).
|
||||
- برچسب گوینده به موتور دیاوریزیشنی که انتخاب میکنید وابسته است. `energy`
|
||||
یک هیوریستیک است: برچسبهایش شباهت صوتی را توصیف میکنند نه هویتِ تأییدشده
|
||||
|
||||
@@ -287,14 +287,18 @@ explicit instead of implied:
|
||||
## Project status and honest limits
|
||||
|
||||
- Accuracy: measured on a fixed public sample — 12 real Common Voice (fa)
|
||||
clips, 61 s of audio, human-verified references. With the default `small`
|
||||
engine: **WER 80.5% / CER 26.7%** (`tiny` 92.7%, `base` 90.2%). The first
|
||||
GPU fine-tune — LoRA on `whisper-small`, 500 clips, free Colab T4 —
|
||||
measures **WER 79.3% / CER 24.9%**
|
||||
([Abol0pati/whisper-small-fa-sokhan](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan)):
|
||||
a small, real gain that data scaling should grow. These numbers are high
|
||||
because Common Voice fa is colloquial and noisy; read speech is far
|
||||
easier. Full methodology and per-clip output:
|
||||
clips, 61 s of audio, human-verified references. The v2 accuracy stack
|
||||
(Persian orthography initial prompt + `fa_polish` post-processing, both
|
||||
measured in [benchmarks/](benchmarks/README.md)) lifts the fixture from
|
||||
**WER 80.5% → 75.0% on `small`**, and the new **default engine is
|
||||
`medium`: WER 56.2% / CER 18.5%** at ~1.1x realtime on 2 CPU cores
|
||||
(int8, ~800 MB download; set `WHISPER_MODEL_SIZE=small` for the
|
||||
speed-first profile). The first GPU fine-tune — LoRA on `whisper-small`,
|
||||
500 clips, free Colab T4 — measures **WER 75.0% / CER 31.0%** under the
|
||||
same v2 harness
|
||||
([Abol0pati/whisper-small-fa-sokhan](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan)).
|
||||
These numbers are still high because Common Voice fa is colloquial and
|
||||
noisy; read speech is far easier. Full methodology and per-clip output:
|
||||
[benchmarks/README.md](benchmarks/README.md).
|
||||
- Speaker labels depend on the diarization engine you pick. `energy` is a
|
||||
heuristic: its labels describe acoustic similarity, not verified identity,
|
||||
|
||||
@@ -20,13 +20,28 @@ class Settings(BaseSettings):
|
||||
data_dir: str = "./data"
|
||||
|
||||
# Whisper
|
||||
whisper_model_size: str = "small"
|
||||
# Accuracy-first default: on CPU int8, `medium` measured 59.8% WER on the
|
||||
# Persian fixture vs 78.0% for `small` (~1.1x realtime on 2 cores, ~800 MB
|
||||
# download). Set WHISPER_MODEL_SIZE=small for the speed-first profile.
|
||||
whisper_model_size: str = "medium"
|
||||
whisper_device: str = "cpu"
|
||||
whisper_compute_type: str = "int8"
|
||||
# Decoding knobs: beam width, and a domain lexicon whispered to the
|
||||
# decoder up front so names and technical terms survive transcription.
|
||||
# The default prompt also nudges the decoder towards standard written
|
||||
# orthography (ZWNJ-correct Persian): measured -1.3 WER points on small,
|
||||
# -4.8 on the fine-tuned checkpoint (benchmarks/tune_decode.py).
|
||||
whisper_beam_size: int = 5
|
||||
whisper_initial_prompt: str = ""
|
||||
whisper_initial_prompt: str = (
|
||||
"این صدا به فارسی است. متن را با املای استاندارد و نیمفاصلهٔ درست بنویس: "
|
||||
"میشود، میگویم، کتابها، بزرگترین."
|
||||
)
|
||||
|
||||
# Orthographic Persian polish (ZWNJ repair, Arabic look-alikes, split
|
||||
# imperatives, digits) applied to every transcript before storage.
|
||||
# Measured -3.6 WER points on the fixture; never rewords colloquial
|
||||
# speech. Disable for raw model output.
|
||||
fa_polish: bool = True
|
||||
|
||||
# Transcript post-processing: rule-based Persian punctuation restoration
|
||||
# (v1.4) and the confidence threshold under which a segment is flagged
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Orthographic polish for Persian ASR output (v2 quality pass).
|
||||
|
||||
Whisper writes Persian reasonably but its orthography is sloppy: prefixes
|
||||
that belong behind a ZWNJ arrive as separate tokens ("می کنی"), the imperative
|
||||
prefix "ب" is mis-split into the real word "بی" ("بی پوش" for "بپوش"),
|
||||
Arabic look-alike code points leak through, and Latin digits appear in
|
||||
Persian sentences.
|
||||
|
||||
`polish_transcript` repairs exactly these surface forms — it never rewords
|
||||
(colloquial speech stays colloquial), so it is safe to apply to BOTH the
|
||||
reference and the hypothesis in WER evaluation (benchmarks v2) and to the
|
||||
product transcript in the pipeline. Every rule is deterministic and
|
||||
unit-tested (`tests/test_fa_polish.py`).
|
||||
|
||||
Not a fix for acoustic errors: when the model mishears a word no amount of
|
||||
text surgery recovers it — that is what bigger checkpoints are for (the
|
||||
measured stack: small 78.0% -> medium 59.8% WER, see benchmarks/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
_ZWNJ = "\u200c"
|
||||
|
||||
# ---------------------------------------------------------------- characters
|
||||
|
||||
# Arabic-block look-alikes -> Persian. Deliberately does NOT touch alef
|
||||
# variants (آ أ إ) — polish is for display, unlike the search normalizer.
|
||||
_ARABIC_CHARS = {
|
||||
"\u064a": "\u06cc", # yeh -> farsi yeh
|
||||
"\u0649": "\u06cc", # alef maksura -> farsi yeh
|
||||
"\u0643": "\u06a9", # kaf -> keheh
|
||||
"\u0629": "\u0647", # teh marbuta -> heh
|
||||
"\u0640": "", # tatweel -> drop
|
||||
# Arabic-Indic digits -> Persian digits
|
||||
"\u0660": "\u06f0", "\u0661": "\u06f1", "\u0662": "\u06f2", "\u0663": "\u06f3",
|
||||
"\u0664": "\u06f4", "\u0665": "\u06f5", "\u0666": "\u06f6", "\u0667": "\u06f7",
|
||||
"\u0668": "\u06f8", "\u0669": "\u06f9",
|
||||
}
|
||||
|
||||
# Latin digits -> Persian digits (Persian-first product).
|
||||
_LATIN_DIGITS = {d: chr(0x06F0 + i) for i, d in enumerate("0123456789")}
|
||||
|
||||
# ------------------------------------------------------------------- lexicon
|
||||
|
||||
# Very common verbs Whisper writes without the ZWNJ: "میکنم" -> "میکنم".
|
||||
_ZWNJ_WORDS = {
|
||||
"میکنم", "میکنی", "میکند", "میکنیم", "میکنید", "میکنند",
|
||||
"میشوم", "میشوی", "میشود", "میشویم", "میشوید", "میشوند",
|
||||
"میگویم", "میگویی", "میگوید", "میگوییم", "میگویید", "میگویند",
|
||||
"میگم", "میگی", "میگه", "میگن",
|
||||
"میخواهم", "میخواهی", "میخواهد", "میخواهیم", "میخواهید", "میخواهند",
|
||||
"میخوام", "میخوای", "میخواد", "میخوان",
|
||||
"میدانم", "میدانی", "میداند", "میدانیم", "میدانید", "میدانند",
|
||||
"میدم", "میدی", "میده", "میدن",
|
||||
"میبرم", "میبری", "میبرد", "میبریم", "میبرید", "میبرند",
|
||||
"میرم", "میری", "میره", "میرن",
|
||||
"میروم", "میروی", "میرود", "میرویم", "میروید", "میروند",
|
||||
"میآیم", "میآیی", "میآید", "میآییم", "میآیید", "میآیند",
|
||||
"میشنوم", "میشنوی", "میشنود", "میشنویم", "میشنوید", "میشنوند",
|
||||
"میبینم", "میبینی", "میبیند", "میبینیم", "میبینید", "میبینند",
|
||||
"میشه",
|
||||
"نمیکنم", "نمیکنی", "نمیکند", "نمیکنیم", "نمیکنید", "نمیکنند",
|
||||
"نمیشود", "نمیشه",
|
||||
"نمیگویم", "نمیگم", "نمیگی", "نمیگه", "نمیگن",
|
||||
"نمیخواهم", "نمیخواهد", "نمیخوام", "نمیخواد",
|
||||
"نمیدانم", "نمیدانی", "نمیداند",
|
||||
"نمیدونم", "نمیدونی", "نمیدونه", "نمیدونن",
|
||||
"نمیدم", "نمیدی", "نمیده", "نمیدن",
|
||||
"نمیرم", "نمیری", "نمیره", "نمیرن", "نمیرود",
|
||||
"نمیآید", "نمیاد",
|
||||
"نمیبینم", "نمیبینی", "نمیبیند",
|
||||
}
|
||||
|
||||
# The imperative "ب" is frequently mis-heard as the real word "بی" and
|
||||
# emitted as its own token: "بپوش ببین" -> "بی پوش بی بین". Only
|
||||
# unambiguous imperatives are repaired, and only right after "بی"/"به".
|
||||
_SPLIT_IMPERATIVES = {
|
||||
"پوش": "بپوش",
|
||||
"بین": "ببین",
|
||||
"بینم": "ببینم",
|
||||
"بینی": "ببینی",
|
||||
"بینید": "ببینید",
|
||||
"بینند": "ببینند",
|
||||
"خواب": "بخواب",
|
||||
"خور": "بخور",
|
||||
"شین": "بشین",
|
||||
"نشین": "بنشین",
|
||||
"گیر": "بگیر",
|
||||
"گو": "بگو",
|
||||
"گوی": "بگو",
|
||||
"بخش": "ببخش",
|
||||
}
|
||||
|
||||
# Separated ZWNJ prefixes: "می کنم" -> "میکنم" (fused with the next token).
|
||||
_FUSED_PREFIXES = {
|
||||
"می کنم": "میکنم", "می کنی": "میکنی", "می کند": "میکند",
|
||||
"می کنیم": "میکنیم", "می کنید": "میکنید", "می کنند": "میکنند",
|
||||
"می شود": "میشود", "می شن": "میشن", "می شه": "میشه",
|
||||
"می گویم": "میگویم", "می گویی": "میگویی", "می گوید": "میگوید",
|
||||
"می گوییم": "میگوییم", "می گویید": "میگویید", "می گویند": "میگویند",
|
||||
"می گم": "میگم", "می گی": "میگی", "می گه": "میگه", "می گن": "میگن",
|
||||
"می خواهم": "میخواهم", "می خواهی": "میخواهی", "می خواهد": "میخواهد",
|
||||
"می خواهیم": "میخواهیم", "می خواهید": "میخواهید", "می خواهند": "میخواهند",
|
||||
"می خوام": "میخوام", "می خوای": "میخوای", "می خواد": "میخواد",
|
||||
"می دانم": "میدانم", "می دانی": "میدانی", "می داند": "میداند",
|
||||
"می دونم": "میدونم", "می دونی": "میدونی", "می دونه": "میدونه",
|
||||
"می دم": "میدم", "می دی": "میدی", "می ده": "میده", "می دن": "میدن",
|
||||
"می برم": "میبرم", "می برد": "میبرد",
|
||||
"می رم": "میرم", "می ری": "میری", "می ره": "میره", "می رن": "میرن",
|
||||
"می روم": "میروم", "می رود": "میرود",
|
||||
"می آیم": "میآیم", "می آید": "میآید", "می این": "میاین",
|
||||
"می شنوم": "میشنوم", "می شنوی": "میشنوی", "می شنود": "میشنود",
|
||||
"می بینم": "میبینم", "می بینی": "میبینی", "می بیند": "میبیند",
|
||||
"نمی کنم": "نمیکنم", "نمی کنی": "نمیکنی", "نمی کند": "نمیکند",
|
||||
"نمی شود": "نمیشود", "نمی شه": "نمیشه",
|
||||
"نمی گم": "نمیگم", "نمی گی": "نمیگی", "نمی گه": "نمیگه",
|
||||
"نمی خوام": "نمیخوام", "نمی خواد": "نمیخواد",
|
||||
"نمی دانم": "نمیدانم", "نمی داند": "نمیداند",
|
||||
"نمی دونم": "نمیدونم",
|
||||
"نمی رم": "نمیرم", "نمی ره": "نمیره",
|
||||
"نمی آید": "نمیآید", "نمی این": "نمیاین",
|
||||
"نمی بینم": "نمیبینم", "نمی بیند": "نمیبیند",
|
||||
}
|
||||
|
||||
_PREFIX_TOKENS = ("می", "نمی")
|
||||
|
||||
# Separated ZWNJ suffixes: "پروانه های" -> "پروانههای" (fused with previous).
|
||||
_SUFFIX_TOKENS = ("ها", "های", "هایی", "تر", "ترین")
|
||||
|
||||
# Punctuation marks that swallow the space BEFORE them (closing marks only —
|
||||
# opening « and ( keep their leading space).
|
||||
_CLOSING_PUNCT = "،؛:.!?؟…»)"
|
||||
|
||||
# ----------------------------------------------------------------- pipeline
|
||||
|
||||
|
||||
def _fix_chars(text: str) -> str:
|
||||
out: list[str] = []
|
||||
for ch in text:
|
||||
if ch in _ARABIC_CHARS:
|
||||
out.append(_ARABIC_CHARS[ch])
|
||||
elif ch in _LATIN_DIGITS:
|
||||
out.append(_LATIN_DIGITS[ch])
|
||||
else:
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _split_edges(token: str) -> tuple[str, str, str]:
|
||||
"""Split a token into (leading punct, core, trailing punct)."""
|
||||
core = token.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if not core:
|
||||
return token, "", ""
|
||||
start = token.index(core)
|
||||
return token[:start], core, token[start + len(core):]
|
||||
|
||||
|
||||
def _zwnj_in_word(word: str) -> str:
|
||||
"""Insert the ZWNJ after a leading می/نمی prefix inside one token."""
|
||||
if word.startswith("نمی") and len(word) > 3:
|
||||
return "نمی" + _ZWNJ + word[3:]
|
||||
if word.startswith("می") and len(word) > 2:
|
||||
return "می" + _ZWNJ + word[2:]
|
||||
return word
|
||||
|
||||
|
||||
def _fix_tokens(text: str) -> str:
|
||||
tokens = text.split()
|
||||
fixed: list[str] = []
|
||||
for token in tokens:
|
||||
leading, core, trailing = _split_edges(token)
|
||||
if not core:
|
||||
fixed.append(token)
|
||||
continue
|
||||
if core in _ZWNJ_WORDS:
|
||||
core = _zwnj_in_word(core)
|
||||
fixed.append(leading + core + trailing)
|
||||
# Split-imperative repair needs the previous token, so run after folding.
|
||||
fused = _fuse(fixed)
|
||||
repaired: list[str] = []
|
||||
for token in fused.split():
|
||||
_leading, core, _trailing = _split_edges(token)
|
||||
if (
|
||||
core in _SPLIT_IMPERATIVES
|
||||
and repaired
|
||||
and repaired[-1].strip("،؛:.!?؟…«»()\"'-–—,") in ("بی", "به")
|
||||
):
|
||||
repaired[-1] = _SPLIT_IMPERATIVES[core]
|
||||
continue
|
||||
repaired.append(token)
|
||||
return " ".join(repaired)
|
||||
|
||||
|
||||
def _fuse(tokens: list[str]) -> str:
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
while i < len(tokens):
|
||||
tok = tokens[i]
|
||||
bare = tok.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if bare in _PREFIX_TOKENS and i + 1 < len(tokens):
|
||||
pair = f"{tok} {tokens[i + 1]}"
|
||||
fused = _FUSED_PREFIXES.get(pair)
|
||||
if fused is None and bare == tok: # no punctuation on the prefix
|
||||
fused = tok + _ZWNJ + tokens[i + 1]
|
||||
if fused is not None:
|
||||
out.append(fused)
|
||||
i += 2
|
||||
continue
|
||||
if bare in _SUFFIX_TOKENS and out:
|
||||
prev = out[-1]
|
||||
prev_core = prev.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if prev_core and prev_core[-1].isalpha():
|
||||
if bare == tok: # no punctuation on the suffix itself
|
||||
out[-1] = prev + _ZWNJ + bare
|
||||
else:
|
||||
out[-1] = prev + _ZWNJ + bare
|
||||
i += 1
|
||||
continue
|
||||
out.append(tok)
|
||||
i += 1
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def _fix_spacing(text: str) -> str:
|
||||
"""No space before a closing mark, one space after (digit-safe)."""
|
||||
text = text.replace(_ZWNJ + " ", _ZWNJ).replace(" " + _ZWNJ, _ZWNJ)
|
||||
out: list[str] = []
|
||||
for i, ch in enumerate(text):
|
||||
if ch in _CLOSING_PUNCT and out and out[-1] == " ":
|
||||
out.pop()
|
||||
out.append(ch)
|
||||
nxt = text[i + 1] if i + 1 < len(text) else ""
|
||||
if ch in _CLOSING_PUNCT and nxt and nxt not in _CLOSING_PUNCT and nxt != " ":
|
||||
# 3.5 / ۱۲٫۵ keep the dot glued to both digits
|
||||
if not (ch in ".،" and out[-2:-1] and out[-2].isdigit() and nxt.isdigit()):
|
||||
out.append(" ")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def polish_transcript(text: str) -> str:
|
||||
"""Repair Persian ASR orthography without rewording. Deterministic."""
|
||||
if not text or not text.strip():
|
||||
return text
|
||||
polished = _fix_chars(text)
|
||||
polished = _fix_tokens(polished)
|
||||
polished = _fix_spacing(polished)
|
||||
return polished.strip()
|
||||
@@ -5,7 +5,8 @@ puts the transcript back into publishable shape with three conservative,
|
||||
deterministic rule families — no model call, no LLM dependency:
|
||||
|
||||
1. Script fix: the Latin comma, question mark and semicolon become their
|
||||
Persian counterparts (، ؟ ؛).
|
||||
Persian counterparts (، ؟ ؛). A comma that groups digits ("1,000",
|
||||
"12,500,000") is a thousands separator, not punctuation, and is kept.
|
||||
2. Spacing: no space *before* punctuation, exactly one space *after* clause
|
||||
and sentence punctuation. `.` and `:` are deliberately left alone so
|
||||
decimals ("3.5") and clock times ("12:30") survive.
|
||||
@@ -26,6 +27,12 @@ import re
|
||||
# Latin forms that should not survive in a Persian transcript.
|
||||
_LATIN_TO_PERSIAN = str.maketrans({",": "،", "?": "؟", ";": "؛"})
|
||||
|
||||
# A comma between a digit and exactly three more digits groups a number.
|
||||
# \d matches Persian digits too, so "۱,۲۰۰" is covered.
|
||||
_THOUSANDS_COMMA = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")
|
||||
# Stands in for a thousands comma while the Latin marks are translated.
|
||||
_KEPT_COMMA = "\x00"
|
||||
|
||||
_CLAUSE = "،؛"
|
||||
_SENTENCE_END = "؟!…."
|
||||
_PUNCT_CHARS = _CLAUSE + _SENTENCE_END + ":."
|
||||
@@ -73,7 +80,8 @@ def _has_terminal(text: str) -> bool:
|
||||
|
||||
def restore_punctuation(text: str) -> str:
|
||||
"""Return `text` with Persian punctuation restored; safe to re-apply."""
|
||||
cleaned = text.translate(_LATIN_TO_PERSIAN).strip()
|
||||
cleaned = _THOUSANDS_COMMA.sub(_KEPT_COMMA, text)
|
||||
cleaned = cleaned.translate(_LATIN_TO_PERSIAN).replace(_KEPT_COMMA, ",").strip()
|
||||
cleaned = _SPACE_BEFORE.sub(r"\1", cleaned)
|
||||
cleaned = _SPACE_AFTER.sub(r"\1 ", cleaned)
|
||||
cleaned = _WS_RUNS.sub(" ", cleaned).strip()
|
||||
|
||||
@@ -35,6 +35,7 @@ from sokhan.core.audio import (
|
||||
probe_duration_seconds,
|
||||
)
|
||||
from sokhan.core.chunking import DEFAULT_OVERLAP_SECONDS, Chunk, chunk_samples, iter_chunks
|
||||
from sokhan.core.fa_polish import polish_transcript
|
||||
from sokhan.core.merge import merge_chunks
|
||||
from sokhan.core.persian import normalize_for_search
|
||||
from sokhan.core.punctuation import restore_punctuation
|
||||
@@ -159,6 +160,11 @@ def process_job(
|
||||
replace(segment, text=restore_punctuation(segment.text))
|
||||
for segment in merged
|
||||
]
|
||||
if settings.fa_polish:
|
||||
merged = [
|
||||
replace(segment, text=polish_transcript(segment.text))
|
||||
for segment in merged
|
||||
]
|
||||
job.text = formats.to_txt(merged)
|
||||
job.text_normalized = normalize_for_search(job.text)
|
||||
session.execute(delete(Segment).where(Segment.job_id == job_id))
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""fa_polish: orthographic Persian ASR repair — deterministic and safe.
|
||||
|
||||
The polisher may only repair surface orthography. It must never change
|
||||
which words a sentence contains (beyond fusing tokens that belong behind
|
||||
one ZWNJ), because the same function runs on both sides of the WER
|
||||
benchmark and inside the product pipeline.
|
||||
"""
|
||||
|
||||
from sokhan.core.fa_polish import polish_transcript
|
||||
|
||||
|
||||
def test_zwnj_prefix_fusion():
|
||||
assert polish_transcript("تو من رو مامنو می کنی؟") == "تو من رو مامنو میکنی؟"
|
||||
|
||||
|
||||
def test_zwnj_inside_single_token():
|
||||
assert polish_transcript("نمیدونم چی میخواد") == "نمیدونم چی میخواد"
|
||||
|
||||
|
||||
def test_suffix_fusion():
|
||||
assert (
|
||||
polish_transcript("پروانه های کوپی لفت را به وجود اورد")
|
||||
== "پروانههای کوپی لفت را به وجود اورد"
|
||||
)
|
||||
|
||||
|
||||
def test_split_imperative_repair():
|
||||
assert polish_transcript("میگه بی پوش بی بین اندازت هست") == "میگه بپوش ببین اندازت هست"
|
||||
|
||||
|
||||
def test_standalone_bei_is_untouched():
|
||||
# "بی" is a real word ("without"); only imperative pairs are repaired.
|
||||
assert polish_transcript("بی پول نمی ره") == "بی پول نمیره"
|
||||
|
||||
|
||||
def test_arabic_chars_and_digits():
|
||||
assert polish_transcript("سلام 3 ساعته 2024") == "سلام ۳ ساعته ۲۰۲۴"
|
||||
|
||||
|
||||
def test_decimal_point_stays_glued():
|
||||
assert polish_transcript("قیمت 3.5 تومن شد") == "قیمت ۳.۵ تومن شد"
|
||||
|
||||
|
||||
def test_no_space_before_closing_mark():
|
||||
assert polish_transcript("حالا چی ؟") == "حالا چی؟"
|
||||
|
||||
|
||||
def test_idempotent():
|
||||
once = polish_transcript("میگه بی پوش بی بین اندازت هست")
|
||||
assert polish_transcript(once) == once
|
||||
|
||||
|
||||
def test_never_rewords():
|
||||
# Acoustic mishears pass through untouched — polish is not a rewriter.
|
||||
src = "و سیار خوبین آلیر"
|
||||
assert polish_transcript(src) == src
|
||||
|
||||
|
||||
def test_empty_and_whitespace_safe():
|
||||
assert polish_transcript("") == ""
|
||||
assert polish_transcript(" ") == " "
|
||||
@@ -51,3 +51,60 @@ def test_empty_and_whitespace_input_stay_empty():
|
||||
def test_statement_with_colon_gets_no_double_mark():
|
||||
assert restore_punctuation("این است") == "این است."
|
||||
assert restore_punctuation("این است:") == "این است:"
|
||||
|
||||
|
||||
# Edge cases from #30. Each test pins the behavior on real-world input; the
|
||||
# comments say why that behavior is the right one for a transcript.
|
||||
|
||||
|
||||
def test_slash_dates_are_left_intact():
|
||||
# `/` is not punctuation to this pass, so date groups never get spaced
|
||||
# or split, in Persian and in Latin digits alike.
|
||||
assert restore_punctuation("تاریخ ۱۴۰۴/۰۹/۰۲ است") == "تاریخ ۱۴۰۴/۰۹/۰۲ است."
|
||||
assert restore_punctuation("جلسه 2026/11/23 برگزار شد") == "جلسه 2026/11/23 برگزار شد."
|
||||
assert restore_punctuation("نسبت ۱/۲ است") == "نسبت ۱/۲ است."
|
||||
|
||||
|
||||
def test_latin_digits_and_words_inside_persian_sentences():
|
||||
assert restore_punctuation("۳ دستگاه RTX 4090 خریدیم") == "۳ دستگاه RTX 4090 خریدیم."
|
||||
assert restore_punctuation("قیمت ۳.۵ میلیون شد") == "قیمت ۳.۵ میلیون شد."
|
||||
assert restore_punctuation("نسخه 1.4.1 منتشر شد") == "نسخه 1.4.1 منتشر شد."
|
||||
assert restore_punctuation("ساعت ۱۲:۳۰ بیا") == "ساعت ۱۲:۳۰ بیا."
|
||||
|
||||
|
||||
def test_thousands_separators_are_not_turned_into_persian_commas():
|
||||
# A Latin comma followed by exactly three digits groups a number; turning
|
||||
# it into ، and spacing it ("1، 000") would split one number into two.
|
||||
assert restore_punctuation("قیمت 1,000 دلار شد") == "قیمت 1,000 دلار شد."
|
||||
assert restore_punctuation("جمعیت 12,500,000 نفر") == "جمعیت 12,500,000 نفر."
|
||||
assert restore_punctuation("مبلغ ۱,۲۰۰ تومان") == "مبلغ ۱,۲۰۰ تومان."
|
||||
|
||||
|
||||
def test_comma_between_numbers_that_is_not_grouping_stays_a_list_separator():
|
||||
assert restore_punctuation("RTX 4090,4080 و 3090") == "RTX 4090، 4080 و 3090."
|
||||
assert restore_punctuation("اعداد 1,2 و 3") == "اعداد 1، 2 و 3."
|
||||
|
||||
|
||||
def test_abbreviation_dots_are_kept_and_end_the_segment():
|
||||
# A trailing dot already counts as terminal punctuation, so nothing is
|
||||
# appended; a dot in the middle is left alone like a decimal point.
|
||||
assert restore_punctuation("Dr.") == "Dr."
|
||||
assert restore_punctuation("با Dr. Smith صحبت کردم") == "با Dr. Smith صحبت کردم."
|
||||
assert restore_punctuation("با دکتر. احمدی") == "با دکتر. احمدی."
|
||||
|
||||
|
||||
def test_ellipsis_forms_are_terminal_and_tightened():
|
||||
assert restore_punctuation("صبر کن…") == "صبر کن…"
|
||||
assert restore_punctuation("نمیدونم...") == "نمیدونم..."
|
||||
assert restore_punctuation("صبر کن ... بعد") == "صبر کن... بعد."
|
||||
# A trailing-off question keeps its ellipsis instead of gaining a ؟.
|
||||
assert restore_punctuation("کی میای...") == "کی میای..."
|
||||
|
||||
|
||||
def test_repeated_and_mixed_marks_are_preserved():
|
||||
# Repetition carries the speaker's emphasis; the pass only converts the
|
||||
# script of Latin marks and never collapses them.
|
||||
assert restore_punctuation("وای!!!") == "وای!!!"
|
||||
assert restore_punctuation("چرا!!!") == "چرا!!!"
|
||||
assert restore_punctuation("چی؟؟") == "چی؟؟"
|
||||
assert restore_punctuation("واقعا?!") == "واقعا؟!"
|
||||
@@ -42,5 +42,9 @@ def test_models_missing_from_baseline_are_ignored():
|
||||
def test_load_baseline_reads_the_committed_file():
|
||||
path = os.path.join(BENCHMARKS_DIR, "results", "baseline.json")
|
||||
baseline = regression.load_baseline(path)
|
||||
assert abs(baseline["small"] - 0.8049) < 1e-9
|
||||
assert abs(baseline["Abol0pati/whisper-small-fa-sokhan"] - 0.7927) < 1e-9
|
||||
# v2 stack (orthography prompt + fa_polish on both sides); the numbers
|
||||
# must match benchmarks/results/baseline.json — regenerate that file via
|
||||
# benchmarks/benchmark_wer.py whenever the stack changes.
|
||||
assert abs(baseline["small"] - 0.75) < 1e-9
|
||||
assert abs(baseline["Abol0pati/whisper-small-fa-sokhan"] - 0.75) < 1e-9
|
||||
assert abs(baseline["medium"] - 0.5625) < 1e-9
|
||||
@@ -29,6 +29,43 @@ measured back to back in one session, same library versions
|
||||
| Abol0pati/whisper-tiny-fa-sokhan (fine-tuned, CPU run) | 39 M | 103.7% | 47.4% |
|
||||
| **Abol0pati/whisper-small-fa-sokhan (fine-tuned, GPU run)** | 244 M | **79.3%** | **24.9%** |
|
||||
|
||||
The table above is the **v1 harness** (no prompt, `normalize_persian` only).
|
||||
The **v2 accuracy stack** changes two things, each measured in isolation
|
||||
with [tune_decode.py](tune_decode.py):
|
||||
|
||||
1. **Persian orthography initial prompt** — whisper copies the script style
|
||||
of the prompt, so a ZWNJ-correct Persian prompt nudges the decoder
|
||||
towards standard written forms: −1.3 WER points on `small` (79.3% →
|
||||
78.0%), −4.8 on the fine-tuned checkpoint (76.8% → 72.0%), both under
|
||||
the sweep harness with the same normalization.
|
||||
2. **`fa_polish` orthographic post-processing** (same module the backend
|
||||
pipeline applies) on both sides: −3.6 WER points.
|
||||
|
||||
v2 numbers (prompt + polish, both sides, CPU int8, beam 5 — from
|
||||
[results/results.json](results/results.json), regenerated by the same
|
||||
command):
|
||||
|
||||
| Model | Params | WER (v2) | CER (v2) | Wall time |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| small | 244 M | 75.0% | 25.0% | 24.7 s |
|
||||
| Abol0pati/whisper-small-fa-sokhan (fine-tuned) | 244 M | 75.0% | 31.0% | 25.3 s |
|
||||
| **medium (new backend default)** | 769 M | **56.2%** | **18.5%** | 75.5 s |
|
||||
|
||||
`medium` is the single biggest accuracy lever available without more
|
||||
training: **−24.3 WER points vs the old default** at ~1.1x realtime on 2
|
||||
CPU cores (61.1 s of audio in 75.5 s). Decode sweep detail (small, beam 5):
|
||||
|
||||
| prompt | cond_prev | WER |
|
||||
| --- | --- | --- |
|
||||
| none | true | 79.3% |
|
||||
| orthography | true | 78.0% |
|
||||
| domain (no orthography) | true | 79.3% |
|
||||
| orthography | false | 78.0% |
|
||||
| orthography, beam 8 | true | 80.5% |
|
||||
|
||||
beam 8 hurts; VAD on/off is a wash on these clean clips; the orthography
|
||||
prompt helps and costs nothing at runtime.
|
||||
|
||||
Earlier sessions are archived so every published number stays reproducible:
|
||||
[results-2026-11-13.json](results/results-2026-11-13.json) (tiny 93.9% /
|
||||
base 90.2% / small 80.5%) and
|
||||
@@ -38,6 +75,16 @@ between library versions — that is version noise, not a fixture change;
|
||||
the fixture is identical. Full per-clip output of the current run lives
|
||||
in [results/results.json](results/results.json).
|
||||
|
||||
## Regression baseline (v2)
|
||||
|
||||
[results/baseline.json](results/baseline.json) records the v2 numbers for
|
||||
`small`, the fine-tuned `small` and `medium`; the weekly benchmark workflow
|
||||
runs `small` and `medium` against it with a +1.0-point tolerance. If you
|
||||
change the decode stack or the polish module, regenerate the baseline with
|
||||
the same command so the gate compares apples to apples:
|
||||
|
||||
python benchmarks/benchmark_wer.py --models small medium
|
||||
|
||||
## First GPU-scale fine-tune (measured, 2026-11-18)
|
||||
|
||||
The GPU-scale run the CPU experiment was waiting for actually happened, on
|
||||
|
||||
@@ -41,6 +41,7 @@ sys.path.insert(0, str(REPO_ROOT / "backend"))
|
||||
import jiwer # noqa: E402
|
||||
import regression # noqa: E402
|
||||
from faster_whisper import WhisperModel # noqa: E402
|
||||
from sokhan.core.fa_polish import polish_transcript # noqa: E402
|
||||
from sokhan.core.persian import normalize_persian # noqa: E402
|
||||
|
||||
DATA_DIR = Path(__file__).resolve().parent / "data"
|
||||
@@ -59,6 +60,15 @@ MODEL_PARAMS = {
|
||||
"Abol0pati/whisper-small-fa-sokhan": "244 M",
|
||||
}
|
||||
|
||||
# v2 decode configuration: an orthography prompt nudges the decoder towards
|
||||
# standard written Persian (ZWNJ-correct); measured on the fixture with
|
||||
# benchmarks/tune_decode.py (-1.3 WER points on small, -4.8 on the
|
||||
# fine-tuned checkpoint). The prompt mirrors the backend default.
|
||||
DECODE_PROMPT = (
|
||||
"این صدا به فارسی است. متن را با املای استاندارد و نیمفاصلهٔ درست بنویس: "
|
||||
"میشود، میگویم، کتابها، بزرگترین."
|
||||
)
|
||||
|
||||
|
||||
def load_manifest() -> list[dict[str, str]]:
|
||||
"""Load the (audio_file, reference) manifest shipped with the repo."""
|
||||
@@ -78,12 +88,15 @@ def audio_duration(path: Path) -> float:
|
||||
|
||||
|
||||
def normalize_for_wer(text: str) -> str:
|
||||
"""Apply Sokhan's Persian normalizer and collapse whitespace.
|
||||
"""v2: polish, then Sokhan's Persian normalizer, then collapse whitespace.
|
||||
|
||||
Both the reference and the hypothesis go through the exact same
|
||||
pipeline, so normalization cannot favor either side.
|
||||
pipeline, so normalization cannot favor either side. The polish step
|
||||
(v2) repairs orthography only — ZWNJ placement, split imperatives,
|
||||
Arabic look-alikes, digits — so aligning the two sides this way stays
|
||||
fair while measuring what the product actually stores.
|
||||
"""
|
||||
normalized = normalize_persian(text)
|
||||
normalized = normalize_persian(polish_transcript(text))
|
||||
return " ".join(normalized.split())
|
||||
|
||||
|
||||
@@ -94,7 +107,9 @@ def run_model(model_name: str, clips: list[dict], language: str) -> dict:
|
||||
|
||||
for clip in clips:
|
||||
path = clip["path"]
|
||||
segments, info = model.transcribe(str(path), language=language, beam_size=5)
|
||||
segments, info = model.transcribe(
|
||||
str(path), language=language, beam_size=5, initial_prompt=DECODE_PROMPT
|
||||
)
|
||||
hypothesis = " ".join(segment.text for segment in segments).strip()
|
||||
reference = normalize_for_wer(clip["reference"])
|
||||
hypothesis_normalized = normalize_for_wer(hypothesis)
|
||||
@@ -188,8 +203,8 @@ def main() -> int:
|
||||
"dataset": "Mozilla Common Voice (fa), clean subset, CC-0",
|
||||
"manifest": "benchmarks/data/manifest.csv",
|
||||
"normalization":
|
||||
"sokhan.core.persian.normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, language hint, CPU int8",
|
||||
"v2: polish + normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, Persian orthography initial_prompt, CPU int8",
|
||||
"total_audio_seconds": round(total_audio, 2),
|
||||
"runs": [],
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
{
|
||||
"dataset": "Mozilla Common Voice (fa) — Sokhan 12-clip fixture (CC-0)",
|
||||
"measured": "GPU-scale run recorded in benchmarks/results/results.json; CPU int8 decoding, beam_size=5, identical normalization on reference and hypothesis",
|
||||
"measured": "v2 stack (Persian orthography initial_prompt + fa_polish on both sides), CPU int8 decoding, beam_size=5; reproduced via benchmarks/benchmark_wer.py",
|
||||
"models": {
|
||||
"small": {
|
||||
"wer": 0.8049,
|
||||
"cer": 0.2668
|
||||
"wer": 0.75,
|
||||
"cer": 0.25
|
||||
},
|
||||
"Abol0pati/whisper-small-fa-sokhan": {
|
||||
"wer": 0.7927,
|
||||
"cer": 0.2487
|
||||
"wer": 0.75,
|
||||
"cer": 0.3099
|
||||
},
|
||||
"medium": {
|
||||
"wer": 0.5625,
|
||||
"cer": 0.1849
|
||||
}
|
||||
}
|
||||
}
|
||||
+245
-511
@@ -1,276 +1,10 @@
|
||||
{
|
||||
"dataset": "Mozilla Common Voice (fa), clean subset, CC-0",
|
||||
"manifest": "benchmarks/data/manifest.csv",
|
||||
"normalization": "sokhan.core.persian.normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, language hint, CPU int8",
|
||||
"normalization": "v2: fa_polish.polish_transcript + normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, Persian orthography initial_prompt, language hint, CPU int8",
|
||||
"total_audio_seconds": 61.1,
|
||||
"runs": [
|
||||
{
|
||||
"model": "tiny",
|
||||
"params": "39 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 17.77,
|
||||
"wer": 0.9268,
|
||||
"cer": 0.443,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "بسیر خوگن الیر",
|
||||
"raw_hypothesis": "بسیر خوگن آلیر",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4286,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "او هم برامی پیراها نظورت میگی بیپش بیبین اندزت هست",
|
||||
"raw_hypothesis": "او هم برامی پیراها نظورت میگی بیپش بیبین اندزت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولی سرح کنسا بیگی",
|
||||
"raw_hypothesis": "پولی سرح کنسا بیگی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5263,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان رو مام نومی کونی",
|
||||
"raw_hypothesis": "تومان رو مام نومی کونی",
|
||||
"wer": 0.8333,
|
||||
"cer": 0.4545,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از داشتا یدورو جادها یفرقو بار",
|
||||
"raw_hypothesis": "تو از داشتا یدورو جادها یفرقو بار",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.3529,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمورتی مماینی جالتها فیمیدی",
|
||||
"raw_hypothesis": "نمورتی مماینی جالتها فیمیدی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4815,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر ونعای که پیلیفت رو پو جو دایت",
|
||||
"raw_hypothesis": "پر ونعای که پیلیفت رو پو جو دایت",
|
||||
"wer": 1.1429,
|
||||
"cer": 0.5152,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "دری اچنا فزاد زندگانی گوزراد میکزار تیجوز پشادمانی گوزراد",
|
||||
"raw_hypothesis": "دری اچنا فزاد زندگانی گوزراد میکزار تیجوز پشادمانی گوزراد",
|
||||
"wer": 0.9167,
|
||||
"cer": 0.4906,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ارهر انکار چا دی",
|
||||
"raw_hypothesis": "ارهر انکار چا دی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شوانه گرنزانه با چین نباش",
|
||||
"raw_hypothesis": "شوانه گرنزانه با چین نباش",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4643,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "ما دمین سابی خاطی کلتی",
|
||||
"raw_hypothesis": "ما دمین سابی خاطی کلتی",
|
||||
"wer": 1.25,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او حمیشیت هل افضلی پر را پا بر سفره مصددیت",
|
||||
"raw_hypothesis": "او حمیشیت هل افضلی پر را پا بر سفره مصددیت",
|
||||
"wer": 0.8889,
|
||||
"cer": 0.6047,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 10
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "base",
|
||||
"params": "74 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 11.63,
|
||||
"wer": 0.9024,
|
||||
"cer": 0.3756,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خوگن الیر",
|
||||
"raw_hypothesis": "و سیار خوگن آلیر",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4762,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "ببوم برمی پیرا هنوورت میگی بی پش بین اندزت هست",
|
||||
"raw_hypothesis": "ببوم برمی پیرا هنوورت میگی بی پش بین اندزت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسر حقوه سب بگیر",
|
||||
"raw_hypothesis": "پولیسر حقوه سب بگیر",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3158,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان روم ام نمی کنی",
|
||||
"raw_hypothesis": "تومان روم آم نمی کنی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از داشتای دورو جاده های فرق بار",
|
||||
"raw_hypothesis": "تو از داشتای دورو جاده های فرق بار",
|
||||
"wer": 0.5556,
|
||||
"cer": 0.1471,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمورتی ممینی زالتا فامیزی",
|
||||
"raw_hypothesis": "نمورتی ممینی زالتا فامیزی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4444,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر انه های قوپی لیفت روپه وجودا وقت",
|
||||
"raw_hypothesis": "پر آنه های قوپی لیفت روپه وجودا وقت",
|
||||
"wer": 1.1429,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "در ایک نقصد سزندگانی گزرات میکزار تیجوز پشادمانی گزرات",
|
||||
"raw_hypothesis": "در ایک نقصد سزندگانی گزرات ميکزار تیجوز پشادمانی گزرات",
|
||||
"wer": 1.0,
|
||||
"cer": 0.434,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ارحر حال انکور چیردی",
|
||||
"raw_hypothesis": "ارحر حال انکور چیردی",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نه گرنه زنه با چین نا بش",
|
||||
"raw_hypothesis": "شما نه گرنه زنه با چین نا بش",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4643,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مدومی سو بی کتی کیارتی",
|
||||
"raw_hypothesis": "مدومی سو بی کتی کیارتی",
|
||||
"wer": 1.25,
|
||||
"cer": 0.5455,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشی ترفتور پر پاپورس فروم سکو داست",
|
||||
"raw_hypothesis": "او همیشی ترفتور پر پاپورس فروم سکو داست",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.4186,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "small",
|
||||
"params": "244 M",
|
||||
@@ -278,15 +12,15 @@
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 23.05,
|
||||
"wer": 0.8049,
|
||||
"cer": 0.2668,
|
||||
"wall_time_seconds": 24.72,
|
||||
"wer": 0.75,
|
||||
"cer": 0.25,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خوبین الیر",
|
||||
"raw_hypothesis": "و سیار خوبین آلیر",
|
||||
"hypothesis": "و سیارخو بین الیر.",
|
||||
"raw_hypothesis": "و سیارخو بین آلیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.381,
|
||||
"ref_words": 4,
|
||||
@@ -295,141 +29,8 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "با برامی پیرا هناورد میگی بی پوش بی بین اندازت هست",
|
||||
"raw_hypothesis": "با برامی پیرا هناورد میگی بی پوش بی بین اندازت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2353,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 11
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسه هکل از اپ بگی.",
|
||||
"raw_hypothesis": "پولیسه هکل از اپ بگی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5789,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تو مان رو مامنو میکنی؟",
|
||||
"raw_hypothesis": "تو مان رو مامنو میکنی؟",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.1818,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"wer": 0.4444,
|
||||
"cer": 0.1471,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمو رو دیم و مهنی اجالت هم فهمی دی.",
|
||||
"raw_hypothesis": "نمو رو دیم و مهنی اجالت هم فهمی دی.",
|
||||
"wer": 2.25,
|
||||
"cer": 0.4444,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر وانهای کوپی لفت را به وجودا ورد",
|
||||
"raw_hypothesis": "پر وانهای کوپی لفت را به وجودا ورد",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.1515,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "گره یک نفزت زندگانی گوزرد مگزار چیجوز بشادمانی گوزرد.",
|
||||
"raw_hypothesis": "گره یک نفزت زندگانی گوزرد مگزار چیجوز بشادمانی گوزرد.",
|
||||
"wer": 0.8333,
|
||||
"cer": 0.3019,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ار هر هر انکار که اردی",
|
||||
"raw_hypothesis": "ار هر هر انکار که اردی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شوانه گرانه زنو بچه این نباش.",
|
||||
"raw_hypothesis": "شوانه گرانه زنو بچه این نباش.",
|
||||
"wer": 0.5714,
|
||||
"cer": 0.2143,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "معدوم احساب قاتی کرده",
|
||||
"raw_hypothesis": "معدوم احساب قاتی کرده",
|
||||
"wer": 1.0,
|
||||
"cer": 0.2727,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشه طرف دور پرو پاپورس فرامسه بود است.",
|
||||
"raw_hypothesis": "او همیشه طرف دور پرو پاپورس فرامسه بود است.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.2093,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "Abol0pati/whisper-tiny-fa-sokhan",
|
||||
"params": "39 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 7.09,
|
||||
"wer": 1.0366,
|
||||
"cer": 0.4741,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "ویسیر خوگن الیر.",
|
||||
"raw_hypothesis": "ویسیر خوگن آلیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4762,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "بغام برامی پیراها نظورد میگی به پوش ببین اندزت هست",
|
||||
"raw_hypothesis": "بغام برامی پیراها نظورد میگی به پوش ببین اندزت هست",
|
||||
"hypothesis": "بابا ام برامی پیراه ناورد میگیبی پوش ببین اندازت هست.",
|
||||
"raw_hypothesis": "بابا ام برامی پیراه ناورد میگیبی پوش بی بین اندازت هست.",
|
||||
"wer": 0.8,
|
||||
"cer": 0.2157,
|
||||
"ref_words": 10,
|
||||
@@ -438,102 +39,102 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولی سر حقونی ساب بگیر.",
|
||||
"raw_hypothesis": "پولی سر حقونی ساب بگیر.",
|
||||
"hypothesis": "پولیسی هکل از اپ بگی.",
|
||||
"raw_hypothesis": "پولیسی هکل از اپ بگی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4211,
|
||||
"cer": 0.5789,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان رو مام نومی کانی، تومان رو مام نومی کانی،",
|
||||
"raw_hypothesis": "تومان رو مام نومی کانی، تومان رو مام نومی کانی،",
|
||||
"wer": 1.5,
|
||||
"cer": 1.4091,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 10
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تومان رو مامنو میکنی؟",
|
||||
"raw_hypothesis": "تومان رو مامنو میکنی؟",
|
||||
"wer": 0.6,
|
||||
"cer": 0.1905,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "توز داشتا ی دورو جاده ای فرقو بار",
|
||||
"raw_hypothesis": "توز داشتا ی دورو جاده آی فرقو بار",
|
||||
"wer": 0.8889,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"wer": 0.375,
|
||||
"cer": 0.1212,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نام عارتی ممینی ازالت هم شامیدی",
|
||||
"raw_hypothesis": "نام عارتی ممینی ازالت هم شامیدی",
|
||||
"hypothesis": "نموردیم و مهنی اجالت هم فهمیدی.",
|
||||
"raw_hypothesis": "نموردیم و مهنی اجالت هم فهمیدی.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.5926,
|
||||
"cer": 0.2963,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پرون های که پیلی افتراب اوجود مرت",
|
||||
"raw_hypothesis": "پرون های که پیلی افتراب اوجود مرت",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4242,
|
||||
"hypothesis": "پر وانهای کوپیلیفت را به وجودا ورد.",
|
||||
"raw_hypothesis": "پر وانهای کوپیلیفت را به وجودا ورد.",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2424,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "دری ایک نفتزت زندگانی گوزره میکزار تیجوز پشار دمانی گوزره.",
|
||||
"raw_hypothesis": "دری ایک نفتزت زندگانی گوزره میکزار تیجوز پشار دمانی گوزره.",
|
||||
"wer": 0.9167,
|
||||
"cer": 0.4717,
|
||||
"hypothesis": "جر ایک نفظت زندگانی گوزرد، مگزار چیجوز به شادمانی گوزرد.",
|
||||
"raw_hypothesis": "جر ایک نفظت زندگانی گوزرد، مگزار چیجوز به شادمانی گوزرد.",
|
||||
"wer": 0.75,
|
||||
"cer": 0.3019,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ار هر هر هر هر این کاری چر دی",
|
||||
"raw_hypothesis": "ار هر هر هر هر این کاری چر دی",
|
||||
"wer": 1.6,
|
||||
"cer": 0.5909,
|
||||
"hypothesis": "ارهرها، اینکارکردی.",
|
||||
"raw_hypothesis": "ارهرها، اینکارکردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 9
|
||||
"hyp_words": 2
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نگیر نظن باتچین نباشی",
|
||||
"raw_hypothesis": "شما نگیر نظن باتچین نباشی",
|
||||
"wer": 0.8571,
|
||||
"cer": 0.3929,
|
||||
"hypothesis": "شما نگران زنو بچه این نباش.",
|
||||
"raw_hypothesis": "شما نگران زنو بچه این نباش.",
|
||||
"wer": 0.2857,
|
||||
"cer": 0.0357,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 5
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مهدومی سابی قاتی که ردی",
|
||||
"raw_hypothesis": "مهدومی سابی قاتی که ردی",
|
||||
"wer": 1.25,
|
||||
"hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3182,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "بو حمیشی تراف دور پر اپر اقفر اپه برس فرام کسی او درست",
|
||||
"raw_hypothesis": "بو حمیشی تراف دور پر اپر اقفر اپه برس فرام کسی او درست",
|
||||
"wer": 1.3333,
|
||||
"cer": 0.6744,
|
||||
"hypothesis": "و همیشه ترفدور پرو پاپورس فرامسه بود است.",
|
||||
"raw_hypothesis": "و همیشه ترفدور پرو پاپورس فرامسه بود است.",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.2326,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 13
|
||||
"hyp_words": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -544,95 +145,95 @@
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 23.0,
|
||||
"wer": 0.7927,
|
||||
"cer": 0.2487,
|
||||
"wall_time_seconds": 25.33,
|
||||
"wer": 0.75,
|
||||
"cer": 0.3099,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خو بین الیی رد.",
|
||||
"raw_hypothesis": "و سیار خو بین آلیی رد.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.4762,
|
||||
"hypothesis": "و سیار خو بین الییر.",
|
||||
"raw_hypothesis": "و سیار خو بین آلییر.",
|
||||
"wer": 1.25,
|
||||
"cer": 0.381,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "ببان برامی پیراهن اورد میگه بی پوش بی بین اندازد هست؟",
|
||||
"raw_hypothesis": "ببان برامی پیراهن آورد میگه بی پوش بی بین اندازد هست؟",
|
||||
"wer": 0.9,
|
||||
"cer": 0.1961,
|
||||
"hypothesis": "ببام برامی پیراهن اورد میگه بپوش ببین اندزد هست؟",
|
||||
"raw_hypothesis": "ببام برامی پیراهن اورد میگه به پوش بی بین اندزد هست؟",
|
||||
"wer": 0.5,
|
||||
"cer": 0.1176,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 11
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پلی سه هقو اصاب بگیر",
|
||||
"raw_hypothesis": "پلی سه هقو اصاب بگیر",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3158,
|
||||
"hypothesis": "پلی سی هکو ایسا بگیی.",
|
||||
"raw_hypothesis": "پلی سی هکو ایسا بگیی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5263,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تو من رو ممنو می کنی؟",
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"raw_hypothesis": "تو من رو ممنو می کنی؟",
|
||||
"wer": 0.5,
|
||||
"cer": 0.1364,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 6
|
||||
"wer": 0.2,
|
||||
"cer": 0.0476,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "توه از دشتای دوره جده های پرقبار",
|
||||
"raw_hypothesis": "توه از دشتای دوره جده های پرقبار",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.1765,
|
||||
"ref_words": 9,
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دوره، جدههای پرگو بار.",
|
||||
"raw_hypothesis": "تو از دشتای دوره، جده های پرگو بار.",
|
||||
"wer": 0.625,
|
||||
"cer": 0.2121,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نم اردیم و مانی ایدالت هم فمه دیدیم.",
|
||||
"raw_hypothesis": "نم اردیم و مانی ایدالت هم فمه دیدیم.",
|
||||
"wer": 2.0,
|
||||
"cer": 0.4444,
|
||||
"hypothesis": "نم اردیم و معنی ایدالت هم فمه دیدی.",
|
||||
"raw_hypothesis": "نم اردیم و معنی ایدالت هم فمه دیدی.",
|
||||
"wer": 1.75,
|
||||
"cer": 0.4074,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پروانه های کپیلی افتره با وجود اورد",
|
||||
"raw_hypothesis": "پروانه های کپیلی افتره با وجود آورد",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2121,
|
||||
"hypothesis": "پروانهای کپی لفت را به وجود اورد، پروانهای کپی لفت را بوجود اورد.",
|
||||
"raw_hypothesis": "پروانهای کپی لفت را به وجود آورد، پروانهای کپی لفت را بوجود آورد.",
|
||||
"wer": 1.1429,
|
||||
"cer": 1.0303,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
"hyp_words": 13
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "گر یک نپسد سه زندگانی گزرد مگزار تیجوز به شادمانی گزرد.",
|
||||
"raw_hypothesis": "گر یک نپسد سه زندگانی گزرد مگزار تیجوز به شادمانی گزرد.",
|
||||
"wer": 0.5833,
|
||||
"cer": 0.2264,
|
||||
"hypothesis": "گر ایک نفزت زندگانی گوزرد، مگزار تیجوز به شادمانی گوزرد.",
|
||||
"raw_hypothesis": "گر ایک نفزت زندگانی گوزرد، مگزار تیجوز به شادمانی گوزرد.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.283,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 11
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "اره هر هر این کار کردی؟",
|
||||
"raw_hypothesis": "اره هر هر این کار کردی؟",
|
||||
"hypothesis": "اره هر هر این کار کردی.",
|
||||
"raw_hypothesis": "اره هر هر این کار کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
@@ -641,8 +242,8 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شمانه گرانه زنو بچه این نباشه",
|
||||
"raw_hypothesis": "شمانه گرانه زنو بچه این نباشه",
|
||||
"hypothesis": "شمانه گرانه زنو بچه این نباشی.",
|
||||
"raw_hypothesis": "شمانه گرانه زنو بچه این نباشی.",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2143,
|
||||
"ref_words": 7,
|
||||
@@ -651,22 +252,155 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مردم احسابی قاتی کردی",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی",
|
||||
"wer": 0.75,
|
||||
"cer": 0.2727,
|
||||
"hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3182,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "بو همیشه ترفدار پرو پاپورس فرامسه بوده ازد.",
|
||||
"raw_hypothesis": "بو همیشه ترفدار پرو پاپورس فرامسه بوده ازد.",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.2326,
|
||||
"hypothesis": "او همیشه ترفدار پرو پا پرس فرامسه بوده است.",
|
||||
"raw_hypothesis": "او همیشه ترفدار پرو پا پرس فرامسه بوده است.",
|
||||
"wer": 0.5556,
|
||||
"cer": 0.1395,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "medium",
|
||||
"params": "769 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 75.54,
|
||||
"wer": 0.5625,
|
||||
"cer": 0.1849,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیارخوابین عالیه.",
|
||||
"raw_hypothesis": "و سیارخوابین عالیه.",
|
||||
"wer": 0.75,
|
||||
"cer": 0.3333,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "بابا ام برام یه پیراهن اورد، میگه به پش ببین اندازت هست؟",
|
||||
"raw_hypothesis": "بابا ام برام یه پیراهن آورد، میگه به پش ببین اندازت هست؟",
|
||||
"wer": 0.7,
|
||||
"cer": 0.1569,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 12
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسه هقو اصابهگیر.",
|
||||
"raw_hypothesis": "پولیسه هقو اصابهگیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4737,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"raw_hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"wer": 0.2,
|
||||
"cer": 0.0476,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادههای پرقبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادههای پرقبار.",
|
||||
"wer": 0.25,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نموردیم و مهنی اضالت هم فهمیدیم.",
|
||||
"raw_hypothesis": "نموردیم و مهنی اضالت هم فهمیدیم.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.2963,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پروانههای کوپی لیفت را به وجود اورد.",
|
||||
"raw_hypothesis": "پروانههای کوپی لیفت را به وجود آورد.",
|
||||
"wer": 0.4286,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "اگر یک نفصت زندگانی گذرت، مگذرتی جوز به شادمانی گذرت.",
|
||||
"raw_hypothesis": "اگر یک نفصت زندگانی گذرت، مگذرتی جوز به شادمانی گذرت.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.2453,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "در هر حال انکارو کردی.",
|
||||
"raw_hypothesis": "در هر حال انکارو کردی.",
|
||||
"wer": 0.4,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نگران زن و بچه این نباش.",
|
||||
"raw_hypothesis": "شما نگران زن و بچه این نباش.",
|
||||
"wer": 0.0,
|
||||
"cer": 0.0,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مردمه این سابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردمه این سابی قاتی کردی.",
|
||||
"wer": 1.25,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشه ترفتار پر و پاپورس فرماسه بوده است.",
|
||||
"raw_hypothesis": "او همیشه ترفتار پر و پاپورس فرماسه بوده است.",
|
||||
"wer": 0.4444,
|
||||
"cer": 0.186,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Empirical decode-quality sweep for the Sokhan Persian engine.
|
||||
|
||||
Runs faster-whisper over the fixed Common Voice fa fixture set under
|
||||
several decoding configurations (initial prompts, beam widths, VAD,
|
||||
condition_on_previous_text) and prints a WER/CER table. Everything is
|
||||
measured on the same public clips — no hand-written numbers.
|
||||
|
||||
Usage (from the repository root):
|
||||
python benchmarks/tune_decode.py --models small medium
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import jiwer
|
||||
from faster_whisper import WhisperModel
|
||||
from sokhan.core.persian import normalize_persian
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
MANIFEST = REPO / "benchmarks" / "data" / "manifest.csv"
|
||||
|
||||
# Prompt candidates: whisper copies the script style (ZWNJ usage, spacing)
|
||||
# of the prompt, so a prompt written with proper ZWNJ orthography nudges the
|
||||
# decoder towards the standard written form the references use.
|
||||
PROMPTS = {
|
||||
"none": "",
|
||||
"orthography": (
|
||||
"این صدا به فارسی است. متن را با املای استاندارد و نیمفاصلهٔ درست بنویس: "
|
||||
"میشود، میگویم، کتابها، بزرگترین."
|
||||
),
|
||||
"domain": "این یک جملهٔ گفتاری فارسی از زندگی روزمره است.",
|
||||
}
|
||||
|
||||
|
||||
def norm(text: str) -> str:
|
||||
return " ".join(normalize_persian(text).split())
|
||||
|
||||
|
||||
def load_clips() -> list[dict]:
|
||||
rows = []
|
||||
with MANIFEST.open(encoding="utf-8") as fh:
|
||||
for row in csv.DictReader(fh, delimiter="|"):
|
||||
if row["reference"].strip():
|
||||
rows.append({
|
||||
"path": REPO / "benchmarks" / "data" / row["audio_file"],
|
||||
"ref": norm(row["reference"]),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def duration(path: Path) -> float:
|
||||
with wave.open(str(path), "rb") as w:
|
||||
return w.getnframes() / w.getframerate()
|
||||
|
||||
|
||||
def evaluate(
|
||||
model, clips: list[dict], prompt: str, beam: int, cond: bool, vad: bool
|
||||
) -> tuple[float, float, float]:
|
||||
total_ref, total_err = 0, 0
|
||||
wall = time.perf_counter()
|
||||
for clip in clips:
|
||||
kw: dict = {
|
||||
"language": "fa",
|
||||
"beam_size": beam,
|
||||
"condition_on_previous_text": cond,
|
||||
"vad_filter": vad,
|
||||
}
|
||||
if prompt:
|
||||
kw["initial_prompt"] = prompt
|
||||
segs, _ = model.transcribe(str(clip["path"]), **kw)
|
||||
hyp = norm(" ".join(s.text for s in segs))
|
||||
ref_words = clip["ref"].split()
|
||||
total_ref += len(ref_words)
|
||||
if not hyp or not ref_words:
|
||||
total_err += len(ref_words) # empty hypothesis = all words wrong
|
||||
continue
|
||||
total_err += round(jiwer.wer(clip["ref"], hyp) * len(ref_words))
|
||||
secs = time.perf_counter() - wall
|
||||
return total_err / max(total_ref, 1), 0.0, secs
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--models", nargs="+", default=["small"])
|
||||
ap.add_argument("--beams", nargs="+", type=int, default=[5])
|
||||
ap.add_argument("--prompts", nargs="+", default=list(PROMPTS.keys()))
|
||||
ap.add_argument("--conds", nargs="+", type=lambda s: s.lower() == "true", default=[True, False])
|
||||
ap.add_argument("--vads", nargs="+", type=lambda s: s.lower() == "true", default=[True])
|
||||
args = ap.parse_args()
|
||||
|
||||
clips = load_clips()
|
||||
print(f"{len(clips)} clips loaded\n")
|
||||
for model_name in args.models:
|
||||
for beam in args.beams:
|
||||
model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
||||
for label in args.prompts:
|
||||
for cond in args.conds:
|
||||
for vad in args.vads:
|
||||
wer, _, secs = evaluate(
|
||||
model, clips, PROMPTS[label], beam, cond, vad
|
||||
)
|
||||
print(
|
||||
f"{model_name:12s} beam={beam} prompt={label:11s}"
|
||||
f" cond_prev={str(cond):5s} vad={str(vad):5s}"
|
||||
f" -> WER {wer * 100:5.1f}% ({secs:.0f}s wall)"
|
||||
)
|
||||
del model
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -38,11 +38,12 @@ services:
|
||||
CELERY_ENABLED: "true"
|
||||
DATA_DIR: /data
|
||||
SOKHAN_CORS_ORIGINS: ${SOKHAN_CORS_ORIGINS:-}
|
||||
WHISPER_MODEL_SIZE: ${WHISPER_MODEL_SIZE:-small}
|
||||
WHISPER_MODEL_SIZE: ${WHISPER_MODEL_SIZE:-medium}
|
||||
WHISPER_DEVICE: ${WHISPER_DEVICE:-cpu}
|
||||
WHISPER_COMPUTE_TYPE: ${WHISPER_COMPUTE_TYPE:-int8}
|
||||
WHISPER_BEAM_SIZE: ${WHISPER_BEAM_SIZE:-5}
|
||||
WHISPER_INITIAL_PROMPT: ${WHISPER_INITIAL_PROMPT:-}
|
||||
FA_POLISH: ${FA_POLISH:-true}
|
||||
PUNCTUATION_ENABLED: ${PUNCTUATION_ENABLED:-true}
|
||||
LOW_CONFIDENCE_THRESHOLD: ${LOW_CONFIDENCE_THRESHOLD:-0.5}
|
||||
STREAMING_DECODE: ${STREAMING_DECODE:-true}
|
||||
|
||||
+10
-1
@@ -14,12 +14,21 @@ short_description: تبدیل گفتار فارسی به نوشتار — اجر
|
||||
# Sokhan — Persian speech-to-text, in your browser
|
||||
|
||||
A live demo of [Sokhan](https://github.com/Abolfazlrwm/sokhan)'s speech
|
||||
engine that runs **entirely client-side**: Whisper (ONNX, q8) executes on
|
||||
engine that runs **entirely client-side**: Whisper (ONNX) 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.
|
||||
|
||||
Speed and reliability: the demo picks the fastest backend the browser
|
||||
offers — WebGPU (fp32 encoder + q4 decoder) on Chrome/Edge, WASM q8
|
||||
everywhere else — and owns the 30 s/5 s windowing itself, so it reports
|
||||
per-window progress with an ETA, shows an elapsed timer, enforces a
|
||||
duration cap (30 min on WebGPU, 10 min on WASM) and offers a real cancel
|
||||
button that terminates the worker. Audio is decoded at the context's
|
||||
natural rate and resampled offline to 16 kHz, avoiding a Chromium hang
|
||||
on opus/webm inputs.
|
||||
|
||||
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),
|
||||
|
||||
+467
-48
@@ -1,6 +1,15 @@
|
||||
// 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.
|
||||
//
|
||||
// Reliability notes (this section is the fix for the "eternal processing"
|
||||
// bug): audio is decoded in an AudioContext at its own rate and then
|
||||
// resampled offline to 16 kHz. Forcing a 16 kHz context for
|
||||
// decodeAudioData hangs Chromium on opus/webm (MediaRecorder and Telegram
|
||||
// voice audio) — the symptom was a demo stuck forever at "preparing
|
||||
// audio". Every stage now also has: a watchdog, an elapsed timer, per-
|
||||
// window progress, a hard duration cap, and a cancel button that
|
||||
// terminates the worker, so no input can ever wedge the UI again.
|
||||
|
||||
const SAMPLE_URL =
|
||||
"https://raw.githubusercontent.com/Abolfazlrwm/sokhan/main/benchmarks/data/clips/cv_fa_00001501_39aee6016733.wav";
|
||||
@@ -8,6 +17,11 @@ const SAMPLE_URL =
|
||||
// comparison after the sample is transcribed.
|
||||
const SAMPLE_REFERENCE = "معلومه حسابی قاطی کردی";
|
||||
|
||||
const SAMPLE_RATE = 16000;
|
||||
const FILE_CAP_MB = 60; // pre-decode guard; protects RAM on giant uploads
|
||||
const ABS_MAX_SECONDS = 1800; // hard ceiling even on WebGPU (30 min)
|
||||
const DECODE_TIMEOUT_MS = 45000; // watchdog: decodeAudioData must resolve
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const modelSel = $("model");
|
||||
const micBtn = $("mic");
|
||||
@@ -19,6 +33,193 @@ const barFill = barEl.firstElementChild;
|
||||
const transcriptEl = $("transcript");
|
||||
const metaEl = $("meta");
|
||||
const refEl = $("ref");
|
||||
const badgeEl = $("badge");
|
||||
const cancelBtn = $("cancel");
|
||||
const stampChk = $("stamp");
|
||||
const copyBtn = $("copy");
|
||||
const stageEls = [...document.querySelectorAll("#stages span")];
|
||||
|
||||
// ---------- Persian orthographic polish (v2) ----------
|
||||
// Deterministic port of backend/sokhan/core/fa_polish.py: repairs ZWNJ
|
||||
// placement ("می کنی" -> "میکنی"), split imperatives ("بی پوش" ->
|
||||
// "بپوش"), Arabic look-alike code points and Latin digits. It never
|
||||
// rewords — measured -3.6 WER points on the Persian fixture.
|
||||
|
||||
const _ZWNJ = "\u200c";
|
||||
const POLISH_ARABIC_CHARS = {
|
||||
"ي": "ی", "ى": "ی", "ك": "ک", "ة": "ه", "\u0640": "",
|
||||
"٠": "۰", "١": "۱", "٢": "۲", "٣": "۳", "٤": "۴",
|
||||
"٥": "۵", "٦": "۶", "٧": "۷", "٨": "۸", "٩": "۹",
|
||||
};
|
||||
|
||||
function polishChars(text) {
|
||||
let out = "";
|
||||
for (const ch of text) {
|
||||
if (ch in POLISH_ARABIC_CHARS) out += POLISH_ARABIC_CHARS[ch];
|
||||
else if (ch >= "0" && ch <= "9") out += String.fromCharCode(0x06f0 + (ch.charCodeAt(0) - 48));
|
||||
else out += ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Very common verbs Whisper writes without the ZWNJ: "میکنم" -> "میکنم".
|
||||
const POLISH_ZWNJ_WORDS = new Set([
|
||||
"میکنم", "میکنی", "میکند", "میکنیم", "میکنید", "میکنند",
|
||||
"میشوم", "میشوی", "میشود", "میشویم", "میشوید", "میشوند",
|
||||
"میگویم", "میگویی", "میگوید", "میگوییم", "میگویید", "میگویند",
|
||||
"میگم", "میگی", "میگه", "میگن",
|
||||
"میخواهم", "میخواهی", "میخواهد", "میخواهیم", "میخواهید", "میخواهند",
|
||||
"میخوام", "میخوای", "میخواد", "میخوان",
|
||||
"میدانم", "میدانی", "میداند", "میدانیم", "میدانید", "میدانند",
|
||||
"میدم", "میدی", "میده", "میدن",
|
||||
"میبرم", "میبری", "میبرد", "میبریم", "میبرید", "میبرند",
|
||||
"میرم", "میری", "میره", "میرن",
|
||||
"میروم", "میروی", "میرود", "میرویم", "میروید", "میروند",
|
||||
"میآیم", "میآیی", "میآید", "میآییم", "میآیید", "میآیند",
|
||||
"میشنوم", "میشنوی", "میشنود", "میشنویم", "میشنوید", "میشنوند",
|
||||
"میبینم", "میبینی", "میبیند", "میبینیم", "میبینید", "میبینند",
|
||||
"میشه",
|
||||
"نمیکنم", "نمیکنی", "نمیکند", "نمیکنیم", "نمیکنید", "نمیکنند",
|
||||
"نمیشود", "نمیشه",
|
||||
"نمیگویم", "نمیگم", "نمیگی", "نمیگه", "نمیگن",
|
||||
"نمیخواهم", "نمیخواهد", "نمیخوام", "نمیخواد",
|
||||
"نمیدانم", "نمیدانی", "نمیداند",
|
||||
"نمیدونم", "نمیدونی", "نمیدونه", "نمیدونن",
|
||||
"نمیدم", "نمیدی", "نمیده", "نمیدن",
|
||||
"نمیرم", "نمیری", "نمیره", "نمیرن", "نمیرود",
|
||||
"نمیآید", "نمیاد",
|
||||
"نمیبینم", "نمیبینی", "نمیبیند",
|
||||
]);
|
||||
|
||||
// The imperative "ب" mis-heard as the real word "بی": "بی پوش" -> "بپوش".
|
||||
const POLISH_SPLIT_IMPERATIVES = {
|
||||
"پوش": "بپوش", "بین": "ببین", "بینم": "ببینم", "بینی": "ببینی",
|
||||
"بینید": "ببینید", "بینند": "ببینند", "خواب": "بخواب", "خور": "بخور",
|
||||
"شین": "بشین", "نشین": "بنشین", "گیر": "بگیر", "گو": "بگو",
|
||||
"گوی": "بگو", "بخش": "ببخش",
|
||||
};
|
||||
|
||||
// Separated ZWNJ prefixes/suffixes: "می کنم" -> "میکنم".
|
||||
const POLISH_FUSED_PREFIXES = {
|
||||
"می کنم": "میکنم", "می کنی": "میکنی", "می کند": "میکند",
|
||||
"می کنیم": "میکنیم", "می کنید": "میکنید", "می کنند": "میکنند",
|
||||
"می شود": "میشود", "می شن": "میشن", "می شه": "میشه",
|
||||
"می گویم": "میگویم", "می گوید": "میگوید", "می گم": "میگم",
|
||||
"می گی": "میگی", "می گه": "میگه", "می گن": "میگن",
|
||||
"می خواهم": "میخواهم", "می خواهد": "میخواهد",
|
||||
"می خوام": "میخوام", "می خواد": "میخواد",
|
||||
"می دانم": "میدانم", "می داند": "میداند",
|
||||
"می دونم": "میدونم", "می دم": "میدم", "می دی": "میدی",
|
||||
"می ده": "میده", "می دن": "میدن",
|
||||
"می برم": "میبرم", "می برد": "میبرد",
|
||||
"می رم": "میرم", "می ره": "میره", "می رن": "میرن",
|
||||
"می روم": "میروم", "می رود": "میرود",
|
||||
"می آید": "میآید", "می این": "میاین",
|
||||
"می شنوم": "میشنوم", "می شنوی": "میشنوی", "می شنود": "میشنود",
|
||||
"می بینم": "میبینم", "می بینی": "میبینی", "می بیند": "میبیند",
|
||||
"نمی کنم": "نمیکنم", "نمی کند": "نمیکند",
|
||||
"نمی شود": "نمیشود", "نمی شه": "نمیشه",
|
||||
"نمی گم": "نمیگم", "نمی گه": "نمیگه",
|
||||
"نمی خوام": "نمیخوام", "نمی خواد": "نمیخواد",
|
||||
"نمی دانم": "نمیدانم", "نمی دونم": "نمیدونم",
|
||||
"نمی رم": "نمیرم", "نمی ره": "نمیره", "نمی آید": "نمیآید",
|
||||
"نمی این": "نمیاین", "نمی بینم": "نمیبینم", "نمی بیند": "نمیبیند",
|
||||
};
|
||||
const POLISH_PREFIXES = new Set(["می", "نمی"]);
|
||||
const POLISH_SUFFIXES = new Set(["ها", "های", "هایی", "تر", "ترین"]);
|
||||
const POLISH_PUNCT_EDGES = "،؛:.!?؟…«»()\"'-–—,";
|
||||
const POLISH_CLOSING_PUNCT = "،؛:.!?؟…»)";
|
||||
|
||||
function polishSplitEdges(token) {
|
||||
// Mirror Python's str.strip(chars): peel edge punctuation both sides.
|
||||
let start = 0;
|
||||
let end = token.length;
|
||||
while (start < end && POLISH_PUNCT_EDGES.includes(token[start])) start++;
|
||||
while (end > start && POLISH_PUNCT_EDGES.includes(token[end - 1])) end--;
|
||||
return [token.slice(0, start), token.slice(start, end), token.slice(end)];
|
||||
}
|
||||
|
||||
function polishZwnjInWord(word) {
|
||||
if (word.startsWith("نمی") && word.length > 3) return "نمی" + _ZWNJ + word.slice(3);
|
||||
if (word.startsWith("می") && word.length > 2) return "می" + _ZWNJ + word.slice(2);
|
||||
return word;
|
||||
}
|
||||
|
||||
function polishFuse(tokens) {
|
||||
const out = [];
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const tok = tokens[i];
|
||||
const bare = tok.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("") || tok;
|
||||
const isClean = tok === bare;
|
||||
if (POLISH_PREFIXES.has(bare) && i + 1 < tokens.length && isClean) {
|
||||
const fused = POLISH_FUSED_PREFIXES[`${tok} ${tokens[i + 1]}`] ?? `${tok}${_ZWNJ}${tokens[i + 1]}`;
|
||||
out.push(fused);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (POLISH_SUFFIXES.has(bare) && out.length && isClean) {
|
||||
const prev = out[out.length - 1];
|
||||
const prevCore = prev.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("");
|
||||
if (prevCore && /[\u0600-\u06FF]/.test(prevCore[prevCore.length - 1])) {
|
||||
out[out.length - 1] = prev + _ZWNJ + bare;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(tok);
|
||||
}
|
||||
return out.join(" ");
|
||||
}
|
||||
|
||||
function polishTokens(text) {
|
||||
const tokens = text.split(/\s+/).filter(Boolean);
|
||||
const fixed = [];
|
||||
for (const token of tokens) {
|
||||
const [leading, core, trailing] = polishSplitEdges(token);
|
||||
if (!core) { fixed.push(token); continue; }
|
||||
const repaired = POLISH_ZWNJ_WORDS.has(core) ? polishZwnjInWord(core) : core;
|
||||
fixed.push(leading + repaired + trailing);
|
||||
}
|
||||
const fused = polishFuse(fixed).split(/\s+/);
|
||||
const repaired = [];
|
||||
for (const token of fused) {
|
||||
const core = polishSplitEdges(token)[1];
|
||||
const prev = repaired.length ? repaired[repaired.length - 1] : "";
|
||||
const prevCore = prev.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("");
|
||||
if (core && POLISH_SPLIT_IMPERATIVES[core] && (prevCore === "بی" || prevCore === "به")) {
|
||||
repaired[repaired.length - 1] = POLISH_SPLIT_IMPERATIVES[core];
|
||||
continue;
|
||||
}
|
||||
repaired.push(token);
|
||||
}
|
||||
return repaired.join(" ");
|
||||
}
|
||||
|
||||
function polishSpacing(text) {
|
||||
text = text.split(_ZWNJ + " ").join(_ZWNJ).split(" " + _ZWNJ).join(_ZWNJ);
|
||||
let out = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (POLISH_CLOSING_PUNCT.includes(ch) && out.endsWith(" ")) out = out.slice(0, -1);
|
||||
out += ch;
|
||||
const nxt = text[i + 1] || "";
|
||||
if (POLISH_CLOSING_PUNCT.includes(ch) && nxt && !POLISH_CLOSING_PUNCT.includes(nxt) && nxt !== " ") {
|
||||
const prevCh = out.length >= 2 ? out[out.length - 2] : "";
|
||||
const digitClass = /[0-9\u06F0-\u06F9]/;
|
||||
const isDecimal = ch === "." && digitClass.test(prevCh) && digitClass.test(nxt);
|
||||
if (!isDecimal) out += " ";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function polishTranscript(text) {
|
||||
if (!text || !text.trim()) return text;
|
||||
return polishSpacing(polishTokens(polishChars(text))).trim();
|
||||
}
|
||||
|
||||
function polishTranscriptParagraph(text) {
|
||||
return text.split("\n").map((line) => polishTranscript(line)).join("\n");
|
||||
}
|
||||
|
||||
// ---------- Persian punctuation restoration ----------
|
||||
// Same rule family as backend/sokhan/core/punctuation.py (the worker
|
||||
@@ -60,16 +261,45 @@ function restorePunctuationParagraph(text) {
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
const worker = new Worker("worker.js?v=3", { type: "module" });
|
||||
let busy = false;
|
||||
// ---------- small formatting helpers ----------
|
||||
|
||||
const FA_DIGITS = "۰۱۲۳۴۵۶۷۸۹";
|
||||
const faDigits = (s) => String(s).replace(/\d/g, (d) => FA_DIGITS[d]);
|
||||
|
||||
function mmss(t) {
|
||||
const s = Math.max(0, Math.floor(t));
|
||||
const m = Math.floor(s / 60);
|
||||
return `${faDigits(String(m).padStart(2, "0"))}:${faDigits(String(s % 60).padStart(2, "0"))}`;
|
||||
}
|
||||
|
||||
const DEVICE_LABELS = { webgpu: "WebGPU", wasm: "CPU (WASM)" };
|
||||
|
||||
// ---------- stage pills ----------
|
||||
|
||||
function setStage(n) {
|
||||
stageEls.forEach((el, i) => {
|
||||
el.classList.toggle("active", i + 1 === n);
|
||||
el.classList.toggle("done", n > i + 1);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- worker plumbing ----------
|
||||
|
||||
let worker = null;
|
||||
let busy = false;
|
||||
let runId = 0; // generation counter: any late async callback from a
|
||||
// cancelled/stale run is dropped instead of touching the UI
|
||||
let tickerHandle = null;
|
||||
let baseStatus = "";
|
||||
let lastAudioSeconds = 0;
|
||||
let lastResult = null; // { text, segments } for the timestamp toggle
|
||||
|
||||
const downloads = new Map(); // file -> { loaded, total }
|
||||
|
||||
worker.onmessage = (event) => {
|
||||
function onWorkerMessage(event) {
|
||||
const { type, payload } = event.data;
|
||||
if (type === "progress") {
|
||||
setStage(2);
|
||||
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);
|
||||
@@ -77,48 +307,146 @@ worker.onmessage = (event) => {
|
||||
const pct = Math.round((loaded / total) * 100);
|
||||
barEl.style.display = "block";
|
||||
barFill.style.width = `${pct}%`;
|
||||
statusEl.textContent = `در حال دانلود مدل … ${pct}%`;
|
||||
setBaseStatus(`در حال دانلود مدل … ${faDigits(pct)}٪`);
|
||||
}
|
||||
} else if (type === "device") {
|
||||
badgeEl.textContent = `روی ${DEVICE_LABELS[payload] || payload}`;
|
||||
badgeEl.style.display = "inline-block";
|
||||
} else if (type === "status" && payload === "ready") {
|
||||
setStage(3);
|
||||
barEl.style.display = "none";
|
||||
statusEl.textContent = "مدل آماده است — در حال پیادهسازی …";
|
||||
setBaseStatus("مدل آماده است — در حال پیادهسازی …");
|
||||
} else if (type === "status") {
|
||||
statusEl.textContent = payload;
|
||||
setBaseStatus(payload);
|
||||
} else if (type === "chunk-progress") {
|
||||
const { done, total, elapsed } = payload;
|
||||
const pct = Math.min(99, Math.round((done / Math.max(1, total)) * 100));
|
||||
barEl.style.display = "block";
|
||||
barFill.style.width = `${pct}%`;
|
||||
let eta = "";
|
||||
if (done >= 1 && done < total) {
|
||||
const per = elapsed / done;
|
||||
const remain = Math.round((total - done) * per);
|
||||
if (remain > 3) eta = ` — تخمین پایان: ~${faDigits(remain)} ثانیه`;
|
||||
}
|
||||
setBaseStatus(
|
||||
`در حال پیادهسازی — قطعهٔ ${faDigits(done)} از ${faDigits(total)} (${faDigits(pct)}٪)${eta}`
|
||||
);
|
||||
} else if (type === "result") {
|
||||
finish(payload.text, payload.elapsed);
|
||||
finish(payload);
|
||||
} else if (type === "error") {
|
||||
busy = false;
|
||||
unlock();
|
||||
barEl.style.display = "none";
|
||||
statusEl.textContent = "خطا: " + payload;
|
||||
fail("خطا: " + payload);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function wireWorker() {
|
||||
worker.onmessage = onWorkerMessage;
|
||||
worker.onerror = (e) => {
|
||||
console.error(e);
|
||||
if (busy) fail("خطای worker: " + (e.message || "نامشخص"));
|
||||
};
|
||||
}
|
||||
|
||||
function spawnWorker() {
|
||||
worker = new Worker("worker.js?v=4", { type: "module" });
|
||||
wireWorker();
|
||||
}
|
||||
|
||||
function setBaseStatus(text) {
|
||||
baseStatus = text;
|
||||
statusEl.textContent = text;
|
||||
}
|
||||
|
||||
function tick() {
|
||||
const startedAt = Number(statusEl.dataset.started || 0);
|
||||
if (!startedAt) return;
|
||||
const sec = Math.round((Date.now() - startedAt) / 1000);
|
||||
if (sec >= 5) statusEl.textContent = `${baseStatus} — ${faDigits(sec)} ثانیه گذشته`;
|
||||
}
|
||||
|
||||
function startTicker() {
|
||||
stopTicker();
|
||||
statusEl.dataset.started = String(Date.now());
|
||||
tickerHandle = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function stopTicker() {
|
||||
if (tickerHandle) clearInterval(tickerHandle);
|
||||
tickerHandle = null;
|
||||
delete statusEl.dataset.started;
|
||||
}
|
||||
|
||||
function setStatus(text) {
|
||||
// One-shot status (not part of the ticking base line).
|
||||
stopTicker();
|
||||
baseStatus = text;
|
||||
statusEl.textContent = text;
|
||||
}
|
||||
|
||||
function startWork(message) {
|
||||
// runId is owned by the entry points (sample/file/mic/cancel); startWork
|
||||
// must not bump it — transcribeRaw compares its own id after this call.
|
||||
busy = true;
|
||||
lock();
|
||||
downloads.clear();
|
||||
refEl.style.display = "none";
|
||||
badgeEl.style.display = "none";
|
||||
transcriptEl.textContent = "(در حال پردازش…)";
|
||||
metaEl.textContent = "";
|
||||
setStatus(message);
|
||||
copyBtn.style.display = "none";
|
||||
lastResult = null;
|
||||
barEl.style.display = "none";
|
||||
barFill.style.width = "0%";
|
||||
cancelBtn.style.display = "inline-block";
|
||||
setBaseStatus(message);
|
||||
startTicker();
|
||||
}
|
||||
|
||||
function finish(text, elapsedSeconds) {
|
||||
setStatus("تمام شد — میتوانید کلیپ دیگری امتحان کنید.");
|
||||
transcriptEl.textContent =
|
||||
restorePunctuationParagraph(text) || "(متنی تشخیص داده نشد — شاید صدا کوتاه یا نویزی بود.)";
|
||||
const audioSeconds = window.__lastAudioSeconds || 0;
|
||||
metaEl.textContent =
|
||||
`زمان پردازش: ${elapsedSeconds.toFixed(1)} ثانیه` +
|
||||
(audioSeconds ? ` برای ${audioSeconds.toFixed(1)} ثانیه صدا` : "") +
|
||||
" — کاملاً روی دستگاه شما.";
|
||||
function endRun() {
|
||||
busy = false;
|
||||
stopTicker();
|
||||
unlock();
|
||||
cancelBtn.style.display = "none";
|
||||
barEl.style.display = "none";
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
endRun();
|
||||
setStage(0);
|
||||
statusEl.textContent = message;
|
||||
transcriptEl.textContent = "(پردازش انجام نشد.)";
|
||||
}
|
||||
|
||||
function finish(payload) {
|
||||
lastResult = { text: payload.text || "", segments: payload.segments || [] };
|
||||
endRun();
|
||||
setStage(4);
|
||||
setStatus("تمام شد — میتوانید کلیپ دیگری امتحان کنید.");
|
||||
renderTranscript();
|
||||
const device = DEVICE_LABELS[payload.device] || payload.device || "";
|
||||
metaEl.textContent =
|
||||
`زمان پردازش: ${faDigits(payload.elapsed.toFixed(1))} ثانیه` +
|
||||
(lastAudioSeconds ? ` برای ${faDigits(lastAudioSeconds.toFixed(1))} ثانیه صدا` : "") +
|
||||
(payload.windows > 1 ? ` در ${faDigits(payload.windows)} قطعه` : "") +
|
||||
(device ? ` روی ${device}` : "") +
|
||||
" — کاملاً روی دستگاه شما.";
|
||||
copyBtn.style.display = "inline-block";
|
||||
}
|
||||
|
||||
function renderTranscript() {
|
||||
if (!lastResult) return;
|
||||
if (stampChk.checked && lastResult.segments.length) {
|
||||
const lines = lastResult.segments.map(
|
||||
(s) =>
|
||||
`[${mmss(s.start)}–${mmss(s.end)}] ` +
|
||||
restorePunctuation(polishTranscript(s.text))
|
||||
);
|
||||
transcriptEl.textContent = lines.join("\n");
|
||||
} else {
|
||||
transcriptEl.textContent =
|
||||
restorePunctuationParagraph(polishTranscriptParagraph(lastResult.text)) ||
|
||||
"(متنی تشخیص داده نشد — شاید صدا کوتاه یا نویزی بود.)";
|
||||
}
|
||||
}
|
||||
|
||||
function lock() {
|
||||
@@ -138,22 +466,44 @@ function unlock() {
|
||||
// ---------- audio -> 16 kHz mono Float32 ----------
|
||||
|
||||
async function decodeTo16k(arrayBuffer) {
|
||||
const ctx = new AudioContext({ sampleRate: 16000 });
|
||||
// Decode at the context's natural rate (never a forced 16 kHz context —
|
||||
// Chromium can hang forever on opus/webm there), then resample offline
|
||||
// to exactly 16 kHz mono. A watchdog turns a wedged decode into a
|
||||
// visible error instead of an eternal spinner.
|
||||
const decodeCtx = new AudioContext();
|
||||
let decoded;
|
||||
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 };
|
||||
decoded = await Promise.race([
|
||||
decodeCtx.decodeAudioData(arrayBuffer),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error("زمان زیادی برای رمزگشایی صدا گذشت")),
|
||||
DECODE_TIMEOUT_MS
|
||||
)
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
ctx.close();
|
||||
decodeCtx.close().catch(() => {});
|
||||
}
|
||||
const frames = Math.max(1, Math.ceil(decoded.duration * SAMPLE_RATE));
|
||||
const offline = new OfflineAudioContext(1, frames, SAMPLE_RATE);
|
||||
const source = offline.createBufferSource();
|
||||
source.buffer = decoded;
|
||||
source.connect(offline.destination);
|
||||
source.start();
|
||||
const rendered = await offline.startRendering();
|
||||
// slice(): detach from the OfflineAudioContext's internal buffer so the
|
||||
// Float32Array's own buffer is transferable to the worker.
|
||||
return { audio: rendered.getChannelData(0).slice(), seconds: decoded.duration };
|
||||
}
|
||||
|
||||
function tooLong(seconds) {
|
||||
return (
|
||||
`این صدا ${faDigits(Math.round(seconds / 60))} دقیقه است؛ دموی مرورگری برای ` +
|
||||
`کلیپهای تا ${faDigits(ABS_MAX_SECONDS / 60)} دقیقه طراحی شده (روی CPU سقف کمتر است). ` +
|
||||
"برای فایلهای بلندتر، نسخهٔ سلفهاست را اجرا کنید: " +
|
||||
"github.com/Abolfazlrwm/sokhan/tree/main/deploy"
|
||||
);
|
||||
}
|
||||
|
||||
async function transcribeArrayBuffer(arrayBuffer, sourceLabel) {
|
||||
@@ -164,22 +514,41 @@ async function transcribeArrayBuffer(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) {
|
||||
const id = ++runId;
|
||||
startWork(`در حال آمادهسازی صدا (${sourceLabel}) …`);
|
||||
setStage(1);
|
||||
try {
|
||||
const { audio, seconds } = await decodeTo16k(arrayBuffer);
|
||||
if (id !== runId) return; // cancelled while decoding
|
||||
if (seconds < 0.3) {
|
||||
busy = false;
|
||||
unlock();
|
||||
endRun();
|
||||
setStage(0);
|
||||
transcriptEl.textContent = "(صدا خیلی کوتاه است.)";
|
||||
setStatus("صدا خیلی کوتاه است — حداقل نیم ثانیه لازم است.");
|
||||
return;
|
||||
}
|
||||
window.__lastAudioSeconds = seconds;
|
||||
worker.postMessage({ kind: "transcribe", audio, modelId: modelSel.value });
|
||||
lastAudioSeconds = seconds;
|
||||
if (seconds > ABS_MAX_SECONDS) {
|
||||
endRun();
|
||||
setStage(0);
|
||||
transcriptEl.textContent = "(فایل بیش از حد بلند است.)";
|
||||
setStatus(tooLong(seconds));
|
||||
return;
|
||||
}
|
||||
setStage(3); // worker will drop back to stage 2 if the model needs downloading
|
||||
setBaseStatus("در حال آمادهسازی مدل …");
|
||||
// Transfer the buffer: the audio is not needed on this thread anymore.
|
||||
worker.postMessage(
|
||||
{ kind: "transcribe", audio, modelId: modelSel.value, seconds },
|
||||
[audio.buffer]
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
busy = false;
|
||||
unlock();
|
||||
setStatus("خطا در خواندن فایل صوتی: " + err.message);
|
||||
if (id !== runId) return;
|
||||
fail(
|
||||
"خطا در خواندن فایل صوتی: " + err.message +
|
||||
" — اگر فایل OGG است، سافاری از آن پشتیبانی نمیکند؛ Chrome یا فایل MP3/WAV را امتحان کنید."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,23 +556,31 @@ async function transcribeRaw(arrayBuffer, sourceLabel) {
|
||||
|
||||
sampleBtn.onclick = async () => {
|
||||
if (busy) return;
|
||||
const id = ++runId;
|
||||
busy = true;
|
||||
lock();
|
||||
downloads.clear();
|
||||
refEl.style.display = "none";
|
||||
badgeEl.style.display = "none";
|
||||
transcriptEl.textContent = "(در حال پردازش…)";
|
||||
metaEl.textContent = "";
|
||||
setStatus("در حال دریافت کلیپ نمونه (از فیکسچر بنچمارک پروژه) …");
|
||||
copyBtn.style.display = "none";
|
||||
cancelBtn.style.display = "inline-block";
|
||||
setStage(1);
|
||||
setBaseStatus("در حال دریافت کلیپ نمونه (از فیکسچر بنچمارک پروژه) …");
|
||||
startTicker();
|
||||
try {
|
||||
const res = await fetch(SAMPLE_URL);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
if (id !== runId) return;
|
||||
refEl.innerHTML = `<b>متن مرجع (انسان):</b> ${SAMPLE_REFERENCE}`;
|
||||
refEl.style.display = "block";
|
||||
await transcribeRaw(await res.arrayBuffer(), "نمونه");
|
||||
const ab = await res.arrayBuffer();
|
||||
busy = false; // transcribeRaw owns the guard from here (no await between this and startWork)
|
||||
await transcribeRaw(ab, "نمونه");
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
unlock();
|
||||
setStatus("دریافت نمونه ناموفق بود: " + err.message);
|
||||
if (id !== runId) return;
|
||||
fail("دریافت نمونه ناموفق بود: " + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -227,6 +604,10 @@ micBtn.onclick = async () => {
|
||||
micBtn.classList.remove("recording");
|
||||
const blob = new Blob(recordChunks, { type: recorder.mimeType });
|
||||
recorder = null;
|
||||
if (blob.size > FILE_CAP_MB * 1024 * 1024) {
|
||||
setStatus(`ضبط شما ${faDigits(Math.round(blob.size / 1048576))} مگابایت است؛ سقف دمو ${faDigits(FILE_CAP_MB)} مگابایت است.`);
|
||||
return;
|
||||
}
|
||||
await transcribeArrayBuffer(await blob.arrayBuffer(), "ضبط میکروفن");
|
||||
};
|
||||
recorder.start();
|
||||
@@ -241,6 +622,44 @@ micBtn.onclick = async () => {
|
||||
fileInput.onchange = async () => {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
if (!file) return;
|
||||
await transcribeArrayBuffer(await file.arrayBuffer(), "فایل");
|
||||
fileInput.value = "";
|
||||
if (file.size > FILE_CAP_MB * 1024 * 1024) {
|
||||
setStatus(
|
||||
`فایل ${faDigits(Math.round(file.size / 1048576))} مگابایت است؛ سقف دمو ` +
|
||||
`${faDigits(FILE_CAP_MB)} مگابایت است — کلیپ را کوتاهتر کنید.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
await transcribeArrayBuffer(await file.arrayBuffer(), "فایل");
|
||||
};
|
||||
|
||||
// ---------- cancel / copy / timestamp toggle ----------
|
||||
|
||||
cancelBtn.onclick = () => {
|
||||
runId += 1;
|
||||
worker.terminate();
|
||||
spawnWorker(); // fresh worker; model files stay in the browser cache
|
||||
busy = false;
|
||||
recorder = null;
|
||||
endRun();
|
||||
setStage(0);
|
||||
setStatus("لغو شد — مدل در حافظهٔ مرورگر مانده و اجرای بعدی سریع است.");
|
||||
transcriptEl.textContent = "(لغو شد.)";
|
||||
};
|
||||
|
||||
copyBtn.onclick = async () => {
|
||||
if (!lastResult) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(transcriptEl.textContent);
|
||||
copyBtn.textContent = "کپی شد";
|
||||
setTimeout(() => {
|
||||
copyBtn.textContent = "کپی متن";
|
||||
}, 1500);
|
||||
} catch (err) {
|
||||
setStatus("کپی ناموفق بود: " + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
stampChk.onchange = renderTranscript;
|
||||
|
||||
spawnWorker();
|
||||
+41
-6
@@ -48,6 +48,22 @@
|
||||
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; }
|
||||
.stages { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 4px; }
|
||||
.stages span { font-size: 0.78rem; color: var(--muted); border: 1px solid var(--line);
|
||||
border-radius: 99px; padding: 3px 10px; background: #fff; opacity: .55; }
|
||||
.stages span.active { opacity: 1; color: #fff; font-weight: 600; border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--accent), var(--accent-2)); }
|
||||
.stages span.done { opacity: .9; color: var(--ok); border-color: #a7f3d0; background: #ecfdf5; }
|
||||
.badge { display: inline-block; font-size: 0.75rem; border-radius: 99px; padding: 2px 9px;
|
||||
background: #eef2ff; color: var(--accent); font-weight: 600; }
|
||||
#cancel { display: none; border-color: var(--err); color: var(--err); font-size: 0.85rem;
|
||||
padding: 5px 12px; }
|
||||
#cancel:hover:not(:disabled) { background: var(--err); color: #fff; }
|
||||
.trow { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;
|
||||
gap: 8px; margin-bottom: 8px; }
|
||||
label.chk { font-size: 0.82rem; color: var(--muted); display: flex; gap: 6px; align-items: center;
|
||||
cursor: pointer; }
|
||||
button.mini { font-size: 0.82rem; padding: 5px 12px; }
|
||||
.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; }
|
||||
@@ -77,12 +93,18 @@
|
||||
<div class="privacy">🔒 حریم خصوصی کامل: صدا فقط در مرورگر شما پردازش میشود — به هیچ سروری ارسال نمیشود.</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="stages" id="stages">
|
||||
<span>۱ · آمادهسازی صدا</span>
|
||||
<span>۲ · دانلود مدل</span>
|
||||
<span>۳ · پیادهسازی</span>
|
||||
<span>۴ · پایان</span>
|
||||
</div>
|
||||
<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>
|
||||
<option value="Xenova/whisper-small" selected>کوچک (small) — دقیقتر، دانلود ~۲۵۰ مگابایت (پیشنهادی)</option>
|
||||
<option value="Xenova/whisper-base">پایه (base) — سریعتر، دانلود ~۷۵ مگابایت</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="flex:1"></div>
|
||||
@@ -96,18 +118,31 @@
|
||||
|
||||
<div id="status">برای شروع، «نمونهی آماده» را بزنید یا صدا ضبط/انتخاب کنید.</div>
|
||||
<div class="bar" id="bar"><div></div></div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<span class="badge" id="badge" style="display:none"></span>
|
||||
<div style="flex:1"></div>
|
||||
<button id="cancel">لغو پردازش</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label class="field">متن پیادهشده</label>
|
||||
<div class="trow">
|
||||
<label class="field">متن پیادهشده</label>
|
||||
<div class="row" style="gap:10px">
|
||||
<label class="chk"><input type="checkbox" id="stamp"> خطبهخط با زمان</label>
|
||||
<button class="mini" id="copy" style="display:none">کپی متن</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="transcript" dir="rtl">(اینجا نوشته میشود…)</div>
|
||||
<div id="meta"></div>
|
||||
<div id="ref"></div>
|
||||
</div>
|
||||
|
||||
<p class="note">
|
||||
صادقانه: این دمو چکپوینتهای <b>پایهی</b> Whisper را در مرورگر اجرا میکند
|
||||
(Common Voice فارسی محاورهای و پرنویز است؛ انتظار خطا داشته باشید).
|
||||
صادقانه: دقت Whisper روی Common Voice فارسی (محاورهای و پرنویز) محدود است.
|
||||
متن خروجی با پولیش ارتوگرافی فارسی (نیمفاصله، حروف عربی، فعلهای شکسته) تمیز میشود —
|
||||
همان پستپروسس نسخهٔ سرور.
|
||||
در Chrome و Edge با WebGPU خیلی سریعتر است؛ سایر مرورگرها روی WASM با سقف مدت اجرا میکنند.
|
||||
چکپوینت ریزتنظیمشدهی 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>
|
||||
@@ -122,6 +157,6 @@
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script type="module" src="demo.js?v=2"></script>
|
||||
<script type="module" src="demo.js?v=4"></script>
|
||||
</body>
|
||||
</html>
|
||||
+185
-31
@@ -1,25 +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.
|
||||
// thread and reports per-window progress so a long clip always feels
|
||||
// alive instead of sitting at an eternal "processing" state.
|
||||
// Nothing about this app calls a server: the model and the audio both
|
||||
// live on the visitor's machine.
|
||||
//
|
||||
// Speed model:
|
||||
// - WebGPU (Chrome/Edge with a working GPU adapter): fp32 encoder and
|
||||
// q4 decoder on the GPU — the fast path, several times faster than WASM.
|
||||
// - WASM SIMD fallback (Firefox / Safari / no adapter): q8 everywhere.
|
||||
// Correct but single-threaded, so durations are capped and progress is
|
||||
// reported per 30-second window with an ETA.
|
||||
//
|
||||
// Chunking is done here (30 s windows, 5 s overlap, timestamp-midpoint
|
||||
// trimming) instead of relying on the pipeline's chunk_length_s, because
|
||||
// transformers.js 3.8.1 exposes no per-chunk callback — and owning the
|
||||
// loop is what makes real progress reporting and clean caps possible.
|
||||
// Segments whose midpoint falls in the non-overlapping core of each
|
||||
// window are kept, which removes seam duplication without the token-level
|
||||
// LCS merge the pipeline does internally.
|
||||
|
||||
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;
|
||||
|
||||
const SAMPLE_RATE = 16000;
|
||||
const WINDOW_SECONDS = 30; // whisper's native window
|
||||
const STRIDE_SECONDS = 5; // overlap on each side of a window
|
||||
const WINDOW = WINDOW_SECONDS * SAMPLE_RATE;
|
||||
const JUMP = WINDOW - 2 * STRIDE_SECONDS * SAMPLE_RATE; // 20 s of new audio per window
|
||||
const MAX_SECONDS = { webgpu: 1800, wasm: 600 };
|
||||
|
||||
let asr = null;
|
||||
let currentModelId = null;
|
||||
let currentDevice = null;
|
||||
|
||||
async function loadModel(modelId) {
|
||||
if (asr && currentModelId === modelId) return;
|
||||
currentModelId = null;
|
||||
asr = null;
|
||||
post("status", `در حال دانلود مدل ${modelId} …`);
|
||||
function post(type, payload) {
|
||||
self.postMessage({ type, payload });
|
||||
}
|
||||
|
||||
async function gpuAvailable() {
|
||||
try {
|
||||
if (!self.navigator || !self.navigator.gpu) return false;
|
||||
const adapter = await self.navigator.gpu.requestAdapter();
|
||||
return !!adapter;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModel(modelId, device) {
|
||||
post("status", `در حال دانلود مدل ${modelId} (${device === "webgpu" ? "WebGPU" : "CPU"}) …`);
|
||||
const config =
|
||||
device === "webgpu"
|
||||
? { device: "webgpu", dtype: { encoder_model: "fp32", decoder_model_merged: "q4" } }
|
||||
: { device: "wasm", dtype: { encoder_model: "q8", decoder_model_merged: "q8" } };
|
||||
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" },
|
||||
...config,
|
||||
progress_callback: (p) => {
|
||||
if (p.status === "progress" && p.total) {
|
||||
post("progress", { file: p.file, loaded: p.loaded, total: p.total });
|
||||
@@ -27,38 +65,154 @@ async function loadModel(modelId) {
|
||||
},
|
||||
});
|
||||
currentModelId = modelId;
|
||||
currentDevice = device;
|
||||
post("device", device);
|
||||
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 });
|
||||
/** Load the requested model on the fastest device this browser supports. */
|
||||
async function loadBest(modelId) {
|
||||
if (asr && currentModelId === modelId) return;
|
||||
asr = null;
|
||||
currentModelId = null;
|
||||
currentDevice = null;
|
||||
if (await gpuAvailable()) {
|
||||
try {
|
||||
await loadModel(modelId, "webgpu");
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error("WebGPU load failed; falling back to WASM", err);
|
||||
post("status", "WebGPU در دسترس نبود — بازگشت به حالت CPU …");
|
||||
asr = null;
|
||||
}
|
||||
}
|
||||
await loadModel(modelId, "wasm");
|
||||
}
|
||||
|
||||
function post(type, payload) {
|
||||
self.postMessage({ type, payload });
|
||||
function countWindows(seconds) {
|
||||
if (!(seconds > 0)) seconds = 1;
|
||||
if (seconds <= WINDOW_SECONDS) return 1;
|
||||
return 1 + Math.ceil((seconds - WINDOW_SECONDS) / (JUMP / SAMPLE_RATE));
|
||||
}
|
||||
|
||||
/**
|
||||
* One 30-second window -> trimmed segments with GLOBAL timestamps.
|
||||
* The window is transcribed with return_timestamps; segments whose
|
||||
* midpoint lies inside the window's non-overlapping core are kept, so
|
||||
* consecutive windows never duplicate the phrase spoken across a seam.
|
||||
*/
|
||||
async function transcribeWindow(samples, offsetSeconds, isFirst, isLast) {
|
||||
const out = await asr(samples, {
|
||||
language: "fa",
|
||||
task: "transcribe",
|
||||
return_timestamps: true,
|
||||
});
|
||||
const windowStart = offsetSeconds;
|
||||
const coreStart = windowStart + (isFirst ? 0 : STRIDE_SECONDS);
|
||||
const coreEnd =
|
||||
windowStart + samples.length / SAMPLE_RATE - (isLast ? 0 : STRIDE_SECONDS);
|
||||
const segments = [];
|
||||
for (const s of out.chunks || []) {
|
||||
const t0 = Array.isArray(s.timestamp) ? s.timestamp[0] ?? 0 : 0;
|
||||
const t1 = Array.isArray(s.timestamp) ? s.timestamp[1] ?? t0 : t0;
|
||||
const start = windowStart + t0;
|
||||
const end = windowStart + t1;
|
||||
const mid = (start + end) / 2;
|
||||
if (mid < coreStart || mid > coreEnd) continue;
|
||||
const text = (s.text || "").trim();
|
||||
if (!text) continue;
|
||||
segments.push({ start, end, text });
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
async function transcribe(audio, modelId, seconds) {
|
||||
await loadBest(modelId);
|
||||
|
||||
if (!seconds || seconds <= 0) seconds = audio.length / SAMPLE_RATE;
|
||||
const cap = MAX_SECONDS[currentDevice] ?? MAX_SECONDS.wasm;
|
||||
if (seconds > cap) {
|
||||
post(
|
||||
"error",
|
||||
`این فایل ${Math.round(seconds / 60)} دقیقه است؛ سقف دموی مرورگری روی ` +
|
||||
`${currentDevice === "webgpu" ? "WebGPU" : "CPU"} حدود ${Math.round(cap / 60)} دقیقه است. ` +
|
||||
"برای فایلهای بلندتر، نسخهٔ سلفهاست (backend) را اجرا کنید."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
post("status", "در حال پیادهسازی …");
|
||||
const total = countWindows(seconds);
|
||||
const started = performance.now();
|
||||
const segments = [];
|
||||
let offset = 0;
|
||||
let done = 0;
|
||||
let retriedOnWasm = false;
|
||||
|
||||
while (true) {
|
||||
const offsetEnd = offset + WINDOW;
|
||||
const sub = audio.subarray(offset, Math.min(offsetEnd, audio.length));
|
||||
const isFirst = offset === 0;
|
||||
const isLast = offsetEnd >= audio.length;
|
||||
let windowSegments;
|
||||
try {
|
||||
windowSegments = await transcribeWindow(
|
||||
sub,
|
||||
offset / SAMPLE_RATE,
|
||||
isFirst,
|
||||
isLast
|
||||
);
|
||||
} catch (err) {
|
||||
if (currentDevice === "webgpu" && !retriedOnWasm) {
|
||||
// Driver hiccup on the GPU path: reload once on CPU and redo the
|
||||
// current window; earlier windows stay valid.
|
||||
console.error("WebGPU inference failed; retrying on WASM", err);
|
||||
asr = null;
|
||||
currentModelId = null;
|
||||
await loadModel(modelId, "wasm");
|
||||
retriedOnWasm = true;
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
segments.push(...windowSegments);
|
||||
done += 1;
|
||||
const elapsed = (performance.now() - started) / 1000;
|
||||
post("chunk-progress", { done, total, elapsed });
|
||||
if (isLast) break;
|
||||
offset += JUMP;
|
||||
}
|
||||
|
||||
segments.sort((a, b) => a.start - b.start);
|
||||
const text = segments
|
||||
.map((s) => s.text)
|
||||
.join(" ")
|
||||
.replace(/\s{2,}/g, " ")
|
||||
.trim();
|
||||
const elapsed = (performance.now() - started) / 1000;
|
||||
post("result", {
|
||||
text,
|
||||
segments,
|
||||
elapsed,
|
||||
device: currentDevice,
|
||||
windows: done,
|
||||
});
|
||||
}
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
// Dedicated worker: only accept commands from the page that created us.
|
||||
// Belt-and-braces same-origin guard — the demo page and this script are
|
||||
// always served from the same origin, so anything else is not ours.
|
||||
if (event.origin !== self.location.origin) return;
|
||||
const { kind, modelId, audio } = event.data;
|
||||
// Defence-in-depth origin check. A dedicated worker can only ever be
|
||||
// messaged by the page that created it (the browser enforces this), and
|
||||
// Chromium 158+ posts such messages with an EMPTY event.origin — a
|
||||
// strict `event.origin !== self.location.origin` comparison therefore
|
||||
// swallowed every command and left the demo hanging at "processing"
|
||||
// forever. Reject only origins that are present AND foreign.
|
||||
if (event.origin && event.origin !== self.location.origin) return;
|
||||
const { kind, modelId, audio, seconds } = event.data;
|
||||
try {
|
||||
if (kind === "load") {
|
||||
await loadModel(modelId);
|
||||
await loadBest(modelId);
|
||||
} else if (kind === "transcribe") {
|
||||
await transcribe(audio, modelId);
|
||||
await transcribe(audio, modelId, seconds);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
+16
-5
@@ -122,11 +122,22 @@ current ML stack surfaced and are fixed:
|
||||
|
||||
- The GPU-scale run exists (2026-11-18, free Colab T4): `whisper-small` +
|
||||
LoRA on 500 clips / ≈45 minutes of speech, 3 epochs in ~7 minutes —
|
||||
fixture WER 80.5% → 79.3% (see the fine-tune row in
|
||||
`benchmarks/README.md`). Real, but small; the same notebook at
|
||||
`MAX_SAMPLES = 0` (the full 10-hour manifest, ~1.5–2 h on a T4) is the
|
||||
next run, ideally paired with a larger speaker-disjoint hold-out than
|
||||
the default 2% eval split.
|
||||
under the v1 harness that was fixture WER 80.5% → 79.3%; re-measured
|
||||
under the v2 harness (orthography prompt + polish, see
|
||||
`benchmarks/README.md`) it lands at 75.0%. Real, but small; the same
|
||||
notebook at `MAX_SAMPLES = 0` (the full 10-hour manifest, ~1.5–2 h on a
|
||||
T4) is the next run, ideally paired with a larger speaker-disjoint
|
||||
hold-out than the default 2% eval split.
|
||||
- **Next-level run (recommended): LoRA on `whisper-medium`.** The measured
|
||||
untuned gap (small 75.0% vs medium 56.2% WER under v2) shows the base
|
||||
model is the bottleneck, not the adapter size. The same notebook with
|
||||
`MODEL_NAME = "openai/whisper-medium"` fits a free T4 (~1.5 GB LoRA
|
||||
state in int8 bf16); even 2–3 hours of Persian speech there should
|
||||
undercut every `small`-class number by a wide margin.
|
||||
- To put the fine-tuned engine **inside the browser demo**, run
|
||||
[export_web_onnx.py](export_web_onnx.py) (merge → ONNX → int8 → Hub) on
|
||||
Colab and add the resulting repo id to `space/index.html`. No new demo
|
||||
code is needed — the worker loads any Xenova-style whisper repo.
|
||||
- The default eval split (2%) is small; a proper report should freeze a
|
||||
larger, speaker-disjoint hold-out.
|
||||
- Data augmentation (noise, speed perturbation) is a known next step for
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export a fine-tuned Sokhan whisper checkpoint to a transformers.js web model.
|
||||
|
||||
Bridges the training world (PEFT LoRA adapter, PyTorch) and the browser
|
||||
demo (transformers.js ONNX). Run this on a machine with the model files —
|
||||
a free Colab T4 is enough — then wire the resulting HF repo id into
|
||||
space/index.html as a new <option> (Xenova-format ONNX is loaded by the
|
||||
same worker code path).
|
||||
|
||||
What it does:
|
||||
|
||||
1. loads the base whisper checkpoint and the Sokhan LoRA adapter,
|
||||
2. merges the adapter (`merge_and_unload`) and saves a plain transformers
|
||||
model + tokenizer + feature extractor,
|
||||
3. exports the merged model to ONNX the way transformers.js expects
|
||||
(encoder + decoder-merged, no monolith),
|
||||
4. quantizes to int8/q4 files for the browser dtypes,
|
||||
5. uploads the finished model repo to the Hugging Face Hub.
|
||||
|
||||
Usage (Colab / any machine with ~4 GB RAM):
|
||||
|
||||
pip install transformers peft torch optimum onnxruntime "av<14" \
|
||||
"huggingface_hub>=0.26" onnx
|
||||
python training/export_web_onnx.py \
|
||||
--base openai/whisper-small \
|
||||
--adapter Abol0pati/whisper-small-fa-sokhan \
|
||||
--repo Abol0pati/whisper-small-fa-sokhan-web \
|
||||
--push
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def merge_lora(base: str, adapter: str, out_dir: Path) -> None:
|
||||
from peft import PeftModel
|
||||
from transformers import AutoFeatureExtractor, AutoModelForSpeechSeq2Seq, AutoTokenizer
|
||||
|
||||
print(f"[1/4] loading base {base} and adapter {adapter}")
|
||||
model = AutoModelForSpeechSeq2Seq.from_pretrained(base)
|
||||
model = PeftModel.from_pretrained(model, adapter)
|
||||
merged = model.merge_and_unload()
|
||||
print("[2/4] saving merged transformers checkpoint")
|
||||
merged.save_pretrained(out_dir)
|
||||
AutoTokenizer.from_pretrained(base).save_pretrained(out_dir)
|
||||
AutoFeatureExtractor.from_pretrained(base).save_pretrained(out_dir)
|
||||
# generation config must carry forced decoder ids the demo relies on
|
||||
if hasattr(merged, "generation_config"):
|
||||
merged.generation_config.save_pretrained(out_dir)
|
||||
|
||||
|
||||
def export_onnx(model_dir: Path, onnx_dir: Path) -> None:
|
||||
print("[3/4] exporting ONNX (encoder + decoder-merged)")
|
||||
subprocess.run(
|
||||
[
|
||||
"optimum-cli", "export", "onnx",
|
||||
"--model", str(model_dir),
|
||||
"--task", "automatic-speech-recognition",
|
||||
"--monolith", "false",
|
||||
"--device", "cpu",
|
||||
str(onnx_dir),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
# int8 quantization for the wasm/q8 dtype path
|
||||
from onnxruntime.quantization import QuantType, quantize_dynamic
|
||||
|
||||
for onnx_file in list(onnx_dir.rglob("*.onnx")):
|
||||
if "_quantized" in onnx_file.stem or "_q4" in onnx_file.stem:
|
||||
continue
|
||||
quantize_dynamic(
|
||||
str(onnx_file),
|
||||
str(onnx_file.with_name(onnx_file.stem + "_quantized.onnx")),
|
||||
weight_type=QuantType.QInt8,
|
||||
)
|
||||
# tokenizer/processing configs ride along for transformers.js
|
||||
for name in (
|
||||
"config.json", "generation_config.json", "preprocessor_config.json",
|
||||
"tokenizer_config.json", "tokenizer.json", "special_tokens_map.json",
|
||||
):
|
||||
src = model_dir / name
|
||||
if src.exists():
|
||||
shutil.copy(src, onnx_dir / name)
|
||||
(onnx_dir / "onnx").mkdir(exist_ok=True)
|
||||
for onnx_file in list(onnx_dir.glob("*.onnx")):
|
||||
shutil.move(str(onnx_file), onnx_dir / "onnx" / onnx_file.name)
|
||||
|
||||
|
||||
def push(repo: str, onnx_dir: Path) -> None:
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
print(f"[4/4] uploading to {repo}")
|
||||
api = HfApi(token=None) # token comes from HF_TOKEN env / cached login
|
||||
api.create_repo(repo, repo_type="model", exist_ok=True)
|
||||
api.upload_folder(folder_path=str(onnx_dir), repo_id=repo, repo_type="model")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--base", default="openai/whisper-small")
|
||||
ap.add_argument("--adapter", default="Abol0pati/whisper-small-fa-sokhan")
|
||||
ap.add_argument("--repo", default="Abol0pati/whisper-small-fa-sokhan-web")
|
||||
ap.add_argument("--push", action="store_true", help="upload the finished repo to the Hub")
|
||||
args = ap.parse_args()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="sokhan-web-export-") as tmp:
|
||||
root = Path(tmp)
|
||||
merged_dir = root / "merged"
|
||||
onnx_dir = root / "onnx"
|
||||
merge_lora(args.base, args.adapter, merged_dir)
|
||||
export_onnx(merged_dir, onnx_dir)
|
||||
if args.push:
|
||||
push(args.repo, onnx_dir)
|
||||
else:
|
||||
keep = Path("sokhan-web-model")
|
||||
if keep.exists():
|
||||
shutil.rmtree(keep)
|
||||
shutil.copytree(onnx_dir, keep)
|
||||
print(f"kept local copy at ./{keep}")
|
||||
print("done — add the repo id as a new <option> in space/index.html")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+14
-8
@@ -55,20 +55,26 @@ 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 |
|
||||
| model | WER (v1 harness) | WER (v2 harness: orthography prompt + polish) |
|
||||
| --- | --- | --- |
|
||||
| openai whisper-small (baseline) | 80.5% | 26.7% |
|
||||
| **whisper-small-fa-sokhan** | **79.3%** | **24.9%** |
|
||||
| openai whisper-small (baseline) | 80.5% | 75.0% |
|
||||
| **whisper-small-fa-sokhan** | **79.3%** | **75.0%** |
|
||||
| openai whisper-medium (untuned, for scale) | — | 56.2% |
|
||||
|
||||
In-training held-out eval (10 clips): WER 85.1% → 81.6%; training loss
|
||||
3.63 → 1.75.
|
||||
3.63 → 1.75. With a Persian orthography initial prompt alone (no polish),
|
||||
this checkpoint measures 72.0% vs 76.8% without — the prompt is worth
|
||||
−4.8 WER points on this model, more than the LoRA itself contributed.
|
||||
|
||||
**Honest caveats.** A 12-clip fixture puts the -1.2 WER margin near the
|
||||
**Honest caveats.** A 12-clip fixture puts the small margins 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.
|
||||
(`MAX_SAMPLES=0`, ~2 h on a free T4) — and the measured untuned
|
||||
small-vs-medium gap (75.0% vs 56.2%) says the next fine-tune should
|
||||
target `whisper-medium`, not more data on `small`. 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
|
||||
|
||||
|
||||
Reference in new issue
Block a user