Author SHA1 Message Date
ahp 103f72f41e fix(security): throttle failed logins per client address and email
POST /auth/login accepted unlimited password guesses.

- FailureThrottle: thread-safe sliding window kept in process (the
  compose stack runs a single uvicorn process)
- keyed by (client address, email): an attacker cannot lock a victim
  out from everywhere, and users behind one NAT are not punished for
  each other's typos
- after LOGIN_MAX_FAILURES (10) failures within
  LOGIN_FAILURE_WINDOW_SECONDS (900) the endpoint answers 429 with
  Retry-After; a successful login clears the count; 0 disables it
2026-11-26 16:25:34 +03:30
ahp ee42254ab1 fix(security)!: keep webhook callbacks off internal addresses
callback_url only had to start with http(s)://, so any user could make
the worker POST to loopback, the compose network (postgres, redis),
link-local cloud metadata or the LAN.

- upload time: literal private, loopback and link-local hosts and
  localhost are rejected with 422 (no DNS lookup on the request path)
- delivery time: a guarded create_connection resolves once, refuses
  the host if any address is non-public and connects to the vetted
  address itself, so DNS rebinding cannot swap in a private IP after
  the check
- redirects are not followed and *_PROXY env vars are ignored for
  callbacks
- WEBHOOK_ALLOW_PRIVATE_TARGETS=true restores the old behaviour for
  trusted single-tenant installs (e.g. n8n on the LAN)

BREAKING CHANGE: callbacks to private addresses now need
WEBHOOK_ALLOW_PRIVATE_TARGETS=true.
2026-11-26 16:25:34 +03:30
ahp 9d15525500 fix(security): cap request bodies before uploads reach disk or memory
The MAX_UPLOAD_MB check in POST /jobs and /v1/audio/transcriptions ran
after file.file.read(): Starlette had already spooled the whole
multipart body to a temp file and the handler then loaded it into RAM,
so one multi-gigabyte upload from any registered user could exhaust the
API container.

- BodySizeLimitMiddleware answers 413 up front from Content-Length, or
  mid-stream by counting bytes for chunked bodies (FastAPI re-raises
  the HTTPException from body parsing)
- the cap is MAX_UPLOAD_MB plus 1 MiB of multipart framing; registered
  before CORS so browsers can read the 413
- measured on the compose stack: a 250 MB chunked upload is cut off
  with 413 while the API stays at ~89 MB RSS and /tmp stays empty
2026-11-26 16:25:34 +03:30
ahp c902ab4469 fix(security)!: require a bot shared secret on POST /auth/telegram
The endpoint minted a fresh API token for whatever telegram_id the
caller sent. Telegram ids are not secret (anyone sharing a group sees
them), so any client that could reach the API could log in as any
Telegram user: read and delete their transcripts, spend their quota and
rotate their token out from under the bot.

- new BOT_API_SECRET; require_bot checks X-Bot-Secret with
  compare_digest, mirroring require_admin: 403 on a wrong or missing
  secret, 503 while unset
- the bot sends the header and refuses to start without the secret
- tests: rejected without / with a wrong secret, disabled while unset,
  bot client sends the header

BREAKING CHANGE: deployments running the bot must set the same
BOT_API_SECRET on the API and the bot.
2026-11-26 16:25:34 +03:30
Abolfazl Ranjbaran 4821d812dc feat(accuracy): Persian accuracy stack v2 — measured -24.3 WER points on the default stack
Every decision below is measured on the 12-clip Common Voice fa fixture
with a reproducible harness; no number is hand-written.

- fa_polish module: orthographic-only repair (ZWNJ fusion, split
  imperatives like 'بی پوش' -> 'بپوش', Arabic code points, digits).
  Wired into the pipeline (FA_POLISH=true) and ported 1:1 to the browser
  demo (16-case parity test vs Python). -3.6 WER points.
- Persian orthography initial_prompt as the default: whisper copies the
  prompt's script style. -1.3 points (small), -4.8 (fine-tuned).
- Default engine small -> medium: 56.2% WER vs 75.0% (v2 harness) at
  ~1.1x realtime on 2 CPU cores. small stays the speed-first profile.
- Browser demo: default model base -> small (90.2% -> 75.0% under v2),
  polished output identical to the server's shape.
- benchmarks/tune_decode.py: the sweep harness behind every decision
  (prompt x beam x VAD x condition_on_previous_text).
- training/export_web_onnx.py: LoRA merge -> ONNX -> int8 -> HF Hub so
  the next fine-tune can run inside the browser demo.
- baseline.json regenerated for the v2 harness; weekly benchmark now
  guards small AND medium; gate test updated.

Fixture: small 80.5% -> 75.0%, fine-tuned 79.3% -> 75.0%, medium 56.2%.
2026-11-26 09:44:41 +00:00
Abolfazl Ranjbaran 601fed0766 fix(demo): never hang again — real speed, progress and cancel for the browser Space
Root causes of the eternal 'processing' state:
- worker dropped every command: Chromium 158+ posts dedicated-worker
  messages with an EMPTY event.origin, so the strict origin guard
  rejected them all; now only foreign origins are rejected
- decodeAudioData inside a forced 16 kHz AudioContext can wedge on
  opus/webm in Chromium; decode now runs at the natural rate and is
  resampled offline to 16 kHz with a 45 s watchdog

Speed:
- WebGPU fast path (fp32 encoder + q4 decoder) with automatic WASM/q8
  fallback and a one-time mid-run GPU->CPU retry on driver errors
- windowing moved into the worker (30 s window / 5 s overlap,
  timestamp-midpoint trim) enabling true per-window progress

UX:
- per-window progress + ETA + elapsed timer + stage pills + device badge
- cancel button that terminates the worker (model stays in cache)
- timestamped line-by-line transcript toggle + copy button
- hard caps: 30 min WebGPU / 10 min WASM / 60 MB per file, with clear
  Persian messages — no input can wedge the demo anymore
2026-11-26 08:57:39 +00:00
39 changed files with 2250 additions and 660 deletions

No files matched your search

+24 -4
View File
@@ -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.
@@ -95,6 +106,9 @@ LLM_MODEL=
# --- Telegram bot (optional) ---
TELEGRAM_BOT_TOKEN=
# Shared secret between the bot and the API; set the same value on both.
BOT_API_SECRET=
# URL the bot puts in messages so users can open their archive in the browser.
WEB_BASE_URL=http://localhost:3000
@@ -118,6 +132,12 @@ WEBHOOK_SIGNING_SECRET=
# best-effort and never flips the job status).
WEBHOOK_TIMEOUT_SECONDS=4.0
WEBHOOK_ATTEMPTS=2
# Allow callbacks to private/loopback addresses (trusted installs only).
WEBHOOK_ALLOW_PRIVATE_TARGETS=false
# --- Login brute-force guard ---
LOGIN_MAX_FAILURES=10
LOGIN_FAILURE_WINDOW_SECONDS=900
# --- Deployment (deploy/docker-compose.yml) ---
# Required: the compose file refuses to start without a real password.
+1 -1
View File
@@ -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
+75
View File
@@ -5,16 +5,91 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### Security
- **`POST /auth/telegram` could be used to take over any Telegram user's
account.** It minted a fresh API token for whatever `telegram_id` the
caller sent, with no proof the caller was the bot. It now requires the
`X-Bot-Secret` header to match the new `BOT_API_SECRET` (constant-time
compare; 403 on mismatch, 503 while unset). **Breaking for deployments
with the bot:** set the same `BOT_API_SECRET` on the API and the bot; the
bot refuses to start without it.
- Request bodies above `MAX_UPLOAD_MB` (plus 1 MiB multipart allowance) are
now refused with 413 by a middleware, up front from `Content-Length` or
mid-stream for chunked uploads. Before, the size check ran only after the
whole body had been spooled to disk and read into memory, so one
multi-gigabyte upload could exhaust the API container's disk or RAM.
- Webhook `callback_url`s can no longer target internal addresses. Any
user could point the worker at loopback, private, link-local (cloud
metadata) or LAN hosts. Literal private hosts are now rejected at upload
(422), every resolved address is checked again at connect time (defeating
DNS rebinding), redirects are not followed and proxy env vars are ignored.
**Breaking for receivers on private addresses:** set
`WEBHOOK_ALLOW_PRIVATE_TARGETS=true` on trusted single-tenant installs.
- `POST /auth/login` is throttled: after `LOGIN_MAX_FAILURES` (10) failures
per client address and email within `LOGIN_FAILURE_WINDOW_SECONDS` (900)
it answers 429 with `Retry-After`; a successful login clears the count.
### 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
+14 -8
View File
@@ -225,9 +225,12 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `LOW_CONFIDENCE_THRESHOLD` | `0.5` | اطمینان سگمنت زیرِ این مقدار پرچم بازبینی می‌گیرد |
| `STREAMING_DECODE` | `true` | خواندن بلاک‌به‌بلاک صدا (حافظهٔ اوج ∝ پنجره، نه طول فایل) |
| `WEBHOOK_SIGNING_SECRET` | خالی | رمز HMAC برای کال‌بک‌های پایان کار (`X-Sokhan-Signature`)؛ خالی یعنی بدون امضا |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | اجازهٔ کال‌بک به نشانی‌های خصوصی/لوکال (فقط برای نصب تک‌کاربرهٔ مورد اعتماد) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | تعداد ورود ناموفق برای هر نشانی و ایمیل پیش از `429`؛ `0` یعنی غیرفعال |
| `SUMMARY_ENABLED` | `false` | فلگ امکان خلاصه‌سازی با LLM |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | خالی | endpoint سازگار با OpenAI |
| `TELEGRAM_BOT_TOKEN` | خالی | فعال‌سازی فرایند ربات |
| `BOT_API_SECRET` | خالی | رمز مشترکی که ربات به `POST /auth/telegram` می‌فرستد؛ روی API و ربات یک مقدار بگذارید، خالی یعنی ورود تلگرامی غیرفعال |
| `WEB_BASE_URL` | `http://localhost:3000` | لینک‌هایی که ربات می‌فرستد |
| `API_BASE_URL` | `http://localhost:8000` | آدرس API که ربات صدا می‌زند |
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | آدرس API که اپ وب صدا می‌زند (زمان build) |
@@ -288,14 +291,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`
یک هیوریستیک است: برچسب‌هایش شباهت صوتی را توصیف می‌کنند نه هویتِ تأییدشده
+15 -8
View File
@@ -224,9 +224,12 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
| `LOW_CONFIDENCE_THRESHOLD` | `0.5` | segment confidence below which review flags apply |
| `STREAMING_DECODE` | `true` | decode audio block-by-block (peak RAM ∝ window, not file length) |
| `WEBHOOK_SIGNING_SECRET` | empty | HMAC secret for job-completion callbacks (`X-Sokhan-Signature`); empty sends them unsigned |
| `WEBHOOK_ALLOW_PRIVATE_TARGETS` | `false` | allow callbacks to private/loopback addresses (trusted single-tenant installs only) |
| `LOGIN_MAX_FAILURES` / `LOGIN_FAILURE_WINDOW_SECONDS` | `10` / `900` | failed logins per client address and email before `429`; `0` disables |
| `SUMMARY_ENABLED` | `false` | LLM summaries feature flag |
| `LLM_API_BASE` / `LLM_API_KEY` / `LLM_MODEL` | empty | OpenAI-compatible endpoint |
| `TELEGRAM_BOT_TOKEN` | empty | enables the bot process |
| `BOT_API_SECRET` | empty | shared secret the bot sends to `POST /auth/telegram`; set the same value on the API and the bot, empty disables Telegram login |
| `WEB_BASE_URL` | `http://localhost:3000` | links the bot sends |
| `API_BASE_URL` | `http://localhost:8000` | API address the bot calls |
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | API address the web app calls (build-time) |
@@ -287,14 +290,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,
+40
View File
@@ -0,0 +1,40 @@
from fastapi import HTTPException
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send
MULTIPART_OVERHEAD_BYTES = 1024 * 1024
_DETAIL = "request body too large"
_PAYLOAD_TOO_LARGE = 413
class BodySizeLimitMiddleware:
def __init__(self, app: ASGIApp, max_body_bytes: int) -> None:
self.app = app
self.max_body_bytes = max_body_bytes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
declared = dict(scope.get("headers") or []).get(b"content-length")
if declared is not None and declared.isdigit() and int(declared) > self.max_body_bytes:
response = JSONResponse(
{"detail": _DETAIL}, status_code=_PAYLOAD_TOO_LARGE
)
await response(scope, receive, send)
return
received = 0
async def limited_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_body_bytes:
raise HTTPException(_PAYLOAD_TOO_LARGE, _DETAIL)
return message
await self.app(scope, limited_receive, send)
+11
View File
@@ -44,3 +44,14 @@ def require_admin(x_admin_key: str | None = Header(default=None)) -> None:
)
if x_admin_key is None or not secrets.compare_digest(x_admin_key, settings.admin_api_key):
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid admin key")
def require_bot(x_bot_secret: str | None = Header(default=None)) -> None:
settings = get_settings()
if not settings.bot_api_secret:
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
"telegram login disabled: set BOT_API_SECRET on the API and the bot",
)
if x_bot_secret is None or not secrets.compare_digest(x_bot_secret, settings.bot_api_secret):
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid bot secret")
+38 -3
View File
@@ -11,12 +11,15 @@ Deliberately lightweight for v1:
import re
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sokhan.api.deps import require_bot
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
from sokhan.config import get_settings
from sokhan.core.throttle import FailureThrottle
from sokhan.db import get_db
from sokhan.models import User
from sokhan.schemas import AuthResponse
@@ -76,12 +79,44 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
return AuthResponse(id=user.id, email=user.email, api_token=token)
_login_throttle: FailureThrottle | None = None
def get_login_throttle() -> FailureThrottle:
global _login_throttle
if _login_throttle is None:
settings = get_settings()
_login_throttle = FailureThrottle(
settings.login_max_failures, settings.login_failure_window_seconds
)
return _login_throttle
def reset_login_throttle() -> None:
global _login_throttle
_login_throttle = None
@router.post("/login", response_model=AuthResponse)
def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
def login(
payload: Credentials, request: Request, session: Session = Depends(get_db)
) -> AuthResponse:
email = payload.email.strip().lower()
throttle = get_login_throttle()
key = (request.client.host if request.client else "", email)
wait_seconds = throttle.retry_after(key)
if wait_seconds:
raise HTTPException(
status.HTTP_429_TOO_MANY_REQUESTS,
"too many failed login attempts, try again later",
headers={"Retry-After": str(wait_seconds)},
)
user = session.scalar(select(User).where(User.email == email))
if user is None or not verify_password(payload.password, user.password_hash):
throttle.record_failure(key)
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid credentials")
throttle.reset(key)
token = generate_token()
user.token_hash = token_hash(token)
@@ -97,7 +132,7 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
@router.post("/telegram", response_model=AuthResponse)
@router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)])
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
"""Register-or-login used by the Telegram bot.
+7 -6
View File
@@ -14,6 +14,7 @@ from sokhan.api.serializers import job_to_detail, job_to_out
from sokhan.config import get_settings
from sokhan.core.audio import delete_audio, probe_duration_seconds, save_upload
from sokhan.core.formats import to_docx, to_json_transcript, to_srt, to_txt, to_vtt
from sokhan.core.webhooks import callback_url_problem
from sokhan.db import get_db
from sokhan.models import Job, JobStatus, Segment, User
from sokhan.schemas import JobCreated, JobDetailOut, JobListResponse
@@ -53,16 +54,16 @@ def create_job(
if callback_url is not None:
callback_url = callback_url.strip() or None
if callback_url and (
len(callback_url) > 2048
or not callback_url.lower().startswith(("http://", "https://"))
):
settings = get_settings()
if callback_url:
if len(callback_url) > 2048:
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY,
"callback_url must be an http(s) URL of at most 2048 characters",
)
settings = get_settings()
problem = callback_url_problem(callback_url, settings.webhook_allow_private_targets)
if problem:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, problem)
data = file.file.read()
if not data:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "empty file")
+23 -2
View File
@@ -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
@@ -59,6 +74,8 @@ class Settings(BaseSettings):
# Leave empty to disable the admin endpoints entirely.
admin_api_key: str = ""
bot_api_secret: str = ""
# LLM summaries (optional, behind a feature flag)
summary_enabled: bool = False
llm_api_base: str = ""
@@ -76,6 +93,10 @@ class Settings(BaseSettings):
webhook_signing_secret: str = ""
webhook_timeout_seconds: float = 4.0
webhook_attempts: int = 2
webhook_allow_private_targets: bool = False
login_max_failures: int = 10
login_failure_window_seconds: int = 900
@lru_cache(maxsize=1)
+247
View File
@@ -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()
+48
View File
@@ -0,0 +1,48 @@
import threading
import time
from collections import deque
from collections.abc import Callable, Hashable
class FailureThrottle:
def __init__(
self,
max_failures: int,
window_seconds: float,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.max_failures = max_failures
self.window_seconds = window_seconds
self._clock = clock
self._failures: dict[Hashable, deque[float]] = {}
self._lock = threading.Lock()
def _prune(self, key: Hashable, now: float) -> deque[float]:
stamps = self._failures.get(key)
if stamps is None:
return deque()
while stamps and now - stamps[0] >= self.window_seconds:
stamps.popleft()
if not stamps:
del self._failures[key]
return stamps
def retry_after(self, key: Hashable) -> int:
if self.max_failures <= 0:
return 0
with self._lock:
now = self._clock()
stamps = self._prune(key, now)
if len(stamps) < self.max_failures:
return 0
return max(1, int(stamps[0] + self.window_seconds - now + 0.999))
def record_failure(self, key: Hashable) -> None:
with self._lock:
now = self._clock()
self._prune(key, now)
self._failures.setdefault(key, deque()).append(now)
def reset(self, key: Hashable) -> None:
with self._lock:
self._failures.pop(key, None)
+102 -1
View File
@@ -21,13 +21,17 @@ transport so tests need no network.
import hashlib
import hmac
import http.client
import ipaddress
import json
import logging
import socket
import time
import urllib.error
import urllib.request
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from sokhan.config import get_settings
@@ -89,6 +93,99 @@ def verify_signature(
return hmac.compare_digest(mac.hexdigest(), provided)
class BlockedTargetError(OSError):
pass
def is_public_address(address: str) -> bool:
ip = ipaddress.ip_address(address.split("%", 1)[0])
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
ip = ip.ipv4_mapped
return ip.is_global and not ip.is_multicast
def callback_url_problem(url: str, allow_private: bool) -> str | None:
try:
parts = urlsplit(url)
host = parts.hostname
parts.port # noqa: B018
except ValueError:
return "callback_url is not a valid URL"
if parts.scheme.lower() not in ("http", "https") or not host:
return "callback_url must be an http(s) URL with a host"
if allow_private:
return None
if host == "localhost" or host.endswith(".localhost"):
return "callback_url must point to a public address"
try:
if not is_public_address(host):
return "callback_url must point to a public address"
except ValueError:
pass
return None
def _guarded_create_connection(
address: tuple[str, int],
timeout: float | object = socket._GLOBAL_DEFAULT_TIMEOUT, # type: ignore[attr-defined]
source_address: tuple[str, int] | None = None,
*args: object,
**kwargs: object,
) -> socket.socket:
host, port = address
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
if not infos:
raise BlockedTargetError(f"{host} did not resolve")
for info in infos:
if not is_public_address(str(info[4][0])):
raise BlockedTargetError(f"{host} resolves to non-public address {info[4][0]}")
last_error: OSError | None = None
for info in infos:
try:
return socket.create_connection(
(str(info[4][0]), port), timeout, source_address # type: ignore[arg-type]
)
except OSError as exc:
last_error = exc
raise last_error or BlockedTargetError(f"could not connect to {host}")
class _GuardedHTTPConnection(http.client.HTTPConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _guarded_create_connection # type: ignore[assignment]
class _GuardedHTTPSConnection(http.client.HTTPSConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _guarded_create_connection # type: ignore[assignment]
class _GuardedHTTPHandler(urllib.request.HTTPHandler):
def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
return self.do_open(_GuardedHTTPConnection, req)
class _GuardedHTTPSHandler(urllib.request.HTTPSHandler):
def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
return self.do_open(_GuardedHTTPSConnection, req, context=self._context) # type: ignore[attr-defined]
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
return None
def _public_only_opener() -> urllib.request.OpenerDirector:
return urllib.request.build_opener(
urllib.request.ProxyHandler({}),
_GuardedHTTPHandler(),
_GuardedHTTPSHandler(),
_NoRedirectHandler(),
)
def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float) -> None:
request = urllib.request.Request(
url,
@@ -96,7 +193,11 @@ def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float
headers={"Content-Type": "application/json", **headers},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
if get_settings().webhook_allow_private_targets:
opener = urllib.request.build_opener()
else:
opener = _public_only_opener()
with opener.open(request, timeout=timeout) as response:
response.read()
+5
View File
@@ -14,6 +14,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sokhan import __version__
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
from sokhan.config import get_settings
from sokhan.db import configure, create_all
@@ -52,6 +53,10 @@ def create_app() -> FastAPI:
for origin in os.getenv("SOKHAN_CORS_ORIGINS", "").split(",")
if origin.strip()
] or ["http://localhost:3000", "http://127.0.0.1:3000"]
app.add_middleware(
BodySizeLimitMiddleware,
max_body_bytes=settings.max_upload_mb * 1024 * 1024 + MULTIPART_OVERHEAD_BYTES,
)
app.add_middleware(
CORSMiddleware,
allow_origins=cors_origins,
+6
View File
@@ -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))
+3
View File
@@ -29,15 +29,18 @@ def app(tmp_path, monkeypatch):
monkeypatch.setenv("PLAN_PRO_MAX_FILE_MINUTES", "180")
monkeypatch.setenv("PLAN_PRO_MONTHLY_MINUTES", "1200")
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
get_settings.cache_clear()
reset_login_throttle()
db.reset()
db.configure(f"sqlite:///{tmp_path / 'test.sqlite3'}")
db.create_all()
yield create_app()
db.reset()
get_settings.cache_clear()
reset_login_throttle()
@pytest.fixture()
+33 -3
View File
@@ -1,3 +1,4 @@
import pytest
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
@@ -51,14 +52,43 @@ def test_token_login_rejects_bad_code(client):
assert response.status_code == 401
def test_telegram_register_or_login(client):
first = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
BOT_SECRET = "bot-shared-secret"
@pytest.fixture()
def bot_secret(monkeypatch):
from sokhan.config import get_settings
monkeypatch.setenv("BOT_API_SECRET", BOT_SECRET)
get_settings.cache_clear()
yield {"X-Bot-Secret": BOT_SECRET}
get_settings.cache_clear()
def test_telegram_register_or_login(client, bot_secret):
body = {"telegram_id": 12345, "username": "amin"}
first = client.post("/auth/telegram", json=body, headers=bot_secret)
assert first.status_code == 200
second = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
second = client.post("/auth/telegram", json=body, headers=bot_secret)
assert second.status_code == 200
assert first.json()["id"] == second.json()["id"]
def test_telegram_login_rejects_callers_without_the_bot_secret(client, bot_secret):
body = {"telegram_id": 12345}
missing = client.post("/auth/telegram", json=body)
wrong = client.post("/auth/telegram", json=body, headers={"X-Bot-Secret": "guess"})
assert missing.status_code == 403
assert wrong.status_code == 403
def test_telegram_login_is_disabled_without_a_configured_secret(client):
response = client.post(
"/auth/telegram", json={"telegram_id": 12345}, headers={"X-Bot-Secret": ""}
)
assert response.status_code == 503
def test_jobs_require_token(client):
response = client.get("/jobs")
assert response.status_code == 401
+49
View File
@@ -0,0 +1,49 @@
import pytest
from fastapi.testclient import TestClient
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES
from sokhan.main import create_app
MIB = 1024 * 1024
@pytest.fixture()
def small_cap_client(app, monkeypatch):
from sokhan.config import get_settings
monkeypatch.setenv("MAX_UPLOAD_MB", "1")
get_settings.cache_clear()
with TestClient(create_app()) as test_client:
yield test_client
get_settings.cache_clear()
def test_declared_oversized_body_is_rejected_up_front(small_cap_client, auth):
too_big = b"\0" * (MIB + MULTIPART_OVERHEAD_BYTES + 1)
response = small_cap_client.post(
"/jobs", headers=auth, files={"file": ("big.wav", too_big, "audio/wav")}
)
assert response.status_code == 413
def test_chunked_oversized_body_is_cut_off_mid_stream(small_cap_client, auth):
def body():
for _ in range(4):
yield b"\0" * MIB
response = small_cap_client.post(
"/jobs",
headers={**auth, "Content-Type": "multipart/form-data; boundary=x"},
content=body(),
)
assert response.status_code == 413
def test_upload_under_the_cap_still_works(
small_cap_client, auth, wav_bytes, fake_engine, wait_for_job
):
response = small_cap_client.post(
"/jobs", headers=auth, files={"file": ("ok.wav", wav_bytes, "audio/wav")}
)
assert response.status_code == 201
job = wait_for_job(small_cap_client, auth, response.json()["id"])
assert job["status"] == "completed"
+61
View File
@@ -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(" ") == " "
+55
View File
@@ -0,0 +1,55 @@
import pytest
from sokhan.core.throttle import FailureThrottle
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
WRONG = {"email": REGISTER["email"], "password": "wrong-pass"}
@pytest.fixture()
def tight_login_limit(app, monkeypatch):
from sokhan.api.routes_auth import reset_login_throttle
from sokhan.config import get_settings
monkeypatch.setenv("LOGIN_MAX_FAILURES", "3")
get_settings.cache_clear()
reset_login_throttle()
def test_login_is_throttled_after_repeated_failures(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(3):
assert client.post("/auth/login", json=WRONG).status_code == 401
blocked = client.post("/auth/login", json=REGISTER)
assert blocked.status_code == 429
assert int(blocked.headers["Retry-After"]) > 0
def test_successful_login_clears_the_failure_count(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
for _ in range(2):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=REGISTER).status_code == 200
for _ in range(2):
assert client.post("/auth/login", json=WRONG).status_code == 401
def test_other_accounts_are_not_locked_out(client, tight_login_limit):
client.post("/auth/register", json=REGISTER)
other = {"email": "sara@example.org", "password": "parool-5678"}
client.post("/auth/register", json=other)
for _ in range(3):
client.post("/auth/login", json=WRONG)
assert client.post("/auth/login", json=other).status_code == 200
def test_throttle_window_slides():
now = [1000.0]
throttle = FailureThrottle(max_failures=2, window_seconds=60, clock=lambda: now[0])
throttle.record_failure("k")
throttle.record_failure("k")
assert throttle.retry_after("k") == 60
now[0] += 30
assert throttle.retry_after("k") == 30
now[0] += 30
assert throttle.retry_after("k") == 0
+6 -2
View File
@@ -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
+50
View File
@@ -341,3 +341,53 @@ def test_dead_endpoint_does_not_fail_the_job(
detail = wait_for_job(client, auth, response.json()["id"])
assert detail["status"] == "completed"
assert "سلام بر تو" in detail["text"]
@pytest.mark.parametrize(
"url",
[
"http://127.0.0.1:6379/",
"http://localhost:8000/admin",
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.5/hook",
"http://[::1]/hook",
"http://[::ffff:192.168.1.1]/hook",
"https://",
],
)
def test_callback_url_to_private_targets_is_rejected(client, auth, wav_bytes, url):
response = _upload(client, auth, wav_bytes, callback_url=url)
assert response.status_code == 422
def test_private_callback_url_allowed_when_opted_in(
client, auth, wav_bytes, monkeypatch, fake_engine, wait_for_job
):
from sokhan.config import get_settings
from sokhan.core import webhooks
monkeypatch.setenv("WEBHOOK_ALLOW_PRIVATE_TARGETS", "true")
get_settings.cache_clear()
delivered: list[str] = []
monkeypatch.setattr(webhooks, "_default_post", lambda url, *rest: delivered.append(url))
response = _upload(client, auth, wav_bytes, callback_url="http://10.0.0.5/hook")
assert response.status_code == 201
wait_for_job(client, auth, response.json()["id"])
get_settings.cache_clear()
assert delivered == ["http://10.0.0.5/hook"]
def test_delivery_refuses_hosts_that_resolve_privately(monkeypatch):
import socket
import urllib.error
from sokhan.core import webhooks
def fake_getaddrinfo(host, port, *args, **kwargs):
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
monkeypatch.setattr(webhooks.socket, "getaddrinfo", fake_getaddrinfo)
with pytest.raises(urllib.error.URLError) as caught:
webhooks._default_post("http://hooks.example/sokhan", b"{}", {}, 1.0)
assert isinstance(caught.value.reason, webhooks.BlockedTargetError)
+47
View File
@@ -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
+21 -6
View File
@@ -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": [],
}
+9 -5
View File
@@ -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
View File
@@ -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
}
]
}
+118
View File
@@ -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())
+1
View File
@@ -50,6 +50,7 @@ class SokhanClient:
response = self._client.post(
f"{self.settings.api_base_url}/auth/telegram",
json={"telegram_id": telegram_id, "username": username},
headers={"X-Bot-Secret": self.settings.bot_api_secret},
)
if response.status_code != 200:
raise BackendError(f"register failed with status {response.status_code}")
+2
View File
@@ -9,6 +9,7 @@ class BotSettings:
telegram_bot_token: str
api_base_url: str
web_base_url: str
bot_api_secret: str = ""
def load_settings() -> BotSettings:
@@ -16,4 +17,5 @@ def load_settings() -> BotSettings:
telegram_bot_token=os.environ.get("TELEGRAM_BOT_TOKEN", ""),
api_base_url=os.environ.get("API_BASE_URL", "http://localhost:8000").rstrip("/"),
web_base_url=os.environ.get("WEB_BASE_URL", "http://localhost:3000").rstrip("/"),
bot_api_secret=os.environ.get("BOT_API_SECRET", ""),
)
+7
View File
@@ -30,6 +30,13 @@ def main() -> None:
file=sys.stderr,
)
raise SystemExit(1)
if not settings.bot_api_secret:
print(
"BOT_API_SECRET is not set. Set the same value on the API and the bot; "
"the API refuses Telegram logins without it.",
file=sys.stderr,
)
raise SystemExit(1)
bot = Bot(settings.telegram_bot_token)
dispatcher = Dispatcher()
+18
View File
@@ -88,3 +88,21 @@ def test_get_plans_parses_catalogue():
plans = client.get_plans()
assert [plan["code"] for plan in plans] == ["free", "pro"]
assert plans[1]["max_file_minutes"] == 180
def test_register_telegram_sends_the_bot_secret():
seen: dict[str, str | None] = {}
def handler(request: httpx.Request) -> httpx.Response:
seen["secret"] = request.headers.get("X-Bot-Secret")
return httpx.Response(200, json={"id": "u1", "email": "tg", "api_token": "tok"})
settings = BotSettings(
telegram_bot_token="t",
api_base_url="http://api.test",
web_base_url="http://web.test",
bot_api_secret="shared",
)
with SokhanClient(settings, transport=httpx.MockTransport(handler)) as client:
assert client.register_telegram(42, None) == "tok"
assert seen["secret"] == "shared"
+6 -1
View File
@@ -38,20 +38,25 @@ 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}
WEBHOOK_SIGNING_SECRET: ${WEBHOOK_SIGNING_SECRET:-}
WEBHOOK_ALLOW_PRIVATE_TARGETS: ${WEBHOOK_ALLOW_PRIVATE_TARGETS:-false}
LOGIN_MAX_FAILURES: ${LOGIN_MAX_FAILURES:-10}
LOGIN_FAILURE_WINDOW_SECONDS: ${LOGIN_FAILURE_WINDOW_SECONDS:-900}
FREE_MINUTES_PER_USER_PER_MONTH: ${FREE_MINUTES_PER_USER_PER_MONTH:-30}
PLAN_FREE_MAX_FILE_MINUTES: ${PLAN_FREE_MAX_FILE_MINUTES:-10}
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}
PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200}
ADMIN_API_KEY: ${ADMIN_API_KEY:-}
BOT_API_SECRET: ${BOT_API_SECRET:-}
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
LLM_API_BASE: ${LLM_API_BASE:-}
+10 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
+130
View File
@@ -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
View File
@@ -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