Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3437ee230
|
||
|
|
9a74cca685
|
||
|
|
ace0b764ba
|
||
|
|
064e7a0bd5
|
||
|
|
9d35436cce
|
||
|
|
bcce7ac897
|
||
|
|
9ccf51e3c9
|
||
|
|
3895219768
|
||
|
|
b22dd5d161
|
||
|
|
032b8de9e8
|
||
|
|
3123e2006c
|
||
|
|
0deafa4cdf
|
||
|
|
1219089a3c
|
||
|
|
b2386acdd1
|
||
|
|
a29dae7f56
|
||
|
|
d254527881
|
||
|
|
53becfa1de
|
||
|
|
4d2c060a29
|
||
|
|
f1f8a9919b
|
||
|
|
ea821ff70b
|
||
|
|
ad23bbfa43
|
||
|
|
36262770d0
|
||
|
|
7a3dab88c8
|
||
|
|
752c972669
|
||
|
|
9ba610d081
|
||
|
|
d93d98c102
|
||
|
|
a2bab55d25
|
||
|
|
9e6d8fc91a
|
||
|
|
8a585fc718
|
||
|
|
57be6ca2ce
|
||
|
|
103f72f41e
|
||
|
|
ee42254ab1
|
||
|
|
9d15525500
|
||
|
|
c902ab4469
|
||
|
|
1304b13999
|
||
|
|
4821d812dc | ||
|
|
601fed0766 |
No files matched your search
+42
-6
@@ -1,5 +1,6 @@
|
||||
# Sokhan configuration
|
||||
# Copy this file to .env and adjust the values.
|
||||
# For docker compose, copy it to deploy/.env instead.
|
||||
# Every variable below has a working default for local development.
|
||||
|
||||
# --- Core ---
|
||||
@@ -18,8 +19,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 +33,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.
|
||||
@@ -83,6 +95,17 @@ MAX_UPLOAD_MB=200
|
||||
# (POST /admin/users/{email}/plan). Leave empty to disable the admin surface.
|
||||
ADMIN_API_KEY=
|
||||
|
||||
# --- Dashboard session cookie ---
|
||||
# The web dashboard signs in with an httpOnly cookie instead of keeping the
|
||||
# API token in localStorage. It reaches the API through its own /api path,
|
||||
# so the cookie is first-party on any host. AUTH_COOKIE_SECURE=auto marks it
|
||||
# Secure whenever the browser uses HTTPS (directly or via a proxy setting
|
||||
# X-Forwarded-Proto); true/false force it. SameSite=none (with HTTPS) is only
|
||||
# needed when NEXT_PUBLIC_API_BASE points at an API on a different site.
|
||||
AUTH_COOKIE_SECURE=auto
|
||||
AUTH_COOKIE_SAMESITE=lax
|
||||
AUTH_COOKIE_MAX_AGE_DAYS=30
|
||||
|
||||
# --- LLM summaries (optional) ---
|
||||
# Any OpenAI-compatible chat-completions endpoint works.
|
||||
# Set SUMMARY_ENABLED=true and provide a key to turn summaries on.
|
||||
@@ -95,6 +118,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
|
||||
|
||||
@@ -102,8 +128,12 @@ WEB_BASE_URL=http://localhost:3000
|
||||
API_BASE_URL=http://localhost:8000
|
||||
|
||||
# --- Web ---
|
||||
# Browser-facing API base URL used by the Next.js app.
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:8000
|
||||
# Browser-facing API base URL, baked into the web build. Leave empty: the
|
||||
# dashboard then calls /api on its own origin, which the web server proxies
|
||||
# to API_PROXY_TARGET. Set it only when the API is served from its own host
|
||||
# (that also needs SOKHAN_CORS_ORIGINS and AUTH_COOKIE_SAMESITE=none).
|
||||
NEXT_PUBLIC_API_BASE=
|
||||
API_PROXY_TARGET=http://api:8000
|
||||
|
||||
# --- Job-completion webhooks (optional) ---
|
||||
# Jobs uploaded with a callback_url get a POST when they finish. The payload
|
||||
@@ -118,6 +148,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+164
@@ -5,16 +5,142 @@ 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.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Compose: the Whisper model cache now lives on the `sokhan-data` volume
|
||||
(`HF_HOME=/data/huggingface`). Previously it sat in the container's own
|
||||
filesystem, so every recreate (`down`/`up`, `--build`, a new image)
|
||||
re-downloaded the weights — and transcription failed outright where the
|
||||
Hugging Face Hub is unreachable.
|
||||
- Compose: the postgres healthcheck probes the configured `POSTGRES_USER` and
|
||||
`POSTGRES_DB` instead of a hardcoded `sokhan`.
|
||||
- Quickstart (both READMEs) and `.env.example` now say to copy the env file to
|
||||
`deploy/.env`; the missing-password error names that path too. Copying it to
|
||||
the repo root left `POSTGRES_PASSWORD` unset for compose.
|
||||
- Sign-in through the dashboard flows (register, login, connect code) now
|
||||
also sets the token as an `HttpOnly; SameSite=lax` session cookie
|
||||
(`Secure` whenever the browser uses HTTPS), and the API accepts it in place of a bearer header. Every
|
||||
cookie-authenticated write must send the session's CSRF token in
|
||||
`X-CSRF-Token` (403 otherwise); the token is an HMAC of the session
|
||||
token, so nothing extra is stored. `GET /auth/session` returns the
|
||||
signed-in account and its CSRF token, and logout clears the cookie.
|
||||
Bearer auth (bot, API scripts, OpenAI-compatible clients) is unchanged
|
||||
and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`
|
||||
(`auto`/`true`/`false`), `AUTH_COOKIE_SAMESITE`,
|
||||
`AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows credentials for the
|
||||
configured `SOKHAN_CORS_ORIGINS` (#33).
|
||||
- The dashboard no longer keeps the API token in `localStorage`, where an
|
||||
XSS could read it (CodeQL `js/clear-text-storage-of-sensitive-data`). It
|
||||
relies on the httpOnly session cookie, sends the CSRF token on writes,
|
||||
learns who is signed in from `GET /auth/session`, and wipes the token
|
||||
earlier versions left in `localStorage`. The dashboard reaches the API
|
||||
through its own `/api` path, proxied by the web server to
|
||||
`API_PROXY_TARGET`, so the cookie is first-party on localhost, 127.0.0.1,
|
||||
a LAN address or a domain alike; `NEXT_PUBLIC_API_BASE` now defaults to
|
||||
empty and is only for an API on its own host (#33).
|
||||
|
||||
### 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.
|
||||
- Dashboard dark mode: a sun/moon toggle in the header, defaulting to the OS
|
||||
preference until the user picks one (saved in localStorage, applied before
|
||||
first paint so there is no flash). Implemented by remapping the Tailwind
|
||||
palette under `html.dark` in `globals.css`, so existing pages needed no
|
||||
per-class changes.
|
||||
- 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.
|
||||
- A show/hide toggle (eye icon) on the login page's password field.
|
||||
|
||||
- `CONTRIBUTING.fa.md`: a Persian translation of the contribution guide,
|
||||
with a language switcher in both files like the READMEs (#31).
|
||||
- `POST /auth/logout` revokes the caller's token (204). An account has a
|
||||
single active token, so it signs out every client holding it.
|
||||
|
||||
- The dashboard header shows the sign-in state: a **Sign in** button when
|
||||
signed out, the account email and **Sign out** when signed in. Sign out
|
||||
revokes the token on the server and works even when the API is
|
||||
unreachable. The landing page's sign-in button is hidden and the login
|
||||
page redirects to the upload page for a signed-in user.
|
||||
|
||||
### 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
|
||||
@@ -23,6 +149,44 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
under it. Applied across LICENSE, both READMEs, CITATION.cff, both
|
||||
pyproject.toml files, web/package.json, the landing site copy, the demo
|
||||
Space metadata and the fine-tuned model card.
|
||||
- The header shows the signed-in account as an avatar with the email's
|
||||
initial. It opens a menu with the full email and Sign out, instead of a
|
||||
truncated email that disappeared on narrow screens.
|
||||
|
||||
### Fixed
|
||||
|
||||
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
|
||||
read-only volume) now answers **503** with a short message on `POST /jobs`
|
||||
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
|
||||
the log. The real `OSError` is logged server-side, a partially written
|
||||
file is removed, and the API logs an error at startup when `DATA_DIR`
|
||||
is not writable.
|
||||
- The punctuation post-pass no longer splits numbers written with a
|
||||
thousands separator: `1,000` stayed `1، 000` (Persian comma plus a
|
||||
space). A comma between digits followed by exactly three digits is now
|
||||
kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`.
|
||||
The edge cases from #30 (slash dates, Latin digits in Persian sentences,
|
||||
abbreviations, ellipses, repeated marks) are pinned by tests.
|
||||
- The Telegram bot recovers when the API revokes the token it cached for a
|
||||
chat (a newer sign-in or a logout of the same account). Every request
|
||||
used to fail from then on; the bot now drops the token, re-registers
|
||||
once and retries, and `/start` only shows a connect code that works.
|
||||
- Job progress now moves while a chunk is being transcribed, not only
|
||||
between 30-second chunks. A clip shorter than 30 s is a single chunk, so
|
||||
its progress sat at 0% for the whole job and then jumped to 100%. The
|
||||
Whisper engine reports how far into the chunk it is as each segment is
|
||||
decoded; the worker saves that at most once a second.
|
||||
- The archive page refreshes itself while any job is queued or processing;
|
||||
its progress bars never moved before. A job with no progress reported yet
|
||||
shows a moving bar and "Getting ready" instead of an empty, stuck-looking
|
||||
bar at 0%, and the job page shows the percentage with the right sign in
|
||||
English.
|
||||
|
||||
### Removed
|
||||
|
||||
- The landing page's separate sign-in button; signing in lives in
|
||||
the header, and "Get started" sends signed-out visitors to the login
|
||||
page.
|
||||
|
||||
## [1.4.1] - 2026-11-26
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# مشارکت در سخن
|
||||
|
||||
[English](CONTRIBUTING.md) | **فارسی**
|
||||
|
||||
ممنون که به سخن سر زدید. این مخزن یک کیت گفتار به متنِ فارسی است که
|
||||
میشود سلفهاستش کرد: یک بکاند FastAPI با موتور faster-whisper، یک ورکر
|
||||
Celery، یک داشبورد Next.js (فارسیمحور و راستبهچپ)، یک ربات تلگرام
|
||||
اختیاری، یک پایپلاین فاینتیونِ LoRA با نتایجِ اندازهگیریشده، و یک دموی
|
||||
عمومیِ مرورگری روی Hugging Face.
|
||||
|
||||
## راهاندازی محیط توسعه
|
||||
|
||||
برای بکاند و ربات Python 3.12 و برای داشبورد وب Node 22 لازم است:
|
||||
|
||||
pip install -e "backend[dev]" -e "bot[dev]"
|
||||
cd web && npm ci
|
||||
|
||||
وابستگیهای سنگین (torch / faster-whisper) فقط برای ابزارهای آموزش و
|
||||
بنچمارک لازماند:
|
||||
|
||||
pip install -r training/requirements.txt -r benchmarks/requirements.txt
|
||||
pip install -r space/gradio/requirements.txt # self-hostable Gradio demo
|
||||
|
||||
## تستها، لینت و نظم کامیتها
|
||||
|
||||
CI روی هر push و pull request همین دستورها را اجرا میکند:
|
||||
|
||||
ruff check backend bot training benchmarks space deploy
|
||||
mypy --config-file backend/pyproject.toml backend/sokhan
|
||||
pytest backend/tests bot/tests
|
||||
cd web && npm ci && npm run build
|
||||
|
||||
هوکهای pre-commit (ruff بهعلاوهٔ چند بررسی پایه) را برای هر کلون یک بار
|
||||
فعال کنید:
|
||||
|
||||
pip install pre-commit && pre-commit install
|
||||
|
||||
پیام کامیتها از Conventional Commits پیروی میکنند (`feat:`، `fix:`،
|
||||
`docs:`، ...) و نسخهگذاری پروژه بر اساس Semantic Versioning است؛ هر
|
||||
تغییری که کاربر میبیند یک خط در CHANGELOG.md میگیرد.
|
||||
|
||||
## دموی مرورگری و ورکفلوی sync-space
|
||||
|
||||
`space/` دموی استاتیکی است که Whisper در آن کاملاً سمتِ مرورگر اجرا
|
||||
میشود (transformers.js). ورکفلوی `Sync demo Space` با هر pushای که به
|
||||
`space/` دست بزند، آن را با سکرتِ `HF_TOKEN` در Actions مخزن روی
|
||||
hf.co/spaces/Abol0pati/sokhan-fa-demo منتشر میکند - برای همین دموی
|
||||
عمومی هیچوقت از `main` عقب نمیماند. `space/gradio/` یک اپ جدا و
|
||||
سلفهاستشدنی است که چکپوینتِ فاینتیونشده را با همان تنظیمات موتورِ
|
||||
محیط production سرو میکند؛ این اپ عمداً روی Space عمومی آپلود نمیشود
|
||||
(قیمتگذاری ۲۰۲۶ هاگینگفیس، Spaceهای میزبانیشدهٔ Gradio/Docker را پشت
|
||||
اشتراک PRO قفل کرده است).
|
||||
|
||||
## قاعدهٔ «اول اندازهگیری»
|
||||
|
||||
هر ادعایی دربارهٔ دقت (WER، CER، سرعت) که در README، کارت مدل یا
|
||||
changelog میآید باید از `benchmarks/benchmark_wer.py` (یا ارزیابیِ
|
||||
نوتبوک) آمده باشد و فیکسچر و سختافزارش ذکر شده باشد. هیچ عددِ ساختگی
|
||||
پذیرفته نیست.
|
||||
|
||||
## امنیت
|
||||
|
||||
گزارشهای امنیتی را بهصورت issue عمومی باز نکنید - برای افشای خصوصی
|
||||
SECURITY.md را ببینید.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Contributing to Sokhan
|
||||
|
||||
**English** | [فارسی](CONTRIBUTING.fa.md)
|
||||
|
||||
Thanks for looking into Sokhan. This repo is a self-hostable Persian
|
||||
speech-to-text kit: a FastAPI backend with a faster-whisper engine, a
|
||||
Celery worker, a Next.js (Persian-first, RTL) dashboard, an optional
|
||||
|
||||
+25
-14
@@ -145,6 +145,8 @@ faster-whisper، یک ورکر Celery، یک داشبورد Next.js که فار
|
||||
```bash
|
||||
git clone https://github.com/Abolfazlrwm/sokhan.git
|
||||
cd sokhan
|
||||
cp .env.example deploy/.env # compose فایل .env کنار فایل compose را میخواند
|
||||
# در deploy/.env مقدار POSTGRES_PASSWORD را یک رمز طولانی و تصادفی بگذارید
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
@@ -152,7 +154,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
|
||||
- API و مستندات: http://localhost:8000/docs
|
||||
|
||||
ورکر مدل Whisper تنظیمشده را در اولین رونویسی دانلود میکند
|
||||
(`WHISPER_MODEL_SIZE`، پیشفرض `small`). برای فعالکردن خلاصهسازی،
|
||||
(`WHISPER_MODEL_SIZE`، پیشفرض `small`) و آن را روی ولوم `sokhan-data`
|
||||
(`HF_HOME=/data/huggingface`) نگه میدارد، پس ساخت دوبارهٔ کانتینرها مدل را
|
||||
دوباره دانلود نمیکند. برای فعالکردن خلاصهسازی،
|
||||
`SUMMARY_ENABLED=true` و متغیرهای LLM خود را در فایل `.env` کنار
|
||||
`docker-compose.yml` بگذارید. برای اعمال مهاجرتهای اسکیما بهصورت دستی:
|
||||
|
||||
@@ -177,10 +181,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest
|
||||
خودش نوشته: با `up -d --build` لوکال بسازید، یا با
|
||||
`docker compose -f deploy/docker-compose.yml pull` و `up -d --no-build`
|
||||
ایمیجهای منتشرشده را اجرا کنید. نسخههای پینشده تابع تگهای گیت هستند
|
||||
(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). توجه: ایمیج وب مقدار
|
||||
`NEXT_PUBLIC_API_BASE` (پیشفرض `http://localhost:8000`) را موقع build
|
||||
میگیرد — دیپلویهایی که داشبورد را از origin دیگری سرو میکنند باید خودشان
|
||||
این build argument را بدهند.
|
||||
(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). داشبورد API را از
|
||||
مسیر `/api` روی همان origin خودش صدا میزند و وبسرور آن را به
|
||||
`API_PROXY_TARGET` (پیشفرض `http://api:8000`، موقع build) پراکسی میکند؛
|
||||
برای همین یک ایمیج روی هر هاست یا دامنهای کار میکند.
|
||||
|
||||
## توسعه
|
||||
|
||||
@@ -225,12 +229,16 @@ 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) |
|
||||
| `NEXT_PUBLIC_API_BASE` | خالی (همان origin، `/api`) | آدرس API که اپ وب صدا میزند، فقط وقتی API روی هاست جدا است (زمان build) |
|
||||
| `API_PROXY_TARGET` | `http://api:8000` | مقصد پراکسی `/api` در وبسرور (زمان build) |
|
||||
|
||||
فهرست کامنتدار در [.env.example](.env.example).
|
||||
|
||||
@@ -288,14 +296,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`
|
||||
یک هیوریستیک است: برچسبهایش شباهت صوتی را توصیف میکنند نه هویتِ تأییدشده
|
||||
|
||||
@@ -143,6 +143,8 @@ default — a GPU is not required.
|
||||
```bash
|
||||
git clone https://github.com/Abolfazlrwm/sokhan.git
|
||||
cd sokhan
|
||||
cp .env.example deploy/.env # compose reads the .env next to the compose file
|
||||
# edit deploy/.env and set POSTGRES_PASSWORD to a long random value
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
@@ -150,7 +152,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
|
||||
- API and docs: http://localhost:8000/docs
|
||||
|
||||
The worker downloads the configured Whisper model on first transcription
|
||||
(`WHISPER_MODEL_SIZE`, default `small`). To enable summaries, set
|
||||
(`WHISPER_MODEL_SIZE`, default `small`) and caches it on the `sokhan-data`
|
||||
volume (`HF_HOME=/data/huggingface`), so recreating the containers does not
|
||||
download it again. To enable summaries, set
|
||||
`SUMMARY_ENABLED=true` and your LLM variables in a `.env` file next to
|
||||
`docker-compose.yml`. To apply schema migrations manually:
|
||||
|
||||
@@ -176,10 +180,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest
|
||||
`build:` blocks: keep `up -d --build` to build locally, or
|
||||
`docker compose -f deploy/docker-compose.yml pull` and
|
||||
`up -d --no-build` to run the published images. Pinned versions follow the
|
||||
git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). Note the web image
|
||||
bakes `NEXT_PUBLIC_API_BASE` (default `http://localhost:8000`) at build
|
||||
time — deployments serving the dashboard from another origin pass the
|
||||
build argument themselves.
|
||||
git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). The dashboard calls
|
||||
the API through its own `/api` path, which the web server proxies to
|
||||
`API_PROXY_TARGET` (default `http://api:8000`, baked at build time), so one
|
||||
image works on any host or domain.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -224,12 +228,16 @@ 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) |
|
||||
| `NEXT_PUBLIC_API_BASE` | empty (same-origin `/api`) | API address the web app calls, only for an API on its own host (build-time) |
|
||||
| `API_PROXY_TARGET` | `http://api:8000` | Where the web server proxies `/api` (build-time) |
|
||||
|
||||
See [.env.example](.env.example) for the commented list.
|
||||
|
||||
@@ -287,14 +295,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,
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ silence:
|
||||
which uses scrypt).
|
||||
3. **Track as an issue** — when a fix needs design work (for example
|
||||
moving the dashboard token from localStorage to an httpOnly cookie
|
||||
implies a CSRF layer and is roadmap work, not a drive-by patch).
|
||||
implied a CSRF layer: it was tracked as #33 and has since shipped, so
|
||||
the dashboard no longer keeps the token in script-readable storage).
|
||||
|
||||
Dismissed alerts stay visible in the Security tab with their
|
||||
justification, so the reasoning is auditable rather than hidden.
|
||||
+3
-3
@@ -12,9 +12,9 @@ COPY alembic ./alembic
|
||||
|
||||
RUN pip install --no-cache-dir .
|
||||
|
||||
# Non-root runtime user; uvicorn binds 8000 (unprivileged) and the app keeps
|
||||
# no local writable state (postgres via DATABASE_URL).
|
||||
RUN useradd --system --uid 1000 --create-home appuser
|
||||
RUN useradd --system --uid 1000 --create-home appuser \
|
||||
&& mkdir -p /data/audio \
|
||||
&& chown -R appuser:appuser /data
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
@@ -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)
|
||||
@@ -1,29 +1,59 @@
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key."""
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key.
|
||||
|
||||
A request authenticates in one of two ways:
|
||||
|
||||
- `Authorization: Bearer <token>`: API clients, the bot and scripts. A
|
||||
browser never attaches this header on its own, so no CSRF check applies.
|
||||
- the httpOnly session cookie set at sign-in: the web dashboard. Browsers
|
||||
send it automatically, so every unsafe method must also carry the
|
||||
matching X-CSRF-Token header (see `sokhan.auth.csrf_token_for`).
|
||||
"""
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.auth import token_hash
|
||||
from sokhan.auth import csrf_token_for, token_hash
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
SESSION_COOKIE = "sokhan_session"
|
||||
CSRF_HEADER = "X-CSRF-Token"
|
||||
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
|
||||
|
||||
def get_request_token(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
) -> str:
|
||||
"""The caller's raw token, from the bearer header or the session cookie.
|
||||
|
||||
Cookie-authenticated unsafe requests must send the CSRF token; a
|
||||
missing or wrong one is a 403 before the token is even looked up.
|
||||
"""
|
||||
if credentials is not None and credentials.credentials:
|
||||
return credentials.credentials
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
if request.method not in _SAFE_METHODS:
|
||||
sent = request.headers.get(CSRF_HEADER, "")
|
||||
if not secrets.compare_digest(sent, csrf_token_for(token)):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "missing or invalid CSRF token")
|
||||
return token
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
token: str = Depends(get_request_token),
|
||||
session: Session = Depends(get_db),
|
||||
) -> User:
|
||||
if credentials is None or not credentials.credentials:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
user = session.scalar(
|
||||
select(User).where(User.token_hash == token_hash(credentials.credentials))
|
||||
)
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token")
|
||||
return user
|
||||
@@ -44,3 +74,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")
|
||||
@@ -7,19 +7,35 @@ Deliberately lightweight for v1:
|
||||
- POST /auth/telegram lets the bot create or resume an account per Telegram id
|
||||
- POST /auth/token-login lets a user paste the connect code shown by the bot
|
||||
to link their browser session
|
||||
- POST /auth/logout revokes the caller's token
|
||||
- GET /auth/session tells the dashboard who is signed in
|
||||
|
||||
Sign-in through the web flows (register, login, token-login) also sets the
|
||||
token as an httpOnly session cookie, so the dashboard never has to keep it
|
||||
in script-readable storage. The JSON body still carries `api_token` for API
|
||||
clients and the bot.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
|
||||
from sokhan.api.deps import SESSION_COOKIE, get_current_user, get_request_token, require_bot
|
||||
from sokhan.auth import (
|
||||
csrf_token_for,
|
||||
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
|
||||
from sokhan.schemas import AuthResponse, SessionOut
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -59,8 +75,58 @@ def _validate_credentials(email: str, password: str) -> str:
|
||||
return email
|
||||
|
||||
|
||||
def _cookie_is_secure(request: Request) -> bool:
|
||||
"""Whether the session cookie gets the Secure attribute.
|
||||
|
||||
`auto` (the default) follows the scheme the browser used: HTTPS directly
|
||||
or behind a proxy that sets X-Forwarded-Proto. Browsers drop a Secure
|
||||
cookie that arrives over plain http (Safari even on localhost), which
|
||||
left plain-http installs unable to stay signed in.
|
||||
"""
|
||||
mode = get_settings().auth_cookie_secure.strip().lower()
|
||||
if mode in ("true", "1", "yes"):
|
||||
return True
|
||||
if mode in ("false", "0", "no"):
|
||||
return False
|
||||
forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower()
|
||||
return request.url.scheme == "https" or forwarded == "https"
|
||||
|
||||
|
||||
def _start_session(request: Request, response: Response, user: User, token: str) -> AuthResponse:
|
||||
"""Set the httpOnly session cookie and answer with the CSRF token."""
|
||||
settings = get_settings()
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
max_age=settings.auth_cookie_max_age_days * 24 * 3600,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=_cookie_is_secure(request),
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
return AuthResponse(
|
||||
id=user.id, email=user.email, api_token=token, csrf_token=csrf_token_for(token)
|
||||
)
|
||||
|
||||
|
||||
def _end_session(request: Request, response: Response) -> None:
|
||||
settings = get_settings()
|
||||
response.delete_cookie(
|
||||
SESSION_COOKIE,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=_cookie_is_secure(request),
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/register", response_model=AuthResponse)
|
||||
def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def register(
|
||||
payload: Credentials,
|
||||
request: Request,
|
||||
response: Response,
|
||||
session: Session = Depends(get_db),
|
||||
) -> AuthResponse:
|
||||
email = _validate_credentials(payload.email, payload.password)
|
||||
if session.scalar(select(User).where(User.email == email)):
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "email already registered")
|
||||
@@ -73,31 +139,103 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(request, response, user, 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,
|
||||
response: Response,
|
||||
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)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(request, response, user, token)
|
||||
|
||||
|
||||
@router.post("/token-login", response_model=AuthResponse)
|
||||
def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def token_login(
|
||||
payload: TokenLogin,
|
||||
request: Request,
|
||||
response: Response,
|
||||
session: Session = Depends(get_db),
|
||||
) -> AuthResponse:
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(payload.api_token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid connect code")
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
|
||||
return _start_session(request, response, user, payload.api_token)
|
||||
|
||||
|
||||
@router.post("/telegram", response_model=AuthResponse)
|
||||
@router.get("/session", response_model=SessionOut)
|
||||
def current_session(
|
||||
user: User = Depends(get_current_user), token: str = Depends(get_request_token)
|
||||
) -> SessionOut:
|
||||
"""Who is signed in, plus the CSRF token for this session.
|
||||
|
||||
The dashboard cannot read its httpOnly cookie, so it asks here after a
|
||||
reload; a 401 means signed out.
|
||||
"""
|
||||
return SessionOut(id=user.id, email=user.email, csrf_token=csrf_token_for(token))
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def logout(
|
||||
request: Request,
|
||||
user: User = Depends(get_current_user),
|
||||
session: Session = Depends(get_db),
|
||||
) -> Response:
|
||||
"""Revoke the caller's token so it stops working everywhere.
|
||||
|
||||
An account has a single active token, so this signs out every client
|
||||
that holds it: other browsers, API scripts and, for Telegram accounts,
|
||||
the bot (which re-registers on its next request). The new token is
|
||||
never returned; signing in again issues a fresh one.
|
||||
"""
|
||||
user.token_hash = token_hash(generate_token())
|
||||
session.commit()
|
||||
response = Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
_end_session(request, response)
|
||||
return response
|
||||
|
||||
|
||||
@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.
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -40,3 +40,13 @@ def generate_token() -> str:
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def csrf_token_for(token: str) -> str:
|
||||
"""The CSRF token bound to a session token (stateless double submit).
|
||||
|
||||
It is an HMAC keyed by the session token itself, so the server can
|
||||
recompute it from the cookie without storing anything, and a cross-site
|
||||
page that cannot read the cookie cannot derive it either.
|
||||
"""
|
||||
return hmac.new(token.encode("utf-8"), b"sokhan-csrf-v1", hashlib.sha256).hexdigest()
|
||||
@@ -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,17 @@ class Settings(BaseSettings):
|
||||
# Leave empty to disable the admin endpoints entirely.
|
||||
admin_api_key: str = ""
|
||||
|
||||
bot_api_secret: str = ""
|
||||
|
||||
# Dashboard session cookie (httpOnly). AUTH_COOKIE_SECURE=auto sets the
|
||||
# Secure attribute whenever the browser came in over HTTPS (directly or
|
||||
# via X-Forwarded-Proto); true/false force it. The web app proxies the
|
||||
# API under its own origin (/api), so SameSite=lax always applies; a
|
||||
# separately hosted API on another site needs "none" plus HTTPS.
|
||||
auth_cookie_secure: str = "auto"
|
||||
auth_cookie_samesite: str = "lax"
|
||||
auth_cookie_max_age_days: int = 30
|
||||
|
||||
# LLM summaries (optional, behind a feature flag)
|
||||
summary_enabled: bool = False
|
||||
llm_api_base: str = ""
|
||||
@@ -76,6 +102,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)
|
||||
|
||||
@@ -25,6 +25,14 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
|
||||
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
|
||||
|
||||
|
||||
class StorageUnavailableError(Exception):
|
||||
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
|
||||
|
||||
It is a server fault, not a bad upload, so the API answers 503 and the
|
||||
real OSError stays in the server log instead of reaching the client.
|
||||
"""
|
||||
|
||||
|
||||
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
|
||||
"""Decode any media file to mono float32 PCM at 16 kHz."""
|
||||
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
|
||||
@@ -102,12 +110,23 @@ def audio_dir() -> Path:
|
||||
|
||||
|
||||
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension."""
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension.
|
||||
|
||||
Raises StorageUnavailableError when the directory or file cannot be
|
||||
written; a partially written file is removed first.
|
||||
"""
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
|
||||
suffix = ".bin"
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
path.write_bytes(data)
|
||||
try:
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
except OSError as exc:
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
try:
|
||||
path.write_bytes(data)
|
||||
except OSError as exc:
|
||||
delete_audio(path)
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
return path
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Orthographic polish for Persian ASR output (v2 quality pass).
|
||||
|
||||
Whisper writes Persian reasonably but its orthography is sloppy: prefixes
|
||||
that belong behind a ZWNJ arrive as separate tokens ("می کنی"), the imperative
|
||||
prefix "ب" is mis-split into the real word "بی" ("بی پوش" for "بپوش"),
|
||||
Arabic look-alike code points leak through, and Latin digits appear in
|
||||
Persian sentences.
|
||||
|
||||
`polish_transcript` repairs exactly these surface forms — it never rewords
|
||||
(colloquial speech stays colloquial), so it is safe to apply to BOTH the
|
||||
reference and the hypothesis in WER evaluation (benchmarks v2) and to the
|
||||
product transcript in the pipeline. Every rule is deterministic and
|
||||
unit-tested (`tests/test_fa_polish.py`).
|
||||
|
||||
Not a fix for acoustic errors: when the model mishears a word no amount of
|
||||
text surgery recovers it — that is what bigger checkpoints are for (the
|
||||
measured stack: small 78.0% -> medium 59.8% WER, see benchmarks/).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
_ZWNJ = "\u200c"
|
||||
|
||||
# ---------------------------------------------------------------- characters
|
||||
|
||||
# Arabic-block look-alikes -> Persian. Deliberately does NOT touch alef
|
||||
# variants (آ أ إ) — polish is for display, unlike the search normalizer.
|
||||
_ARABIC_CHARS = {
|
||||
"\u064a": "\u06cc", # yeh -> farsi yeh
|
||||
"\u0649": "\u06cc", # alef maksura -> farsi yeh
|
||||
"\u0643": "\u06a9", # kaf -> keheh
|
||||
"\u0629": "\u0647", # teh marbuta -> heh
|
||||
"\u0640": "", # tatweel -> drop
|
||||
# Arabic-Indic digits -> Persian digits
|
||||
"\u0660": "\u06f0", "\u0661": "\u06f1", "\u0662": "\u06f2", "\u0663": "\u06f3",
|
||||
"\u0664": "\u06f4", "\u0665": "\u06f5", "\u0666": "\u06f6", "\u0667": "\u06f7",
|
||||
"\u0668": "\u06f8", "\u0669": "\u06f9",
|
||||
}
|
||||
|
||||
# Latin digits -> Persian digits (Persian-first product).
|
||||
_LATIN_DIGITS = {d: chr(0x06F0 + i) for i, d in enumerate("0123456789")}
|
||||
|
||||
# ------------------------------------------------------------------- lexicon
|
||||
|
||||
# Very common verbs Whisper writes without the ZWNJ: "میکنم" -> "میکنم".
|
||||
_ZWNJ_WORDS = {
|
||||
"میکنم", "میکنی", "میکند", "میکنیم", "میکنید", "میکنند",
|
||||
"میشوم", "میشوی", "میشود", "میشویم", "میشوید", "میشوند",
|
||||
"میگویم", "میگویی", "میگوید", "میگوییم", "میگویید", "میگویند",
|
||||
"میگم", "میگی", "میگه", "میگن",
|
||||
"میخواهم", "میخواهی", "میخواهد", "میخواهیم", "میخواهید", "میخواهند",
|
||||
"میخوام", "میخوای", "میخواد", "میخوان",
|
||||
"میدانم", "میدانی", "میداند", "میدانیم", "میدانید", "میدانند",
|
||||
"میدم", "میدی", "میده", "میدن",
|
||||
"میبرم", "میبری", "میبرد", "میبریم", "میبرید", "میبرند",
|
||||
"میرم", "میری", "میره", "میرن",
|
||||
"میروم", "میروی", "میرود", "میرویم", "میروید", "میروند",
|
||||
"میآیم", "میآیی", "میآید", "میآییم", "میآیید", "میآیند",
|
||||
"میشنوم", "میشنوی", "میشنود", "میشنویم", "میشنوید", "میشنوند",
|
||||
"میبینم", "میبینی", "میبیند", "میبینیم", "میبینید", "میبینند",
|
||||
"میشه",
|
||||
"نمیکنم", "نمیکنی", "نمیکند", "نمیکنیم", "نمیکنید", "نمیکنند",
|
||||
"نمیشود", "نمیشه",
|
||||
"نمیگویم", "نمیگم", "نمیگی", "نمیگه", "نمیگن",
|
||||
"نمیخواهم", "نمیخواهد", "نمیخوام", "نمیخواد",
|
||||
"نمیدانم", "نمیدانی", "نمیداند",
|
||||
"نمیدونم", "نمیدونی", "نمیدونه", "نمیدونن",
|
||||
"نمیدم", "نمیدی", "نمیده", "نمیدن",
|
||||
"نمیرم", "نمیری", "نمیره", "نمیرن", "نمیرود",
|
||||
"نمیآید", "نمیاد",
|
||||
"نمیبینم", "نمیبینی", "نمیبیند",
|
||||
}
|
||||
|
||||
# The imperative "ب" is frequently mis-heard as the real word "بی" and
|
||||
# emitted as its own token: "بپوش ببین" -> "بی پوش بی بین". Only
|
||||
# unambiguous imperatives are repaired, and only right after "بی"/"به".
|
||||
_SPLIT_IMPERATIVES = {
|
||||
"پوش": "بپوش",
|
||||
"بین": "ببین",
|
||||
"بینم": "ببینم",
|
||||
"بینی": "ببینی",
|
||||
"بینید": "ببینید",
|
||||
"بینند": "ببینند",
|
||||
"خواب": "بخواب",
|
||||
"خور": "بخور",
|
||||
"شین": "بشین",
|
||||
"نشین": "بنشین",
|
||||
"گیر": "بگیر",
|
||||
"گو": "بگو",
|
||||
"گوی": "بگو",
|
||||
"بخش": "ببخش",
|
||||
}
|
||||
|
||||
# Separated ZWNJ prefixes: "می کنم" -> "میکنم" (fused with the next token).
|
||||
_FUSED_PREFIXES = {
|
||||
"می کنم": "میکنم", "می کنی": "میکنی", "می کند": "میکند",
|
||||
"می کنیم": "میکنیم", "می کنید": "میکنید", "می کنند": "میکنند",
|
||||
"می شود": "میشود", "می شن": "میشن", "می شه": "میشه",
|
||||
"می گویم": "میگویم", "می گویی": "میگویی", "می گوید": "میگوید",
|
||||
"می گوییم": "میگوییم", "می گویید": "میگویید", "می گویند": "میگویند",
|
||||
"می گم": "میگم", "می گی": "میگی", "می گه": "میگه", "می گن": "میگن",
|
||||
"می خواهم": "میخواهم", "می خواهی": "میخواهی", "می خواهد": "میخواهد",
|
||||
"می خواهیم": "میخواهیم", "می خواهید": "میخواهید", "می خواهند": "میخواهند",
|
||||
"می خوام": "میخوام", "می خوای": "میخوای", "می خواد": "میخواد",
|
||||
"می دانم": "میدانم", "می دانی": "میدانی", "می داند": "میداند",
|
||||
"می دونم": "میدونم", "می دونی": "میدونی", "می دونه": "میدونه",
|
||||
"می دم": "میدم", "می دی": "میدی", "می ده": "میده", "می دن": "میدن",
|
||||
"می برم": "میبرم", "می برد": "میبرد",
|
||||
"می رم": "میرم", "می ری": "میری", "می ره": "میره", "می رن": "میرن",
|
||||
"می روم": "میروم", "می رود": "میرود",
|
||||
"می آیم": "میآیم", "می آید": "میآید", "می این": "میاین",
|
||||
"می شنوم": "میشنوم", "می شنوی": "میشنوی", "می شنود": "میشنود",
|
||||
"می بینم": "میبینم", "می بینی": "میبینی", "می بیند": "میبیند",
|
||||
"نمی کنم": "نمیکنم", "نمی کنی": "نمیکنی", "نمی کند": "نمیکند",
|
||||
"نمی شود": "نمیشود", "نمی شه": "نمیشه",
|
||||
"نمی گم": "نمیگم", "نمی گی": "نمیگی", "نمی گه": "نمیگه",
|
||||
"نمی خوام": "نمیخوام", "نمی خواد": "نمیخواد",
|
||||
"نمی دانم": "نمیدانم", "نمی داند": "نمیداند",
|
||||
"نمی دونم": "نمیدونم",
|
||||
"نمی رم": "نمیرم", "نمی ره": "نمیره",
|
||||
"نمی آید": "نمیآید", "نمی این": "نمیاین",
|
||||
"نمی بینم": "نمیبینم", "نمی بیند": "نمیبیند",
|
||||
}
|
||||
|
||||
_PREFIX_TOKENS = ("می", "نمی")
|
||||
|
||||
# Separated ZWNJ suffixes: "پروانه های" -> "پروانههای" (fused with previous).
|
||||
_SUFFIX_TOKENS = ("ها", "های", "هایی", "تر", "ترین")
|
||||
|
||||
# Punctuation marks that swallow the space BEFORE them (closing marks only —
|
||||
# opening « and ( keep their leading space).
|
||||
_CLOSING_PUNCT = "،؛:.!?؟…»)"
|
||||
|
||||
# ----------------------------------------------------------------- pipeline
|
||||
|
||||
|
||||
def _fix_chars(text: str) -> str:
|
||||
out: list[str] = []
|
||||
for ch in text:
|
||||
if ch in _ARABIC_CHARS:
|
||||
out.append(_ARABIC_CHARS[ch])
|
||||
elif ch in _LATIN_DIGITS:
|
||||
out.append(_LATIN_DIGITS[ch])
|
||||
else:
|
||||
out.append(ch)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _split_edges(token: str) -> tuple[str, str, str]:
|
||||
"""Split a token into (leading punct, core, trailing punct)."""
|
||||
core = token.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if not core:
|
||||
return token, "", ""
|
||||
start = token.index(core)
|
||||
return token[:start], core, token[start + len(core):]
|
||||
|
||||
|
||||
def _zwnj_in_word(word: str) -> str:
|
||||
"""Insert the ZWNJ after a leading می/نمی prefix inside one token."""
|
||||
if word.startswith("نمی") and len(word) > 3:
|
||||
return "نمی" + _ZWNJ + word[3:]
|
||||
if word.startswith("می") and len(word) > 2:
|
||||
return "می" + _ZWNJ + word[2:]
|
||||
return word
|
||||
|
||||
|
||||
def _fix_tokens(text: str) -> str:
|
||||
tokens = text.split()
|
||||
fixed: list[str] = []
|
||||
for token in tokens:
|
||||
leading, core, trailing = _split_edges(token)
|
||||
if not core:
|
||||
fixed.append(token)
|
||||
continue
|
||||
if core in _ZWNJ_WORDS:
|
||||
core = _zwnj_in_word(core)
|
||||
fixed.append(leading + core + trailing)
|
||||
# Split-imperative repair needs the previous token, so run after folding.
|
||||
fused = _fuse(fixed)
|
||||
repaired: list[str] = []
|
||||
for token in fused.split():
|
||||
_leading, core, _trailing = _split_edges(token)
|
||||
if (
|
||||
core in _SPLIT_IMPERATIVES
|
||||
and repaired
|
||||
and repaired[-1].strip("،؛:.!?؟…«»()\"'-–—,") in ("بی", "به")
|
||||
):
|
||||
repaired[-1] = _SPLIT_IMPERATIVES[core]
|
||||
continue
|
||||
repaired.append(token)
|
||||
return " ".join(repaired)
|
||||
|
||||
|
||||
def _fuse(tokens: list[str]) -> str:
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
while i < len(tokens):
|
||||
tok = tokens[i]
|
||||
bare = tok.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if bare in _PREFIX_TOKENS and i + 1 < len(tokens):
|
||||
pair = f"{tok} {tokens[i + 1]}"
|
||||
fused = _FUSED_PREFIXES.get(pair)
|
||||
if fused is None and bare == tok: # no punctuation on the prefix
|
||||
fused = tok + _ZWNJ + tokens[i + 1]
|
||||
if fused is not None:
|
||||
out.append(fused)
|
||||
i += 2
|
||||
continue
|
||||
if bare in _SUFFIX_TOKENS and out:
|
||||
prev = out[-1]
|
||||
prev_core = prev.strip("،؛:.!?؟…«»()\"'-–—,")
|
||||
if prev_core and prev_core[-1].isalpha():
|
||||
if bare == tok: # no punctuation on the suffix itself
|
||||
out[-1] = prev + _ZWNJ + bare
|
||||
else:
|
||||
out[-1] = prev + _ZWNJ + bare
|
||||
i += 1
|
||||
continue
|
||||
out.append(tok)
|
||||
i += 1
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def _fix_spacing(text: str) -> str:
|
||||
"""No space before a closing mark, one space after (digit-safe)."""
|
||||
text = text.replace(_ZWNJ + " ", _ZWNJ).replace(" " + _ZWNJ, _ZWNJ)
|
||||
out: list[str] = []
|
||||
for i, ch in enumerate(text):
|
||||
if ch in _CLOSING_PUNCT and out and out[-1] == " ":
|
||||
out.pop()
|
||||
out.append(ch)
|
||||
nxt = text[i + 1] if i + 1 < len(text) else ""
|
||||
if ch in _CLOSING_PUNCT and nxt and nxt not in _CLOSING_PUNCT and nxt != " ":
|
||||
# 3.5 / ۱۲٫۵ keep the dot glued to both digits
|
||||
if not (ch in ".،" and out[-2:-1] and out[-2].isdigit() and nxt.isdigit()):
|
||||
out.append(" ")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def polish_transcript(text: str) -> str:
|
||||
"""Repair Persian ASR orthography without rewording. Deterministic."""
|
||||
if not text or not text.strip():
|
||||
return text
|
||||
polished = _fix_chars(text)
|
||||
polished = _fix_tokens(polished)
|
||||
polished = _fix_spacing(polished)
|
||||
return polished.strip()
|
||||
@@ -5,7 +5,8 @@ puts the transcript back into publishable shape with three conservative,
|
||||
deterministic rule families — no model call, no LLM dependency:
|
||||
|
||||
1. Script fix: the Latin comma, question mark and semicolon become their
|
||||
Persian counterparts (، ؟ ؛).
|
||||
Persian counterparts (، ؟ ؛). A comma that groups digits ("1,000",
|
||||
"12,500,000") is a thousands separator, not punctuation, and is kept.
|
||||
2. Spacing: no space *before* punctuation, exactly one space *after* clause
|
||||
and sentence punctuation. `.` and `:` are deliberately left alone so
|
||||
decimals ("3.5") and clock times ("12:30") survive.
|
||||
@@ -26,6 +27,12 @@ import re
|
||||
# Latin forms that should not survive in a Persian transcript.
|
||||
_LATIN_TO_PERSIAN = str.maketrans({",": "،", "?": "؟", ";": "؛"})
|
||||
|
||||
# A comma between a digit and exactly three more digits groups a number.
|
||||
# \d matches Persian digits too, so "۱,۲۰۰" is covered.
|
||||
_THOUSANDS_COMMA = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")
|
||||
# Stands in for a thousands comma while the Latin marks are translated.
|
||||
_KEPT_COMMA = "\x00"
|
||||
|
||||
_CLAUSE = "،؛"
|
||||
_SENTENCE_END = "؟!…."
|
||||
_PUNCT_CHARS = _CLAUSE + _SENTENCE_END + ":."
|
||||
@@ -73,7 +80,8 @@ def _has_terminal(text: str) -> bool:
|
||||
|
||||
def restore_punctuation(text: str) -> str:
|
||||
"""Return `text` with Persian punctuation restored; safe to re-apply."""
|
||||
cleaned = text.translate(_LATIN_TO_PERSIAN).strip()
|
||||
cleaned = _THOUSANDS_COMMA.sub(_KEPT_COMMA, text)
|
||||
cleaned = cleaned.translate(_LATIN_TO_PERSIAN).replace(_KEPT_COMMA, ",").strip()
|
||||
cleaned = _SPACE_BEFORE.sub(r"\1", cleaned)
|
||||
cleaned = _SPACE_AFTER.sub(r"\1 ", cleaned)
|
||||
cleaned = _WS_RUNS.sub(" ", cleaned).strip()
|
||||
|
||||
@@ -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)
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
@@ -36,15 +37,30 @@ class Segment:
|
||||
speaker: str | None = None
|
||||
|
||||
|
||||
# Called with the fraction (0..1) of the current chunk decoded so far.
|
||||
ProgressCallback = Callable[[float], None]
|
||||
|
||||
|
||||
class Transcriber(Protocol):
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
) -> list[Segment]: ...
|
||||
|
||||
|
||||
def reports_progress(engine: object) -> bool:
|
||||
"""Whether `engine.transcribe` accepts an `on_progress` callback.
|
||||
|
||||
Opt-in via a class attribute, so third-party engines and test doubles
|
||||
with the plain three-argument signature keep working unchanged.
|
||||
"""
|
||||
return bool(getattr(engine, "reports_progress", False))
|
||||
|
||||
|
||||
class FasterWhisperTranscriber:
|
||||
"""Chunk-local transcription with faster-whisper."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_size: str | None = None,
|
||||
@@ -73,7 +89,11 @@ class FasterWhisperTranscriber:
|
||||
return self._model
|
||||
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
self,
|
||||
samples: np.ndarray,
|
||||
sample_rate: int,
|
||||
language: str,
|
||||
on_progress: ProgressCallback | None = None,
|
||||
) -> list[Segment]:
|
||||
model = self._load()
|
||||
settings = get_settings()
|
||||
@@ -86,8 +106,13 @@ class FasterWhisperTranscriber:
|
||||
if language and language != "auto":
|
||||
options["language"] = language
|
||||
segments_iter, _info = model.transcribe(samples, **options) # type: ignore[arg-type]
|
||||
chunk_seconds = len(samples) / sample_rate
|
||||
segments: list[Segment] = []
|
||||
# faster-whisper decodes lazily, segment by segment, so each step of
|
||||
# this loop is real work done: report how far into the chunk it is.
|
||||
for segment in segments_iter:
|
||||
if on_progress is not None and chunk_seconds > 0:
|
||||
on_progress(min(1.0, float(segment.end) / chunk_seconds))
|
||||
text = segment.text.strip()
|
||||
if not text:
|
||||
continue
|
||||
@@ -107,8 +132,14 @@ class FasterWhisperTranscriber:
|
||||
class FakeTranscriber:
|
||||
"""Deterministic engine for tests: one or two fixed Persian segments."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
self,
|
||||
samples: np.ndarray,
|
||||
sample_rate: int,
|
||||
language: str,
|
||||
on_progress: ProgressCallback | None = None,
|
||||
) -> list[Segment]:
|
||||
duration = len(samples) / sample_rate
|
||||
segments: list[Segment] = []
|
||||
@@ -132,6 +163,9 @@ class FakeTranscriber:
|
||||
confidence=0.741,
|
||||
)
|
||||
)
|
||||
if on_progress is not None and duration > 0:
|
||||
for segment in segments:
|
||||
on_progress(min(1.0, segment.end / duration))
|
||||
return segments
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
+27
-2
@@ -10,11 +10,14 @@ import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from sokhan import __version__
|
||||
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir
|
||||
from sokhan.db import configure, create_all
|
||||
|
||||
logger = logging.getLogger("sokhan")
|
||||
@@ -27,6 +30,14 @@ def create_app() -> FastAPI:
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
configure()
|
||||
create_all()
|
||||
try:
|
||||
audio_dir()
|
||||
except OSError as exc:
|
||||
logger.error(
|
||||
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
|
||||
"it is; in Docker check the volume is owned by the app user",
|
||||
exc,
|
||||
)
|
||||
if not settings.celery_enabled:
|
||||
logger.warning(
|
||||
"CELERY_ENABLED=false - jobs run inline in the API process; "
|
||||
@@ -52,10 +63,16 @@ 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,
|
||||
allow_credentials=False,
|
||||
# The dashboard's session cookie rides on credentialed requests; the
|
||||
# origins above are an explicit list, never a wildcard.
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -68,6 +85,14 @@ def create_app() -> FastAPI:
|
||||
app.include_router(routes_openai.router)
|
||||
app.include_router(routes_admin.router)
|
||||
|
||||
@app.exception_handler(StorageUnavailableError)
|
||||
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
|
||||
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
content={"detail": "upload storage is unavailable, try again later"},
|
||||
)
|
||||
|
||||
@app.get("/")
|
||||
def root() -> dict:
|
||||
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
|
||||
|
||||
@@ -9,6 +9,15 @@ class AuthResponse(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
api_token: str
|
||||
# Sent back as X-CSRF-Token on cookie-authenticated writes; absent for
|
||||
# flows that set no cookie (the Telegram bot).
|
||||
csrf_token: str | None = None
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
csrf_token: str
|
||||
|
||||
|
||||
class JobCreated(BaseModel):
|
||||
|
||||
@@ -19,6 +19,7 @@ never hold a transaction open.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
@@ -35,12 +36,13 @@ 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
|
||||
from sokhan.core.quota import record_usage
|
||||
from sokhan.core.summary import Summarizer, get_summarizer
|
||||
from sokhan.core.transcribe import Transcriber, get_transcriber
|
||||
from sokhan.core.transcribe import Transcriber, get_transcriber, reports_progress
|
||||
from sokhan.core.webhooks import build_payload, fire_job_callback
|
||||
from sokhan.db import session_scope
|
||||
from sokhan.diarization import Diarizer, SpeakerTurn, get_diarizer, label_segments
|
||||
@@ -49,6 +51,11 @@ from sokhan.models import Job, JobStatus, Segment, utcnow
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Clock for throttling progress writes; a module attribute so tests can
|
||||
# swap it without patching the process-wide `time.monotonic`.
|
||||
_progress_clock = time.monotonic
|
||||
|
||||
|
||||
def process_job(
|
||||
job_id: str,
|
||||
transcriber: Transcriber | None = None,
|
||||
@@ -122,11 +129,38 @@ def process_job(
|
||||
|
||||
chunk_segments = []
|
||||
chunk_starts = []
|
||||
last_saved_at = float("-inf")
|
||||
|
||||
def save_progress(value: float) -> None:
|
||||
"""Persist mid-chunk progress: monotonic, below 100, ~1/s."""
|
||||
nonlocal last_saved_at
|
||||
value = min(99.0, round(value, 1))
|
||||
now = _progress_clock()
|
||||
if value <= (job.progress or 0.0) or now - last_saved_at < 1.0:
|
||||
return
|
||||
job.progress = value
|
||||
session.commit()
|
||||
last_saved_at = now
|
||||
|
||||
for position, chunk in enumerate(chunk_source, start=1):
|
||||
chunk_starts.append(chunk.start)
|
||||
chunk_segments.append(
|
||||
engine.transcribe(chunk.samples, SAMPLE_RATE, job.language)
|
||||
)
|
||||
|
||||
def chunk_progress(
|
||||
fraction: float, position: int = position, chunk: Chunk = chunk
|
||||
) -> None:
|
||||
if chunk_total is not None:
|
||||
save_progress((position - 1 + fraction) / chunk_total * 100.0)
|
||||
elif estimated_duration:
|
||||
done = chunk.start + fraction * (chunk.end - chunk.start)
|
||||
save_progress(done / estimated_duration * 99.0)
|
||||
|
||||
if reports_progress(engine):
|
||||
segments = engine.transcribe( # type: ignore[call-arg]
|
||||
chunk.samples, SAMPLE_RATE, job.language, on_progress=chunk_progress
|
||||
)
|
||||
else:
|
||||
segments = engine.transcribe(chunk.samples, SAMPLE_RATE, job.language)
|
||||
chunk_segments.append(segments)
|
||||
if chunk_total is not None:
|
||||
job.progress = round(position / chunk_total * 100.0, 1)
|
||||
elif estimated_duration:
|
||||
@@ -159,6 +193,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))
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import pytest
|
||||
|
||||
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
|
||||
|
||||
@@ -51,14 +52,80 @@ 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
|
||||
|
||||
|
||||
def _bearer(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_logout_revokes_the_token(client):
|
||||
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
assert client.get("/quota", headers=_bearer(token)).status_code == 200
|
||||
|
||||
response = client.post("/auth/logout", headers=_bearer(token))
|
||||
|
||||
assert response.status_code == 204
|
||||
assert client.get("/quota", headers=_bearer(token)).status_code == 401
|
||||
# The revoked token is no longer a valid connect code either.
|
||||
assert client.post("/auth/token-login", json={"api_token": token}).status_code == 401
|
||||
|
||||
|
||||
def test_logout_twice_with_the_same_token_is_rejected(client):
|
||||
token = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
client.post("/auth/logout", headers=_bearer(token))
|
||||
|
||||
assert client.post("/auth/logout", headers=_bearer(token)).status_code == 401
|
||||
|
||||
|
||||
def test_logout_requires_a_token(client):
|
||||
assert client.post("/auth/logout").status_code == 401
|
||||
|
||||
|
||||
def test_signing_in_after_logout_issues_a_working_token(client):
|
||||
first = client.post("/auth/register", json=REGISTER).json()["api_token"]
|
||||
client.post("/auth/logout", headers=_bearer(first))
|
||||
|
||||
second = client.post("/auth/login", json=REGISTER).json()["api_token"]
|
||||
|
||||
assert second != first
|
||||
assert client.get("/quota", headers=_bearer(second)).status_code == 200
|
||||
@@ -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"
|
||||
@@ -0,0 +1,113 @@
|
||||
"""httpOnly cookie sessions for the dashboard, with CSRF on writes (#33)."""
|
||||
|
||||
import pytest
|
||||
from sokhan.auth import csrf_token_for
|
||||
from sokhan.config import get_settings
|
||||
|
||||
CREDENTIALS = {"email": "nima@example.com", "password": "parool-1234"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cookie_client(client, monkeypatch):
|
||||
"""The test client speaks plain http, which never sends Secure cookies."""
|
||||
monkeypatch.setenv("AUTH_COOKIE_SECURE", "false")
|
||||
get_settings.cache_clear()
|
||||
return client
|
||||
|
||||
|
||||
def _sign_in(client) -> dict:
|
||||
client.post("/auth/register", json=CREDENTIALS)
|
||||
return client.post("/auth/login", json=CREDENTIALS).json()
|
||||
|
||||
|
||||
def test_login_sets_an_httponly_session_cookie(cookie_client):
|
||||
response = cookie_client.post("/auth/register", json=CREDENTIALS)
|
||||
|
||||
cookie = response.headers["set-cookie"]
|
||||
assert cookie.startswith("sokhan_session=")
|
||||
assert "HttpOnly" in cookie
|
||||
assert "SameSite=lax" in cookie
|
||||
body = response.json()
|
||||
assert body["csrf_token"] == csrf_token_for(body["api_token"])
|
||||
|
||||
|
||||
def test_cookie_secure_follows_the_scheme_by_default(client):
|
||||
# Plain http: a Secure cookie would be dropped by the browser.
|
||||
plain = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"]
|
||||
assert "Secure" not in plain
|
||||
|
||||
# HTTPS terminated by a reverse proxy in front of the API.
|
||||
behind_tls = client.post(
|
||||
"/auth/login", json=CREDENTIALS, headers={"X-Forwarded-Proto": "https"}
|
||||
).headers["set-cookie"]
|
||||
assert "Secure" in behind_tls
|
||||
|
||||
|
||||
def test_cookie_secure_can_be_forced(client, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_COOKIE_SECURE", "true")
|
||||
get_settings.cache_clear()
|
||||
|
||||
cookie = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"]
|
||||
|
||||
assert "Secure" in cookie
|
||||
|
||||
|
||||
def test_cookie_authenticates_reads_without_a_bearer_header(cookie_client):
|
||||
_sign_in(cookie_client)
|
||||
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
session = cookie_client.get("/auth/session")
|
||||
assert session.status_code == 200
|
||||
assert session.json()["email"] == CREDENTIALS["email"]
|
||||
|
||||
|
||||
def test_cookie_writes_need_the_csrf_header(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
missing = cookie_client.post("/auth/logout")
|
||||
wrong = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": "forged"})
|
||||
|
||||
assert missing.status_code == 403
|
||||
assert wrong.status_code == 403
|
||||
# The session survived both forged attempts.
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
|
||||
ok = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
assert ok.status_code == 204
|
||||
|
||||
|
||||
def test_logout_clears_the_cookie_and_revokes_the_token(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
response = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
|
||||
assert 'sokhan_session=""' in response.headers["set-cookie"]
|
||||
assert cookie_client.get("/auth/session").status_code == 401
|
||||
bearer = {"Authorization": f"Bearer {body['api_token']}"}
|
||||
assert cookie_client.get("/quota", headers=bearer).status_code == 401
|
||||
|
||||
|
||||
def test_bearer_clients_need_no_csrf_token(client):
|
||||
token = client.post("/auth/register", json=CREDENTIALS).json()["api_token"]
|
||||
client.cookies.clear()
|
||||
bearer = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
assert client.get("/auth/session", headers=bearer).status_code == 200
|
||||
assert client.post("/auth/logout", headers=bearer).status_code == 204
|
||||
|
||||
|
||||
def test_session_without_any_credentials_is_401(client):
|
||||
assert client.get("/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_telegram_flow_sets_no_cookie(client, monkeypatch):
|
||||
monkeypatch.setenv("BOT_API_SECRET", "s3cret")
|
||||
get_settings.cache_clear()
|
||||
|
||||
response = client.post(
|
||||
"/auth/telegram", json={"telegram_id": 7}, headers={"X-Bot-Secret": "s3cret"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "set-cookie" not in response.headers
|
||||
assert response.json()["csrf_token"] is None
|
||||
@@ -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(" ") == " "
|
||||
@@ -1,5 +1,8 @@
|
||||
import io
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from docx import Document
|
||||
|
||||
|
||||
@@ -188,3 +191,51 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
|
||||
|
||||
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
|
||||
assert client.get("/jobs", headers=headers).json()["total"] == 0
|
||||
|
||||
|
||||
def _make_data_dir_unwritable(tmp_path):
|
||||
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
|
||||
shutil.rmtree(tmp_path / "data")
|
||||
(tmp_path / "data").write_text("not a directory")
|
||||
|
||||
|
||||
def test_upload_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = _upload(client, auth, wav_bytes)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
|
||||
# No job row is left behind for an upload that was never stored.
|
||||
assert client.get("/jobs", headers=auth).json()["total"] == 0
|
||||
|
||||
|
||||
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = client.post(
|
||||
"/v1/audio/transcriptions",
|
||||
files={"file": ("test.wav", wav_bytes, "audio/wav")},
|
||||
data={"language": "fa", "response_format": "json"},
|
||||
headers=auth,
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
|
||||
|
||||
def write_fails_midway(self, data):
|
||||
self.open("wb").write(data[:1])
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
|
||||
|
||||
with pytest.raises(StorageUnavailableError):
|
||||
save_upload(b"RIFF....", "job-1", "clip.wav")
|
||||
assert list(audio_dir().iterdir()) == []
|
||||
@@ -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
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Job progress moves while a chunk is being decoded, not only between chunks.
|
||||
|
||||
A clip shorter than the 30 s window is a single chunk, so chunk-level
|
||||
progress alone sat at 0% for the whole job and then jumped to 100%.
|
||||
"""
|
||||
|
||||
import sokhan.db as db
|
||||
from sokhan.core.transcribe import FakeTranscriber, Segment, reports_progress
|
||||
from sokhan.models import Job
|
||||
|
||||
|
||||
class SlowEngine:
|
||||
"""Reports four steps through the chunk and records what the DB shows."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.seen: list[float] = []
|
||||
|
||||
def transcribe(self, samples, sample_rate, language, on_progress=None):
|
||||
for fraction in (0.25, 0.5, 0.75, 1.0):
|
||||
on_progress(fraction)
|
||||
with db.session_scope() as other:
|
||||
job = other.query(Job).one()
|
||||
self.seen.append(job.progress)
|
||||
return [Segment(start=0.0, end=1.0, text="سلام")]
|
||||
|
||||
|
||||
class PlainEngine:
|
||||
"""A third-party engine with the original three-argument signature."""
|
||||
|
||||
def transcribe(self, samples, sample_rate, language):
|
||||
return [Segment(start=0.0, end=1.0, text="سلام")]
|
||||
|
||||
|
||||
def _upload(client, auth, wav_bytes):
|
||||
response = client.post(
|
||||
"/jobs",
|
||||
files={"file": ("clip.wav", wav_bytes, "audio/wav")},
|
||||
data={"language": "fa"},
|
||||
headers=auth,
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
def test_progress_is_saved_inside_a_single_chunk(
|
||||
client, auth, wav_bytes, wait_for_job, monkeypatch
|
||||
):
|
||||
engine = SlowEngine()
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: engine)
|
||||
ticks = iter(range(0, 1000, 2)) # every call is 2 s later: never throttled
|
||||
monkeypatch.setattr("sokhan.worker.pipeline._progress_clock", lambda: float(next(ticks)))
|
||||
|
||||
job_id = _upload(client, auth, wav_bytes)
|
||||
wait_for_job(client, auth, job_id)
|
||||
|
||||
assert engine.seen == sorted(engine.seen)
|
||||
assert 0 < engine.seen[0] < engine.seen[-1] <= 99.0
|
||||
assert client.get(f"/jobs/{job_id}", headers=auth).json()["progress"] == 100.0
|
||||
|
||||
|
||||
def test_progress_writes_are_throttled(client, auth, wav_bytes, wait_for_job, monkeypatch):
|
||||
engine = SlowEngine()
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: engine)
|
||||
monkeypatch.setattr("sokhan.worker.pipeline._progress_clock", lambda: 5.0)
|
||||
|
||||
wait_for_job(client, auth, _upload(client, auth, wav_bytes))
|
||||
|
||||
# Same instant for every report: only the first one reaches the database.
|
||||
assert len(set(engine.seen)) == 1
|
||||
|
||||
|
||||
def test_engines_without_progress_support_still_work(
|
||||
client, auth, wav_bytes, wait_for_job, monkeypatch
|
||||
):
|
||||
assert not reports_progress(PlainEngine())
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: PlainEngine())
|
||||
|
||||
job_id = _upload(client, auth, wav_bytes)
|
||||
|
||||
assert wait_for_job(client, auth, job_id)["status"] == "completed"
|
||||
|
||||
|
||||
def test_fake_engine_reports_fractions_up_to_the_end():
|
||||
seen: list[float] = []
|
||||
import numpy as np
|
||||
|
||||
FakeTranscriber().transcribe(np.zeros(16000 * 4, dtype=np.float32), 16000, "fa", seen.append)
|
||||
|
||||
assert seen == sorted(seen) and seen[-1] == 1.0
|
||||
@@ -51,3 +51,60 @@ def test_empty_and_whitespace_input_stay_empty():
|
||||
def test_statement_with_colon_gets_no_double_mark():
|
||||
assert restore_punctuation("این است") == "این است."
|
||||
assert restore_punctuation("این است:") == "این است:"
|
||||
|
||||
|
||||
# Edge cases from #30. Each test pins the behavior on real-world input; the
|
||||
# comments say why that behavior is the right one for a transcript.
|
||||
|
||||
|
||||
def test_slash_dates_are_left_intact():
|
||||
# `/` is not punctuation to this pass, so date groups never get spaced
|
||||
# or split, in Persian and in Latin digits alike.
|
||||
assert restore_punctuation("تاریخ ۱۴۰۴/۰۹/۰۲ است") == "تاریخ ۱۴۰۴/۰۹/۰۲ است."
|
||||
assert restore_punctuation("جلسه 2026/11/23 برگزار شد") == "جلسه 2026/11/23 برگزار شد."
|
||||
assert restore_punctuation("نسبت ۱/۲ است") == "نسبت ۱/۲ است."
|
||||
|
||||
|
||||
def test_latin_digits_and_words_inside_persian_sentences():
|
||||
assert restore_punctuation("۳ دستگاه RTX 4090 خریدیم") == "۳ دستگاه RTX 4090 خریدیم."
|
||||
assert restore_punctuation("قیمت ۳.۵ میلیون شد") == "قیمت ۳.۵ میلیون شد."
|
||||
assert restore_punctuation("نسخه 1.4.1 منتشر شد") == "نسخه 1.4.1 منتشر شد."
|
||||
assert restore_punctuation("ساعت ۱۲:۳۰ بیا") == "ساعت ۱۲:۳۰ بیا."
|
||||
|
||||
|
||||
def test_thousands_separators_are_not_turned_into_persian_commas():
|
||||
# A Latin comma followed by exactly three digits groups a number; turning
|
||||
# it into ، and spacing it ("1، 000") would split one number into two.
|
||||
assert restore_punctuation("قیمت 1,000 دلار شد") == "قیمت 1,000 دلار شد."
|
||||
assert restore_punctuation("جمعیت 12,500,000 نفر") == "جمعیت 12,500,000 نفر."
|
||||
assert restore_punctuation("مبلغ ۱,۲۰۰ تومان") == "مبلغ ۱,۲۰۰ تومان."
|
||||
|
||||
|
||||
def test_comma_between_numbers_that_is_not_grouping_stays_a_list_separator():
|
||||
assert restore_punctuation("RTX 4090,4080 و 3090") == "RTX 4090، 4080 و 3090."
|
||||
assert restore_punctuation("اعداد 1,2 و 3") == "اعداد 1، 2 و 3."
|
||||
|
||||
|
||||
def test_abbreviation_dots_are_kept_and_end_the_segment():
|
||||
# A trailing dot already counts as terminal punctuation, so nothing is
|
||||
# appended; a dot in the middle is left alone like a decimal point.
|
||||
assert restore_punctuation("Dr.") == "Dr."
|
||||
assert restore_punctuation("با Dr. Smith صحبت کردم") == "با Dr. Smith صحبت کردم."
|
||||
assert restore_punctuation("با دکتر. احمدی") == "با دکتر. احمدی."
|
||||
|
||||
|
||||
def test_ellipsis_forms_are_terminal_and_tightened():
|
||||
assert restore_punctuation("صبر کن…") == "صبر کن…"
|
||||
assert restore_punctuation("نمیدونم...") == "نمیدونم..."
|
||||
assert restore_punctuation("صبر کن ... بعد") == "صبر کن... بعد."
|
||||
# A trailing-off question keeps its ellipsis instead of gaining a ؟.
|
||||
assert restore_punctuation("کی میای...") == "کی میای..."
|
||||
|
||||
|
||||
def test_repeated_and_mixed_marks_are_preserved():
|
||||
# Repetition carries the speaker's emphasis; the pass only converts the
|
||||
# script of Latin marks and never collapses them.
|
||||
assert restore_punctuation("وای!!!") == "وای!!!"
|
||||
assert restore_punctuation("چرا!!!") == "چرا!!!"
|
||||
assert restore_punctuation("چی؟؟") == "چی؟؟"
|
||||
assert restore_punctuation("واقعا?!") == "واقعا؟!"
|
||||
@@ -42,5 +42,9 @@ def test_models_missing_from_baseline_are_ignored():
|
||||
def test_load_baseline_reads_the_committed_file():
|
||||
path = os.path.join(BENCHMARKS_DIR, "results", "baseline.json")
|
||||
baseline = regression.load_baseline(path)
|
||||
assert abs(baseline["small"] - 0.8049) < 1e-9
|
||||
assert abs(baseline["Abol0pati/whisper-small-fa-sokhan"] - 0.7927) < 1e-9
|
||||
# v2 stack (orthography prompt + fa_polish on both sides); the numbers
|
||||
# must match benchmarks/results/baseline.json — regenerate that file via
|
||||
# benchmarks/benchmark_wer.py whenever the stack changes.
|
||||
assert abs(baseline["small"] - 0.75) < 1e-9
|
||||
assert abs(baseline["Abol0pati/whisper-small-fa-sokhan"] - 0.75) < 1e-9
|
||||
assert abs(baseline["medium"] - 0.5625) < 1e-9
|
||||
@@ -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)
|
||||
@@ -29,6 +29,43 @@ measured back to back in one session, same library versions
|
||||
| Abol0pati/whisper-tiny-fa-sokhan (fine-tuned, CPU run) | 39 M | 103.7% | 47.4% |
|
||||
| **Abol0pati/whisper-small-fa-sokhan (fine-tuned, GPU run)** | 244 M | **79.3%** | **24.9%** |
|
||||
|
||||
The table above is the **v1 harness** (no prompt, `normalize_persian` only).
|
||||
The **v2 accuracy stack** changes two things, each measured in isolation
|
||||
with [tune_decode.py](tune_decode.py):
|
||||
|
||||
1. **Persian orthography initial prompt** — whisper copies the script style
|
||||
of the prompt, so a ZWNJ-correct Persian prompt nudges the decoder
|
||||
towards standard written forms: −1.3 WER points on `small` (79.3% →
|
||||
78.0%), −4.8 on the fine-tuned checkpoint (76.8% → 72.0%), both under
|
||||
the sweep harness with the same normalization.
|
||||
2. **`fa_polish` orthographic post-processing** (same module the backend
|
||||
pipeline applies) on both sides: −3.6 WER points.
|
||||
|
||||
v2 numbers (prompt + polish, both sides, CPU int8, beam 5 — from
|
||||
[results/results.json](results/results.json), regenerated by the same
|
||||
command):
|
||||
|
||||
| Model | Params | WER (v2) | CER (v2) | Wall time |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| small | 244 M | 75.0% | 25.0% | 24.7 s |
|
||||
| Abol0pati/whisper-small-fa-sokhan (fine-tuned) | 244 M | 75.0% | 31.0% | 25.3 s |
|
||||
| **medium (new backend default)** | 769 M | **56.2%** | **18.5%** | 75.5 s |
|
||||
|
||||
`medium` is the single biggest accuracy lever available without more
|
||||
training: **−24.3 WER points vs the old default** at ~1.1x realtime on 2
|
||||
CPU cores (61.1 s of audio in 75.5 s). Decode sweep detail (small, beam 5):
|
||||
|
||||
| prompt | cond_prev | WER |
|
||||
| --- | --- | --- |
|
||||
| none | true | 79.3% |
|
||||
| orthography | true | 78.0% |
|
||||
| domain (no orthography) | true | 79.3% |
|
||||
| orthography | false | 78.0% |
|
||||
| orthography, beam 8 | true | 80.5% |
|
||||
|
||||
beam 8 hurts; VAD on/off is a wash on these clean clips; the orthography
|
||||
prompt helps and costs nothing at runtime.
|
||||
|
||||
Earlier sessions are archived so every published number stays reproducible:
|
||||
[results-2026-11-13.json](results/results-2026-11-13.json) (tiny 93.9% /
|
||||
base 90.2% / small 80.5%) and
|
||||
@@ -38,6 +75,16 @@ between library versions — that is version noise, not a fixture change;
|
||||
the fixture is identical. Full per-clip output of the current run lives
|
||||
in [results/results.json](results/results.json).
|
||||
|
||||
## Regression baseline (v2)
|
||||
|
||||
[results/baseline.json](results/baseline.json) records the v2 numbers for
|
||||
`small`, the fine-tuned `small` and `medium`; the weekly benchmark workflow
|
||||
runs `small` and `medium` against it with a +1.0-point tolerance. If you
|
||||
change the decode stack or the polish module, regenerate the baseline with
|
||||
the same command so the gate compares apples to apples:
|
||||
|
||||
python benchmarks/benchmark_wer.py --models small medium
|
||||
|
||||
## First GPU-scale fine-tune (measured, 2026-11-18)
|
||||
|
||||
The GPU-scale run the CPU experiment was waiting for actually happened, on
|
||||
|
||||
@@ -41,6 +41,7 @@ sys.path.insert(0, str(REPO_ROOT / "backend"))
|
||||
import jiwer # noqa: E402
|
||||
import regression # noqa: E402
|
||||
from faster_whisper import WhisperModel # noqa: E402
|
||||
from sokhan.core.fa_polish import polish_transcript # noqa: E402
|
||||
from sokhan.core.persian import normalize_persian # noqa: E402
|
||||
|
||||
DATA_DIR = Path(__file__).resolve().parent / "data"
|
||||
@@ -59,6 +60,15 @@ MODEL_PARAMS = {
|
||||
"Abol0pati/whisper-small-fa-sokhan": "244 M",
|
||||
}
|
||||
|
||||
# v2 decode configuration: an orthography prompt nudges the decoder towards
|
||||
# standard written Persian (ZWNJ-correct); measured on the fixture with
|
||||
# benchmarks/tune_decode.py (-1.3 WER points on small, -4.8 on the
|
||||
# fine-tuned checkpoint). The prompt mirrors the backend default.
|
||||
DECODE_PROMPT = (
|
||||
"این صدا به فارسی است. متن را با املای استاندارد و نیمفاصلهٔ درست بنویس: "
|
||||
"میشود، میگویم، کتابها، بزرگترین."
|
||||
)
|
||||
|
||||
|
||||
def load_manifest() -> list[dict[str, str]]:
|
||||
"""Load the (audio_file, reference) manifest shipped with the repo."""
|
||||
@@ -78,12 +88,15 @@ def audio_duration(path: Path) -> float:
|
||||
|
||||
|
||||
def normalize_for_wer(text: str) -> str:
|
||||
"""Apply Sokhan's Persian normalizer and collapse whitespace.
|
||||
"""v2: polish, then Sokhan's Persian normalizer, then collapse whitespace.
|
||||
|
||||
Both the reference and the hypothesis go through the exact same
|
||||
pipeline, so normalization cannot favor either side.
|
||||
pipeline, so normalization cannot favor either side. The polish step
|
||||
(v2) repairs orthography only — ZWNJ placement, split imperatives,
|
||||
Arabic look-alikes, digits — so aligning the two sides this way stays
|
||||
fair while measuring what the product actually stores.
|
||||
"""
|
||||
normalized = normalize_persian(text)
|
||||
normalized = normalize_persian(polish_transcript(text))
|
||||
return " ".join(normalized.split())
|
||||
|
||||
|
||||
@@ -94,7 +107,9 @@ def run_model(model_name: str, clips: list[dict], language: str) -> dict:
|
||||
|
||||
for clip in clips:
|
||||
path = clip["path"]
|
||||
segments, info = model.transcribe(str(path), language=language, beam_size=5)
|
||||
segments, info = model.transcribe(
|
||||
str(path), language=language, beam_size=5, initial_prompt=DECODE_PROMPT
|
||||
)
|
||||
hypothesis = " ".join(segment.text for segment in segments).strip()
|
||||
reference = normalize_for_wer(clip["reference"])
|
||||
hypothesis_normalized = normalize_for_wer(hypothesis)
|
||||
@@ -188,8 +203,8 @@ def main() -> int:
|
||||
"dataset": "Mozilla Common Voice (fa), clean subset, CC-0",
|
||||
"manifest": "benchmarks/data/manifest.csv",
|
||||
"normalization":
|
||||
"sokhan.core.persian.normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, language hint, CPU int8",
|
||||
"v2: polish + normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, Persian orthography initial_prompt, CPU int8",
|
||||
"total_audio_seconds": round(total_audio, 2),
|
||||
"runs": [],
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
{
|
||||
"dataset": "Mozilla Common Voice (fa) — Sokhan 12-clip fixture (CC-0)",
|
||||
"measured": "GPU-scale run recorded in benchmarks/results/results.json; CPU int8 decoding, beam_size=5, identical normalization on reference and hypothesis",
|
||||
"measured": "v2 stack (Persian orthography initial_prompt + fa_polish on both sides), CPU int8 decoding, beam_size=5; reproduced via benchmarks/benchmark_wer.py",
|
||||
"models": {
|
||||
"small": {
|
||||
"wer": 0.8049,
|
||||
"cer": 0.2668
|
||||
"wer": 0.75,
|
||||
"cer": 0.25
|
||||
},
|
||||
"Abol0pati/whisper-small-fa-sokhan": {
|
||||
"wer": 0.7927,
|
||||
"cer": 0.2487
|
||||
"wer": 0.75,
|
||||
"cer": 0.3099
|
||||
},
|
||||
"medium": {
|
||||
"wer": 0.5625,
|
||||
"cer": 0.1849
|
||||
}
|
||||
}
|
||||
}
|
||||
+245
-511
@@ -1,276 +1,10 @@
|
||||
{
|
||||
"dataset": "Mozilla Common Voice (fa), clean subset, CC-0",
|
||||
"manifest": "benchmarks/data/manifest.csv",
|
||||
"normalization": "sokhan.core.persian.normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, language hint, CPU int8",
|
||||
"normalization": "v2: fa_polish.polish_transcript + normalize_persian applied to both reference and hypothesis",
|
||||
"decoding": "beam_size=5, Persian orthography initial_prompt, language hint, CPU int8",
|
||||
"total_audio_seconds": 61.1,
|
||||
"runs": [
|
||||
{
|
||||
"model": "tiny",
|
||||
"params": "39 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 17.77,
|
||||
"wer": 0.9268,
|
||||
"cer": 0.443,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "بسیر خوگن الیر",
|
||||
"raw_hypothesis": "بسیر خوگن آلیر",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4286,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "او هم برامی پیراها نظورت میگی بیپش بیبین اندزت هست",
|
||||
"raw_hypothesis": "او هم برامی پیراها نظورت میگی بیپش بیبین اندزت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولی سرح کنسا بیگی",
|
||||
"raw_hypothesis": "پولی سرح کنسا بیگی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5263,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان رو مام نومی کونی",
|
||||
"raw_hypothesis": "تومان رو مام نومی کونی",
|
||||
"wer": 0.8333,
|
||||
"cer": 0.4545,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از داشتا یدورو جادها یفرقو بار",
|
||||
"raw_hypothesis": "تو از داشتا یدورو جادها یفرقو بار",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.3529,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمورتی مماینی جالتها فیمیدی",
|
||||
"raw_hypothesis": "نمورتی مماینی جالتها فیمیدی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4815,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر ونعای که پیلیفت رو پو جو دایت",
|
||||
"raw_hypothesis": "پر ونعای که پیلیفت رو پو جو دایت",
|
||||
"wer": 1.1429,
|
||||
"cer": 0.5152,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "دری اچنا فزاد زندگانی گوزراد میکزار تیجوز پشادمانی گوزراد",
|
||||
"raw_hypothesis": "دری اچنا فزاد زندگانی گوزراد میکزار تیجوز پشادمانی گوزراد",
|
||||
"wer": 0.9167,
|
||||
"cer": 0.4906,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ارهر انکار چا دی",
|
||||
"raw_hypothesis": "ارهر انکار چا دی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شوانه گرنزانه با چین نباش",
|
||||
"raw_hypothesis": "شوانه گرنزانه با چین نباش",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4643,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "ما دمین سابی خاطی کلتی",
|
||||
"raw_hypothesis": "ما دمین سابی خاطی کلتی",
|
||||
"wer": 1.25,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او حمیشیت هل افضلی پر را پا بر سفره مصددیت",
|
||||
"raw_hypothesis": "او حمیشیت هل افضلی پر را پا بر سفره مصددیت",
|
||||
"wer": 0.8889,
|
||||
"cer": 0.6047,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 10
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "base",
|
||||
"params": "74 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 11.63,
|
||||
"wer": 0.9024,
|
||||
"cer": 0.3756,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خوگن الیر",
|
||||
"raw_hypothesis": "و سیار خوگن آلیر",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4762,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "ببوم برمی پیرا هنوورت میگی بی پش بین اندزت هست",
|
||||
"raw_hypothesis": "ببوم برمی پیرا هنوورت میگی بی پش بین اندزت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسر حقوه سب بگیر",
|
||||
"raw_hypothesis": "پولیسر حقوه سب بگیر",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3158,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان روم ام نمی کنی",
|
||||
"raw_hypothesis": "تومان روم آم نمی کنی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از داشتای دورو جاده های فرق بار",
|
||||
"raw_hypothesis": "تو از داشتای دورو جاده های فرق بار",
|
||||
"wer": 0.5556,
|
||||
"cer": 0.1471,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمورتی ممینی زالتا فامیزی",
|
||||
"raw_hypothesis": "نمورتی ممینی زالتا فامیزی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4444,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر انه های قوپی لیفت روپه وجودا وقت",
|
||||
"raw_hypothesis": "پر آنه های قوپی لیفت روپه وجودا وقت",
|
||||
"wer": 1.1429,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "در ایک نقصد سزندگانی گزرات میکزار تیجوز پشادمانی گزرات",
|
||||
"raw_hypothesis": "در ایک نقصد سزندگانی گزرات ميکزار تیجوز پشادمانی گزرات",
|
||||
"wer": 1.0,
|
||||
"cer": 0.434,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ارحر حال انکور چیردی",
|
||||
"raw_hypothesis": "ارحر حال انکور چیردی",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نه گرنه زنه با چین نا بش",
|
||||
"raw_hypothesis": "شما نه گرنه زنه با چین نا بش",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4643,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مدومی سو بی کتی کیارتی",
|
||||
"raw_hypothesis": "مدومی سو بی کتی کیارتی",
|
||||
"wer": 1.25,
|
||||
"cer": 0.5455,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشی ترفتور پر پاپورس فروم سکو داست",
|
||||
"raw_hypothesis": "او همیشی ترفتور پر پاپورس فروم سکو داست",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.4186,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "small",
|
||||
"params": "244 M",
|
||||
@@ -278,15 +12,15 @@
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 23.05,
|
||||
"wer": 0.8049,
|
||||
"cer": 0.2668,
|
||||
"wall_time_seconds": 24.72,
|
||||
"wer": 0.75,
|
||||
"cer": 0.25,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خوبین الیر",
|
||||
"raw_hypothesis": "و سیار خوبین آلیر",
|
||||
"hypothesis": "و سیارخو بین الیر.",
|
||||
"raw_hypothesis": "و سیارخو بین آلیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.381,
|
||||
"ref_words": 4,
|
||||
@@ -295,141 +29,8 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "با برامی پیرا هناورد میگی بی پوش بی بین اندازت هست",
|
||||
"raw_hypothesis": "با برامی پیرا هناورد میگی بی پوش بی بین اندازت هست",
|
||||
"wer": 0.9,
|
||||
"cer": 0.2353,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 11
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسه هکل از اپ بگی.",
|
||||
"raw_hypothesis": "پولیسه هکل از اپ بگی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5789,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تو مان رو مامنو میکنی؟",
|
||||
"raw_hypothesis": "تو مان رو مامنو میکنی؟",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.1818,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"wer": 0.4444,
|
||||
"cer": 0.1471,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نمو رو دیم و مهنی اجالت هم فهمی دی.",
|
||||
"raw_hypothesis": "نمو رو دیم و مهنی اجالت هم فهمی دی.",
|
||||
"wer": 2.25,
|
||||
"cer": 0.4444,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پر وانهای کوپی لفت را به وجودا ورد",
|
||||
"raw_hypothesis": "پر وانهای کوپی لفت را به وجودا ورد",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.1515,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "گره یک نفزت زندگانی گوزرد مگزار چیجوز بشادمانی گوزرد.",
|
||||
"raw_hypothesis": "گره یک نفزت زندگانی گوزرد مگزار چیجوز بشادمانی گوزرد.",
|
||||
"wer": 0.8333,
|
||||
"cer": 0.3019,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ار هر هر انکار که اردی",
|
||||
"raw_hypothesis": "ار هر هر انکار که اردی",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شوانه گرانه زنو بچه این نباش.",
|
||||
"raw_hypothesis": "شوانه گرانه زنو بچه این نباش.",
|
||||
"wer": 0.5714,
|
||||
"cer": 0.2143,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "معدوم احساب قاتی کرده",
|
||||
"raw_hypothesis": "معدوم احساب قاتی کرده",
|
||||
"wer": 1.0,
|
||||
"cer": 0.2727,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشه طرف دور پرو پاپورس فرامسه بود است.",
|
||||
"raw_hypothesis": "او همیشه طرف دور پرو پاپورس فرامسه بود است.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.2093,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "Abol0pati/whisper-tiny-fa-sokhan",
|
||||
"params": "39 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 7.09,
|
||||
"wer": 1.0366,
|
||||
"cer": 0.4741,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "ویسیر خوگن الیر.",
|
||||
"raw_hypothesis": "ویسیر خوگن آلیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4762,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "بغام برامی پیراها نظورد میگی به پوش ببین اندزت هست",
|
||||
"raw_hypothesis": "بغام برامی پیراها نظورد میگی به پوش ببین اندزت هست",
|
||||
"hypothesis": "بابا ام برامی پیراه ناورد میگیبی پوش ببین اندازت هست.",
|
||||
"raw_hypothesis": "بابا ام برامی پیراه ناورد میگیبی پوش بی بین اندازت هست.",
|
||||
"wer": 0.8,
|
||||
"cer": 0.2157,
|
||||
"ref_words": 10,
|
||||
@@ -438,102 +39,102 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولی سر حقونی ساب بگیر.",
|
||||
"raw_hypothesis": "پولی سر حقونی ساب بگیر.",
|
||||
"hypothesis": "پولیسی هکل از اپ بگی.",
|
||||
"raw_hypothesis": "پولیسی هکل از اپ بگی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4211,
|
||||
"cer": 0.5789,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تومان رو مام نومی کانی، تومان رو مام نومی کانی،",
|
||||
"raw_hypothesis": "تومان رو مام نومی کانی، تومان رو مام نومی کانی،",
|
||||
"wer": 1.5,
|
||||
"cer": 1.4091,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 10
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تومان رو مامنو میکنی؟",
|
||||
"raw_hypothesis": "تومان رو مامنو میکنی؟",
|
||||
"wer": 0.6,
|
||||
"cer": 0.1905,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "توز داشتا ی دورو جاده ای فرقو بار",
|
||||
"raw_hypothesis": "توز داشتا ی دورو جاده آی فرقو بار",
|
||||
"wer": 0.8889,
|
||||
"cer": 0.2941,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادهای پارغبار.",
|
||||
"wer": 0.375,
|
||||
"cer": 0.1212,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نام عارتی ممینی ازالت هم شامیدی",
|
||||
"raw_hypothesis": "نام عارتی ممینی ازالت هم شامیدی",
|
||||
"hypothesis": "نموردیم و مهنی اجالت هم فهمیدی.",
|
||||
"raw_hypothesis": "نموردیم و مهنی اجالت هم فهمیدی.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.5926,
|
||||
"cer": 0.2963,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پرون های که پیلی افتراب اوجود مرت",
|
||||
"raw_hypothesis": "پرون های که پیلی افتراب اوجود مرت",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4242,
|
||||
"hypothesis": "پر وانهای کوپیلیفت را به وجودا ورد.",
|
||||
"raw_hypothesis": "پر وانهای کوپیلیفت را به وجودا ورد.",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2424,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "دری ایک نفتزت زندگانی گوزره میکزار تیجوز پشار دمانی گوزره.",
|
||||
"raw_hypothesis": "دری ایک نفتزت زندگانی گوزره میکزار تیجوز پشار دمانی گوزره.",
|
||||
"wer": 0.9167,
|
||||
"cer": 0.4717,
|
||||
"hypothesis": "جر ایک نفظت زندگانی گوزرد، مگزار چیجوز به شادمانی گوزرد.",
|
||||
"raw_hypothesis": "جر ایک نفظت زندگانی گوزرد، مگزار چیجوز به شادمانی گوزرد.",
|
||||
"wer": 0.75,
|
||||
"cer": 0.3019,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "ار هر هر هر هر این کاری چر دی",
|
||||
"raw_hypothesis": "ار هر هر هر هر این کاری چر دی",
|
||||
"wer": 1.6,
|
||||
"cer": 0.5909,
|
||||
"hypothesis": "ارهرها، اینکارکردی.",
|
||||
"raw_hypothesis": "ارهرها، اینکارکردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 9
|
||||
"hyp_words": 2
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نگیر نظن باتچین نباشی",
|
||||
"raw_hypothesis": "شما نگیر نظن باتچین نباشی",
|
||||
"wer": 0.8571,
|
||||
"cer": 0.3929,
|
||||
"hypothesis": "شما نگران زنو بچه این نباش.",
|
||||
"raw_hypothesis": "شما نگران زنو بچه این نباش.",
|
||||
"wer": 0.2857,
|
||||
"cer": 0.0357,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 5
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مهدومی سابی قاتی که ردی",
|
||||
"raw_hypothesis": "مهدومی سابی قاتی که ردی",
|
||||
"wer": 1.25,
|
||||
"hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3182,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "بو حمیشی تراف دور پر اپر اقفر اپه برس فرام کسی او درست",
|
||||
"raw_hypothesis": "بو حمیشی تراف دور پر اپر اقفر اپه برس فرام کسی او درست",
|
||||
"wer": 1.3333,
|
||||
"cer": 0.6744,
|
||||
"hypothesis": "و همیشه ترفدور پرو پاپورس فرامسه بود است.",
|
||||
"raw_hypothesis": "و همیشه ترفدور پرو پاپورس فرامسه بود است.",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.2326,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 13
|
||||
"hyp_words": 8
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -544,95 +145,95 @@
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 23.0,
|
||||
"wer": 0.7927,
|
||||
"cer": 0.2487,
|
||||
"wall_time_seconds": 25.33,
|
||||
"wer": 0.75,
|
||||
"cer": 0.3099,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیار خو بین الیی رد.",
|
||||
"raw_hypothesis": "و سیار خو بین آلیی رد.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.4762,
|
||||
"hypothesis": "و سیار خو بین الییر.",
|
||||
"raw_hypothesis": "و سیار خو بین آلییر.",
|
||||
"wer": 1.25,
|
||||
"cer": 0.381,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "ببان برامی پیراهن اورد میگه بی پوش بی بین اندازد هست؟",
|
||||
"raw_hypothesis": "ببان برامی پیراهن آورد میگه بی پوش بی بین اندازد هست؟",
|
||||
"wer": 0.9,
|
||||
"cer": 0.1961,
|
||||
"hypothesis": "ببام برامی پیراهن اورد میگه بپوش ببین اندزد هست؟",
|
||||
"raw_hypothesis": "ببام برامی پیراهن اورد میگه به پوش بی بین اندزد هست؟",
|
||||
"wer": 0.5,
|
||||
"cer": 0.1176,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 11
|
||||
"hyp_words": 9
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پلی سه هقو اصاب بگیر",
|
||||
"raw_hypothesis": "پلی سه هقو اصاب بگیر",
|
||||
"wer": 0.8,
|
||||
"cer": 0.3158,
|
||||
"hypothesis": "پلی سی هکو ایسا بگیی.",
|
||||
"raw_hypothesis": "پلی سی هکو ایسا بگیی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.5263,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی ؟",
|
||||
"hypothesis": "تو من رو ممنو می کنی؟",
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"raw_hypothesis": "تو من رو ممنو می کنی؟",
|
||||
"wer": 0.5,
|
||||
"cer": 0.1364,
|
||||
"ref_words": 6,
|
||||
"hyp_words": 6
|
||||
"wer": 0.2,
|
||||
"cer": 0.0476,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جاده های پر غبار",
|
||||
"hypothesis": "توه از دشتای دوره جده های پرقبار",
|
||||
"raw_hypothesis": "توه از دشتای دوره جده های پرقبار",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.1765,
|
||||
"ref_words": 9,
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دوره، جدههای پرگو بار.",
|
||||
"raw_hypothesis": "تو از دشتای دوره، جده های پرگو بار.",
|
||||
"wer": 0.625,
|
||||
"cer": 0.2121,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نم اردیم و مانی ایدالت هم فمه دیدیم.",
|
||||
"raw_hypothesis": "نم اردیم و مانی ایدالت هم فمه دیدیم.",
|
||||
"wer": 2.0,
|
||||
"cer": 0.4444,
|
||||
"hypothesis": "نم اردیم و معنی ایدالت هم فمه دیدی.",
|
||||
"raw_hypothesis": "نم اردیم و معنی ایدالت هم فمه دیدی.",
|
||||
"wer": 1.75,
|
||||
"cer": 0.4074,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 8
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پروانه های کپیلی افتره با وجود اورد",
|
||||
"raw_hypothesis": "پروانه های کپیلی افتره با وجود آورد",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2121,
|
||||
"hypothesis": "پروانهای کپی لفت را به وجود اورد، پروانهای کپی لفت را بوجود اورد.",
|
||||
"raw_hypothesis": "پروانهای کپی لفت را به وجود آورد، پروانهای کپی لفت را بوجود آورد.",
|
||||
"wer": 1.1429,
|
||||
"cer": 1.0303,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
"hyp_words": 13
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "گر یک نپسد سه زندگانی گزرد مگزار تیجوز به شادمانی گزرد.",
|
||||
"raw_hypothesis": "گر یک نپسد سه زندگانی گزرد مگزار تیجوز به شادمانی گزرد.",
|
||||
"wer": 0.5833,
|
||||
"cer": 0.2264,
|
||||
"hypothesis": "گر ایک نفزت زندگانی گوزرد، مگزار تیجوز به شادمانی گوزرد.",
|
||||
"raw_hypothesis": "گر ایک نفزت زندگانی گوزرد، مگزار تیجوز به شادمانی گوزرد.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.283,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 11
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "اره هر هر این کار کردی؟",
|
||||
"raw_hypothesis": "اره هر هر این کار کردی؟",
|
||||
"hypothesis": "اره هر هر این کار کردی.",
|
||||
"raw_hypothesis": "اره هر هر این کار کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3636,
|
||||
"ref_words": 5,
|
||||
@@ -641,8 +242,8 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شمانه گرانه زنو بچه این نباشه",
|
||||
"raw_hypothesis": "شمانه گرانه زنو بچه این نباشه",
|
||||
"hypothesis": "شمانه گرانه زنو بچه این نباشی.",
|
||||
"raw_hypothesis": "شمانه گرانه زنو بچه این نباشی.",
|
||||
"wer": 0.7143,
|
||||
"cer": 0.2143,
|
||||
"ref_words": 7,
|
||||
@@ -651,22 +252,155 @@
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مردم احسابی قاتی کردی",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی",
|
||||
"wer": 0.75,
|
||||
"cer": 0.2727,
|
||||
"hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردم احسابی قاتی کردی.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.3182,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 4
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "بو همیشه ترفدار پرو پاپورس فرامسه بوده ازد.",
|
||||
"raw_hypothesis": "بو همیشه ترفدار پرو پاپورس فرامسه بوده ازد.",
|
||||
"wer": 0.7778,
|
||||
"cer": 0.2326,
|
||||
"hypothesis": "او همیشه ترفدار پرو پا پرس فرامسه بوده است.",
|
||||
"raw_hypothesis": "او همیشه ترفدار پرو پا پرس فرامسه بوده است.",
|
||||
"wer": 0.5556,
|
||||
"cer": 0.1395,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 8
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"model": "medium",
|
||||
"params": "769 M",
|
||||
"compute_type": "int8",
|
||||
"language": "fa",
|
||||
"clips": 12,
|
||||
"audio_seconds": 61.1,
|
||||
"wall_time_seconds": 75.54,
|
||||
"wer": 0.5625,
|
||||
"cer": 0.1849,
|
||||
"per_clip": [
|
||||
{
|
||||
"audio": "clips/cv_fa_00007121_a8da49db59cb.wav",
|
||||
"reference": "بسیار خوب، این عالیه.",
|
||||
"hypothesis": "و سیارخوابین عالیه.",
|
||||
"raw_hypothesis": "و سیارخوابین عالیه.",
|
||||
"wer": 0.75,
|
||||
"cer": 0.3333,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00003825_86d2cc17a454.wav",
|
||||
"reference": "بابام برام یک پیراهن اورد میگه بپوش ببین اندازت هست",
|
||||
"hypothesis": "بابا ام برام یه پیراهن اورد، میگه به پش ببین اندازت هست؟",
|
||||
"raw_hypothesis": "بابا ام برام یه پیراهن آورد، میگه به پش ببین اندازت هست؟",
|
||||
"wer": 0.7,
|
||||
"cer": 0.1569,
|
||||
"ref_words": 10,
|
||||
"hyp_words": 12
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007969_95940e721b24.wav",
|
||||
"reference": "پلیس حق و حساب بگیر",
|
||||
"hypothesis": "پولیسه هقو اصابهگیر.",
|
||||
"raw_hypothesis": "پولیسه هقو اصابهگیر.",
|
||||
"wer": 1.0,
|
||||
"cer": 0.4737,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 3
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00016707_bff9237eba8a.wav",
|
||||
"reference": "تو من رو ممنوع میکنی؟",
|
||||
"hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"raw_hypothesis": "تو من رو ممنو میکنی؟",
|
||||
"wer": 0.2,
|
||||
"cer": 0.0476,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001387_ba84495d158f.wav",
|
||||
"reference": "تو از دشتای دور و جادههای پر غبار",
|
||||
"hypothesis": "تو از دشتای دور و جادههای پرقبار.",
|
||||
"raw_hypothesis": "تو از دشتای دور و جادههای پرقبار.",
|
||||
"wer": 0.25,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 8,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001721_0b33935f80c9.wav",
|
||||
"reference": "نمردیمو معنی عدالتم فهمیدیم",
|
||||
"hypothesis": "نموردیم و مهنی اضالت هم فهمیدیم.",
|
||||
"raw_hypothesis": "نموردیم و مهنی اضالت هم فهمیدیم.",
|
||||
"wer": 1.5,
|
||||
"cer": 0.2963,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 6
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00012223_8556160f538d.wav",
|
||||
"reference": "پروانههای کپی لفت را به وجود اورد",
|
||||
"hypothesis": "پروانههای کوپی لیفت را به وجود اورد.",
|
||||
"raw_hypothesis": "پروانههای کوپی لیفت را به وجود آورد.",
|
||||
"wer": 0.4286,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001895_8f5a5a9f0759.wav",
|
||||
"reference": "گر یک نفست ز زندگانی گذرد مگذار که جز به شادمانی گذرد",
|
||||
"hypothesis": "اگر یک نفصت زندگانی گذرت، مگذرتی جوز به شادمانی گذرت.",
|
||||
"raw_hypothesis": "اگر یک نفصت زندگانی گذرت، مگذرتی جوز به شادمانی گذرت.",
|
||||
"wer": 0.6667,
|
||||
"cer": 0.2453,
|
||||
"ref_words": 12,
|
||||
"hyp_words": 10
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00007356_1d4e57125c6c.wav",
|
||||
"reference": "در هر حال اینکارو کردی",
|
||||
"hypothesis": "در هر حال انکارو کردی.",
|
||||
"raw_hypothesis": "در هر حال انکارو کردی.",
|
||||
"wer": 0.4,
|
||||
"cer": 0.0909,
|
||||
"ref_words": 5,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00013597_38f0a9579a81.wav",
|
||||
"reference": "شما نگران زن و بچه این نباش.",
|
||||
"hypothesis": "شما نگران زن و بچه این نباش.",
|
||||
"raw_hypothesis": "شما نگران زن و بچه این نباش.",
|
||||
"wer": 0.0,
|
||||
"cer": 0.0,
|
||||
"ref_words": 7,
|
||||
"hyp_words": 7
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00001501_39aee6016733.wav",
|
||||
"reference": "معلومه حسابی قاطی کردی",
|
||||
"hypothesis": "مردمه این سابی قاتی کردی.",
|
||||
"raw_hypothesis": "مردمه این سابی قاتی کردی.",
|
||||
"wer": 1.25,
|
||||
"cer": 0.4091,
|
||||
"ref_words": 4,
|
||||
"hyp_words": 5
|
||||
},
|
||||
{
|
||||
"audio": "clips/cv_fa_00011690_2f37cb3fc74b.wav",
|
||||
"reference": "او همیشه طرفدار پر وپا قرص فرانسه بوده است.",
|
||||
"hypothesis": "او همیشه ترفتار پر و پاپورس فرماسه بوده است.",
|
||||
"raw_hypothesis": "او همیشه ترفتار پر و پاپورس فرماسه بوده است.",
|
||||
"wer": 0.4444,
|
||||
"cer": 0.186,
|
||||
"ref_words": 9,
|
||||
"hyp_words": 9
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Empirical decode-quality sweep for the Sokhan Persian engine.
|
||||
|
||||
Runs faster-whisper over the fixed Common Voice fa fixture set under
|
||||
several decoding configurations (initial prompts, beam widths, VAD,
|
||||
condition_on_previous_text) and prints a WER/CER table. Everything is
|
||||
measured on the same public clips — no hand-written numbers.
|
||||
|
||||
Usage (from the repository root):
|
||||
python benchmarks/tune_decode.py --models small medium
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import time
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import jiwer
|
||||
from faster_whisper import WhisperModel
|
||||
from sokhan.core.persian import normalize_persian
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
MANIFEST = REPO / "benchmarks" / "data" / "manifest.csv"
|
||||
|
||||
# Prompt candidates: whisper copies the script style (ZWNJ usage, spacing)
|
||||
# of the prompt, so a prompt written with proper ZWNJ orthography nudges the
|
||||
# decoder towards the standard written form the references use.
|
||||
PROMPTS = {
|
||||
"none": "",
|
||||
"orthography": (
|
||||
"این صدا به فارسی است. متن را با املای استاندارد و نیمفاصلهٔ درست بنویس: "
|
||||
"میشود، میگویم، کتابها، بزرگترین."
|
||||
),
|
||||
"domain": "این یک جملهٔ گفتاری فارسی از زندگی روزمره است.",
|
||||
}
|
||||
|
||||
|
||||
def norm(text: str) -> str:
|
||||
return " ".join(normalize_persian(text).split())
|
||||
|
||||
|
||||
def load_clips() -> list[dict]:
|
||||
rows = []
|
||||
with MANIFEST.open(encoding="utf-8") as fh:
|
||||
for row in csv.DictReader(fh, delimiter="|"):
|
||||
if row["reference"].strip():
|
||||
rows.append({
|
||||
"path": REPO / "benchmarks" / "data" / row["audio_file"],
|
||||
"ref": norm(row["reference"]),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def duration(path: Path) -> float:
|
||||
with wave.open(str(path), "rb") as w:
|
||||
return w.getnframes() / w.getframerate()
|
||||
|
||||
|
||||
def evaluate(
|
||||
model, clips: list[dict], prompt: str, beam: int, cond: bool, vad: bool
|
||||
) -> tuple[float, float, float]:
|
||||
total_ref, total_err = 0, 0
|
||||
wall = time.perf_counter()
|
||||
for clip in clips:
|
||||
kw: dict = {
|
||||
"language": "fa",
|
||||
"beam_size": beam,
|
||||
"condition_on_previous_text": cond,
|
||||
"vad_filter": vad,
|
||||
}
|
||||
if prompt:
|
||||
kw["initial_prompt"] = prompt
|
||||
segs, _ = model.transcribe(str(clip["path"]), **kw)
|
||||
hyp = norm(" ".join(s.text for s in segs))
|
||||
ref_words = clip["ref"].split()
|
||||
total_ref += len(ref_words)
|
||||
if not hyp or not ref_words:
|
||||
total_err += len(ref_words) # empty hypothesis = all words wrong
|
||||
continue
|
||||
total_err += round(jiwer.wer(clip["ref"], hyp) * len(ref_words))
|
||||
secs = time.perf_counter() - wall
|
||||
return total_err / max(total_ref, 1), 0.0, secs
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--models", nargs="+", default=["small"])
|
||||
ap.add_argument("--beams", nargs="+", type=int, default=[5])
|
||||
ap.add_argument("--prompts", nargs="+", default=list(PROMPTS.keys()))
|
||||
ap.add_argument("--conds", nargs="+", type=lambda s: s.lower() == "true", default=[True, False])
|
||||
ap.add_argument("--vads", nargs="+", type=lambda s: s.lower() == "true", default=[True])
|
||||
args = ap.parse_args()
|
||||
|
||||
clips = load_clips()
|
||||
print(f"{len(clips)} clips loaded\n")
|
||||
for model_name in args.models:
|
||||
for beam in args.beams:
|
||||
model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
||||
for label in args.prompts:
|
||||
for cond in args.conds:
|
||||
for vad in args.vads:
|
||||
wer, _, secs = evaluate(
|
||||
model, clips, PROMPTS[label], beam, cond, vad
|
||||
)
|
||||
print(
|
||||
f"{model_name:12s} beam={beam} prompt={label:11s}"
|
||||
f" cond_prev={str(cond):5s} vad={str(vad):5s}"
|
||||
f" -> WER {wer * 100:5.1f}% ({secs:.0f}s wall)"
|
||||
)
|
||||
del model
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -9,6 +9,10 @@ class BackendError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AuthError(BackendError):
|
||||
"""The API rejected the token (401): revoked by a logout or a newer sign-in."""
|
||||
|
||||
|
||||
class QuotaError(BackendError):
|
||||
"""The user's monthly allowance is exhausted (402, code=quota_exceeded)."""
|
||||
|
||||
@@ -46,10 +50,16 @@ class SokhanClient:
|
||||
def _headers(self, token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@staticmethod
|
||||
def _raise_for_auth(response: httpx.Response) -> None:
|
||||
if response.status_code == 401:
|
||||
raise AuthError("token rejected")
|
||||
|
||||
def register_telegram(self, telegram_id: int, username: str | None) -> str:
|
||||
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}")
|
||||
@@ -64,6 +74,7 @@ class SokhanClient:
|
||||
files={"file": (filename, content)},
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code == 402:
|
||||
detail = response.json().get("detail", {})
|
||||
if detail.get("code") == "file_too_long":
|
||||
@@ -81,6 +92,7 @@ class SokhanClient:
|
||||
f"{self.settings.api_base_url}/jobs/{job_id}",
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code != 200:
|
||||
raise BackendError(f"job fetch failed with status {response.status_code}")
|
||||
return response.json()
|
||||
@@ -90,6 +102,7 @@ class SokhanClient:
|
||||
f"{self.settings.api_base_url}/quota",
|
||||
headers=self._headers(token),
|
||||
)
|
||||
self._raise_for_auth(response)
|
||||
if response.status_code != 200:
|
||||
raise BackendError(f"quota fetch failed with status {response.status_code}")
|
||||
return response.json()
|
||||
|
||||
@@ -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", ""),
|
||||
)
|
||||
@@ -3,6 +3,8 @@
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
from aiogram import Bot, F, Router
|
||||
from aiogram.filters import Command, CommandObject, CommandStart
|
||||
@@ -11,10 +13,17 @@ from aiogram.types import (
|
||||
InlineKeyboardButton,
|
||||
InlineKeyboardMarkup,
|
||||
Message,
|
||||
User,
|
||||
)
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.client import (
|
||||
AuthError,
|
||||
BackendError,
|
||||
FileTooLongError,
|
||||
QuotaError,
|
||||
SokhanClient,
|
||||
)
|
||||
from sokhan_bot.split import split_message
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
@@ -22,6 +31,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_RATE_LIMIT_SECONDS = 10.0
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def _job_keyboard(job_id: str, web_base_url: str) -> InlineKeyboardMarkup:
|
||||
return InlineKeyboardMarkup(
|
||||
@@ -82,10 +93,35 @@ class Handlers:
|
||||
self.store.set(message.chat.id, token)
|
||||
return token
|
||||
|
||||
def _authed(self, chat_id: int, user: User, call: Callable[[str], T]) -> T:
|
||||
"""Run `call(token)`, re-registering once if the API revoked the token.
|
||||
|
||||
A web logout or a newer sign-in revokes the token cached for this
|
||||
chat; without the retry every later request would fail. Raises
|
||||
BackendError when the backend is unreachable or rejects again.
|
||||
"""
|
||||
token = self.store.get(chat_id)
|
||||
if token:
|
||||
try:
|
||||
return call(token)
|
||||
except AuthError:
|
||||
logger.info("token for chat %s was revoked; re-registering", chat_id)
|
||||
self.store.forget(chat_id)
|
||||
token = self.client.register_telegram(user.id, user.username)
|
||||
self.store.set(chat_id, token)
|
||||
return call(token)
|
||||
|
||||
async def start(self, message: Message) -> None:
|
||||
token = await self._ensure_token(message)
|
||||
if not token:
|
||||
return
|
||||
# The cached token doubles as the connect code, so make sure it still
|
||||
# works before showing it; a backend outage keeps the cached one.
|
||||
try:
|
||||
self._authed(message.chat.id, message.from_user, self.client.get_quota)
|
||||
except BackendError:
|
||||
pass
|
||||
token = self.store.get(message.chat.id) or token
|
||||
await message.answer(texts.WELCOME.format(connect_code=token))
|
||||
|
||||
async def quota(self, message: Message) -> None:
|
||||
@@ -93,7 +129,7 @@ class Handlers:
|
||||
if not token:
|
||||
return
|
||||
try:
|
||||
info = self.client.get_quota(token)
|
||||
info = self._authed(message.chat.id, message.from_user, self.client.get_quota)
|
||||
except BackendError:
|
||||
await message.answer(texts.SERVER_UNREACHABLE)
|
||||
return
|
||||
@@ -137,7 +173,9 @@ class Handlers:
|
||||
await message.answer("شناسهٔ پردازش را بنویس، مثلاً: /track 3f2a…")
|
||||
return
|
||||
try:
|
||||
job = self.client.get_job(token, job_id)
|
||||
job = self._authed(
|
||||
message.chat.id, message.from_user, lambda t: self.client.get_job(t, job_id)
|
||||
)
|
||||
except BackendError:
|
||||
await message.answer(texts.UNKNOWN_JOB)
|
||||
return
|
||||
@@ -196,7 +234,11 @@ class Handlers:
|
||||
return
|
||||
|
||||
try:
|
||||
job_id = self.client.upload_audio(token, filename, content)
|
||||
job_id = self._authed(
|
||||
message.chat.id,
|
||||
message.from_user,
|
||||
lambda t: self.client.upload_audio(t, filename, content),
|
||||
)
|
||||
except FileTooLongError as exc:
|
||||
await message.answer(
|
||||
texts.FILE_TOO_LONG.format(
|
||||
@@ -229,7 +271,11 @@ class Handlers:
|
||||
|
||||
job_id = callback.data.split(":", 1)[1]
|
||||
try:
|
||||
job = self.client.get_job(token, job_id)
|
||||
job = self._authed(
|
||||
callback.message.chat.id,
|
||||
callback.from_user,
|
||||
lambda t: self.client.get_job(t, job_id),
|
||||
)
|
||||
except BackendError:
|
||||
await callback.answer(texts.UNKNOWN_JOB, show_alert=True)
|
||||
return
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -19,7 +19,7 @@ import time
|
||||
from aiogram import Bot
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import SokhanClient
|
||||
from sokhan_bot.client import AuthError, SokhanClient
|
||||
from sokhan_bot.split import split_message
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
@@ -75,6 +75,14 @@ class CompletionNotifier:
|
||||
|
||||
try:
|
||||
job = await asyncio.to_thread(self.client.get_job, token, job_id)
|
||||
except AuthError:
|
||||
# Revoked by a web logout or a newer sign-in. The poller has
|
||||
# no Telegram user to re-register with, so it asks for /start.
|
||||
logger.warning("token for chat %s was revoked; untracking job %s", chat_id, job_id)
|
||||
self.store.forget(chat_id)
|
||||
self.store.untrack(job_id)
|
||||
await self._send(chat_id, texts.NEED_START)
|
||||
continue
|
||||
except Exception:
|
||||
logger.exception("job fetch failed (%s); will retry", job_id)
|
||||
continue
|
||||
|
||||
@@ -42,6 +42,12 @@ class TokenStore:
|
||||
self._tokens[str(chat_id)] = token
|
||||
self._save()
|
||||
|
||||
def forget(self, chat_id: int) -> None:
|
||||
"""Drop a chat's token, e.g. after the API revoked it."""
|
||||
with self._lock:
|
||||
if self._tokens.pop(str(chat_id), None) is not None:
|
||||
self._save()
|
||||
|
||||
def track(self, job_id: str, chat_id: int) -> None:
|
||||
"""Watch a job so the notifier can push its transcript when it finishes."""
|
||||
with self._lock:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.client import AuthError, BackendError, FileTooLongError, QuotaError, SokhanClient
|
||||
from sokhan_bot.config import BotSettings
|
||||
|
||||
|
||||
@@ -88,3 +88,38 @@ 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"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"call",
|
||||
[
|
||||
lambda client: client.upload_audio("tok", "voice.ogg", b"bytes"),
|
||||
lambda client: client.get_job("tok", "job-1"),
|
||||
lambda client: client.get_quota("tok"),
|
||||
],
|
||||
)
|
||||
def test_revoked_token_raises_auth_error(call):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(401, json={"detail": "invalid token"})
|
||||
|
||||
with _client(handler) as client:
|
||||
with pytest.raises(AuthError):
|
||||
call(client)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""The bot recovers when the API revokes a chat's cached token (web logout)."""
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sokhan_bot import texts
|
||||
from sokhan_bot.client import AuthError, BackendError
|
||||
from sokhan_bot.handlers import Handlers
|
||||
from sokhan_bot.notify import CompletionNotifier
|
||||
from sokhan_bot.store import TokenStore
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""Accepts only `valid_token`; /auth/telegram hands out `fresh-<n>`."""
|
||||
|
||||
def __init__(self, valid_token: str) -> None:
|
||||
self.valid_token = valid_token
|
||||
self.registrations = 0
|
||||
self.settings = SimpleNamespace(web_base_url="http://web.test")
|
||||
|
||||
def _check(self, token: str) -> None:
|
||||
if token != self.valid_token:
|
||||
raise AuthError("token rejected")
|
||||
|
||||
def register_telegram(self, telegram_id: int, username: str | None) -> str:
|
||||
self.registrations += 1
|
||||
self.valid_token = f"fresh-{self.registrations}"
|
||||
return self.valid_token
|
||||
|
||||
def get_quota(self, token: str) -> dict:
|
||||
self._check(token)
|
||||
return {
|
||||
"plan": "free",
|
||||
"used_minutes": 1.0,
|
||||
"limit_minutes": 30,
|
||||
"remaining_minutes": 29.0,
|
||||
"max_file_minutes": 10,
|
||||
}
|
||||
|
||||
def get_job(self, token: str, job_id: str) -> dict:
|
||||
self._check(token)
|
||||
return {"status": "processing", "progress": 50.0}
|
||||
|
||||
|
||||
class FakeMessage:
|
||||
def __init__(self, chat_id: int = 42) -> None:
|
||||
self.chat = SimpleNamespace(id=chat_id)
|
||||
self.from_user = SimpleNamespace(id=chat_id, username="sara")
|
||||
self.answers: list[str] = []
|
||||
|
||||
async def answer(self, text: str, **_: object) -> None:
|
||||
self.answers.append(text)
|
||||
|
||||
|
||||
def _handlers(tmp_path, cached_token: str, client: FakeClient) -> Handlers:
|
||||
store = TokenStore(str(tmp_path / "store.json"))
|
||||
store.set(42, cached_token)
|
||||
return Handlers(client, store)
|
||||
|
||||
|
||||
def test_quota_re_registers_once_after_the_token_was_revoked(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "revoked", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.quota(message))
|
||||
|
||||
assert client.registrations == 1
|
||||
assert handlers.store.get(42) == "fresh-1"
|
||||
assert message.answers and texts.SERVER_UNREACHABLE not in message.answers
|
||||
|
||||
|
||||
def test_a_valid_token_is_used_without_re_registering(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "current", client)
|
||||
|
||||
asyncio.run(handlers.quota(FakeMessage()))
|
||||
|
||||
assert client.registrations == 0
|
||||
assert handlers.store.get(42) == "current"
|
||||
|
||||
|
||||
def test_start_shows_a_working_connect_code_after_revocation(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
handlers = _handlers(tmp_path, "revoked", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.start(message))
|
||||
|
||||
assert "fresh-1" in message.answers[-1]
|
||||
assert "revoked" not in message.answers[-1]
|
||||
|
||||
|
||||
def test_backend_outage_still_reports_unreachable(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
|
||||
def unreachable(token: str) -> dict:
|
||||
raise BackendError("down")
|
||||
|
||||
client.get_quota = unreachable
|
||||
handlers = _handlers(tmp_path, "current", client)
|
||||
message = FakeMessage()
|
||||
|
||||
asyncio.run(handlers.quota(message))
|
||||
|
||||
assert message.answers == [texts.SERVER_UNREACHABLE]
|
||||
assert client.registrations == 0
|
||||
|
||||
|
||||
def test_poller_untracks_and_asks_for_start_when_revoked(tmp_path):
|
||||
client = FakeClient(valid_token="current")
|
||||
store = TokenStore(str(tmp_path / "store.json"))
|
||||
store.set(42, "revoked")
|
||||
store.track("job-1", 42)
|
||||
sent: list[tuple[int, str]] = []
|
||||
|
||||
notifier = CompletionNotifier(bot=None, client=client, store=store)
|
||||
|
||||
async def fake_send(chat_id: int, text: str) -> bool:
|
||||
sent.append((chat_id, text))
|
||||
return True
|
||||
|
||||
notifier._send = fake_send
|
||||
asyncio.run(notifier.poll_once())
|
||||
|
||||
assert store.tracked() == []
|
||||
assert store.get(42) is None
|
||||
assert sent == [(42, texts.NEED_START)]
|
||||
@@ -47,3 +47,15 @@ def test_legacy_token_file_is_migrated(tmp_path):
|
||||
reloaded = TokenStore(str(path))
|
||||
assert reloaded.get(123) == "legacy-token"
|
||||
assert [job_id for job_id, _, _ in reloaded.tracked()] == ["job-x"]
|
||||
|
||||
|
||||
def test_forget_drops_a_token_and_persists(tmp_path):
|
||||
path = str(tmp_path / "store.json")
|
||||
store = TokenStore(path)
|
||||
store.set(42, "old-token")
|
||||
|
||||
store.forget(42)
|
||||
store.forget(99) # unknown chats are a no-op
|
||||
|
||||
assert store.get(42) is None
|
||||
assert TokenStore(path).get(42) is None
|
||||
@@ -5,12 +5,12 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-sokhan}
|
||||
# Required on purpose: shipping a default credential means every
|
||||
# deployment that forgets the .env runs an open database.
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-sokhan}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U sokhan"]
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
@@ -33,25 +33,34 @@ services:
|
||||
build:
|
||||
context: ../backend
|
||||
environment: &backend-env
|
||||
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}@postgres:5432/${POSTGRES_DB:-sokhan}
|
||||
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}@postgres:5432/${POSTGRES_DB:-sokhan}
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
CELERY_ENABLED: "true"
|
||||
DATA_DIR: /data
|
||||
HF_HOME: /data/huggingface
|
||||
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:-}
|
||||
AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-auto}
|
||||
AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax}
|
||||
AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30}
|
||||
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
|
||||
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
|
||||
LLM_API_BASE: ${LLM_API_BASE:-}
|
||||
@@ -91,7 +100,10 @@ services:
|
||||
build:
|
||||
context: ../web
|
||||
args:
|
||||
NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-http://localhost:8000}
|
||||
# Empty: the browser calls /api on the web origin, proxied to the api
|
||||
# service, so the session cookie is first-party on any host.
|
||||
NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-}
|
||||
API_PROXY_TARGET: ${API_PROXY_TARGET:-http://api:8000}
|
||||
ports:
|
||||
- "${SOKHAN_WEB_PORT:-3000}:3000"
|
||||
depends_on:
|
||||
|
||||
+10
-1
@@ -14,12 +14,21 @@ short_description: تبدیل گفتار فارسی به نوشتار — اجر
|
||||
# Sokhan — Persian speech-to-text, in your browser
|
||||
|
||||
A live demo of [Sokhan](https://github.com/Abolfazlrwm/sokhan)'s speech
|
||||
engine that runs **entirely client-side**: Whisper (ONNX, q8) executes on
|
||||
engine that runs **entirely client-side**: Whisper (ONNX) executes on
|
||||
the visitor's own machine via
|
||||
[transformers.js](https://huggingface.co/docs/transformers.js) — nothing
|
||||
is uploaded, no backend, no compute cost. Persian RTL UI, mic recording,
|
||||
file upload and a bundled benchmark sample clip.
|
||||
|
||||
Speed and reliability: the demo picks the fastest backend the browser
|
||||
offers — WebGPU (fp32 encoder + q4 decoder) on Chrome/Edge, WASM q8
|
||||
everywhere else — and owns the 30 s/5 s windowing itself, so it reports
|
||||
per-window progress with an ETA, shows an elapsed timer, enforces a
|
||||
duration cap (30 min on WebGPU, 10 min on WASM) and offers a real cancel
|
||||
button that terminates the worker. Audio is decoded at the context's
|
||||
natural rate and resampled offline to 16 kHz, avoiding a Chromium hang
|
||||
on opus/webm inputs.
|
||||
|
||||
Two untuned checkpoints are selectable (base / small) so anyone can hear
|
||||
the difference. The **fine-tuned** checkpoint
|
||||
([`Abol0pati/whisper-small-fa-sokhan`](https://huggingface.co/Abol0pati/whisper-small-fa-sokhan),
|
||||
|
||||
+467
-48
@@ -1,6 +1,15 @@
|
||||
// Sokhan demo UI wiring — audio capture (mic / file / bundled sample),
|
||||
// resampling to 16 kHz mono, and talking to the transformers.js worker.
|
||||
// All inference happens client-side; see worker.js.
|
||||
//
|
||||
// Reliability notes (this section is the fix for the "eternal processing"
|
||||
// bug): audio is decoded in an AudioContext at its own rate and then
|
||||
// resampled offline to 16 kHz. Forcing a 16 kHz context for
|
||||
// decodeAudioData hangs Chromium on opus/webm (MediaRecorder and Telegram
|
||||
// voice audio) — the symptom was a demo stuck forever at "preparing
|
||||
// audio". Every stage now also has: a watchdog, an elapsed timer, per-
|
||||
// window progress, a hard duration cap, and a cancel button that
|
||||
// terminates the worker, so no input can ever wedge the UI again.
|
||||
|
||||
const SAMPLE_URL =
|
||||
"https://raw.githubusercontent.com/Abolfazlrwm/sokhan/main/benchmarks/data/clips/cv_fa_00001501_39aee6016733.wav";
|
||||
@@ -8,6 +17,11 @@ const SAMPLE_URL =
|
||||
// comparison after the sample is transcribed.
|
||||
const SAMPLE_REFERENCE = "معلومه حسابی قاطی کردی";
|
||||
|
||||
const SAMPLE_RATE = 16000;
|
||||
const FILE_CAP_MB = 60; // pre-decode guard; protects RAM on giant uploads
|
||||
const ABS_MAX_SECONDS = 1800; // hard ceiling even on WebGPU (30 min)
|
||||
const DECODE_TIMEOUT_MS = 45000; // watchdog: decodeAudioData must resolve
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const modelSel = $("model");
|
||||
const micBtn = $("mic");
|
||||
@@ -19,6 +33,193 @@ const barFill = barEl.firstElementChild;
|
||||
const transcriptEl = $("transcript");
|
||||
const metaEl = $("meta");
|
||||
const refEl = $("ref");
|
||||
const badgeEl = $("badge");
|
||||
const cancelBtn = $("cancel");
|
||||
const stampChk = $("stamp");
|
||||
const copyBtn = $("copy");
|
||||
const stageEls = [...document.querySelectorAll("#stages span")];
|
||||
|
||||
// ---------- Persian orthographic polish (v2) ----------
|
||||
// Deterministic port of backend/sokhan/core/fa_polish.py: repairs ZWNJ
|
||||
// placement ("می کنی" -> "میکنی"), split imperatives ("بی پوش" ->
|
||||
// "بپوش"), Arabic look-alike code points and Latin digits. It never
|
||||
// rewords — measured -3.6 WER points on the Persian fixture.
|
||||
|
||||
const _ZWNJ = "\u200c";
|
||||
const POLISH_ARABIC_CHARS = {
|
||||
"ي": "ی", "ى": "ی", "ك": "ک", "ة": "ه", "\u0640": "",
|
||||
"٠": "۰", "١": "۱", "٢": "۲", "٣": "۳", "٤": "۴",
|
||||
"٥": "۵", "٦": "۶", "٧": "۷", "٨": "۸", "٩": "۹",
|
||||
};
|
||||
|
||||
function polishChars(text) {
|
||||
let out = "";
|
||||
for (const ch of text) {
|
||||
if (ch in POLISH_ARABIC_CHARS) out += POLISH_ARABIC_CHARS[ch];
|
||||
else if (ch >= "0" && ch <= "9") out += String.fromCharCode(0x06f0 + (ch.charCodeAt(0) - 48));
|
||||
else out += ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Very common verbs Whisper writes without the ZWNJ: "میکنم" -> "میکنم".
|
||||
const POLISH_ZWNJ_WORDS = new Set([
|
||||
"میکنم", "میکنی", "میکند", "میکنیم", "میکنید", "میکنند",
|
||||
"میشوم", "میشوی", "میشود", "میشویم", "میشوید", "میشوند",
|
||||
"میگویم", "میگویی", "میگوید", "میگوییم", "میگویید", "میگویند",
|
||||
"میگم", "میگی", "میگه", "میگن",
|
||||
"میخواهم", "میخواهی", "میخواهد", "میخواهیم", "میخواهید", "میخواهند",
|
||||
"میخوام", "میخوای", "میخواد", "میخوان",
|
||||
"میدانم", "میدانی", "میداند", "میدانیم", "میدانید", "میدانند",
|
||||
"میدم", "میدی", "میده", "میدن",
|
||||
"میبرم", "میبری", "میبرد", "میبریم", "میبرید", "میبرند",
|
||||
"میرم", "میری", "میره", "میرن",
|
||||
"میروم", "میروی", "میرود", "میرویم", "میروید", "میروند",
|
||||
"میآیم", "میآیی", "میآید", "میآییم", "میآیید", "میآیند",
|
||||
"میشنوم", "میشنوی", "میشنود", "میشنویم", "میشنوید", "میشنوند",
|
||||
"میبینم", "میبینی", "میبیند", "میبینیم", "میبینید", "میبینند",
|
||||
"میشه",
|
||||
"نمیکنم", "نمیکنی", "نمیکند", "نمیکنیم", "نمیکنید", "نمیکنند",
|
||||
"نمیشود", "نمیشه",
|
||||
"نمیگویم", "نمیگم", "نمیگی", "نمیگه", "نمیگن",
|
||||
"نمیخواهم", "نمیخواهد", "نمیخوام", "نمیخواد",
|
||||
"نمیدانم", "نمیدانی", "نمیداند",
|
||||
"نمیدونم", "نمیدونی", "نمیدونه", "نمیدونن",
|
||||
"نمیدم", "نمیدی", "نمیده", "نمیدن",
|
||||
"نمیرم", "نمیری", "نمیره", "نمیرن", "نمیرود",
|
||||
"نمیآید", "نمیاد",
|
||||
"نمیبینم", "نمیبینی", "نمیبیند",
|
||||
]);
|
||||
|
||||
// The imperative "ب" mis-heard as the real word "بی": "بی پوش" -> "بپوش".
|
||||
const POLISH_SPLIT_IMPERATIVES = {
|
||||
"پوش": "بپوش", "بین": "ببین", "بینم": "ببینم", "بینی": "ببینی",
|
||||
"بینید": "ببینید", "بینند": "ببینند", "خواب": "بخواب", "خور": "بخور",
|
||||
"شین": "بشین", "نشین": "بنشین", "گیر": "بگیر", "گو": "بگو",
|
||||
"گوی": "بگو", "بخش": "ببخش",
|
||||
};
|
||||
|
||||
// Separated ZWNJ prefixes/suffixes: "می کنم" -> "میکنم".
|
||||
const POLISH_FUSED_PREFIXES = {
|
||||
"می کنم": "میکنم", "می کنی": "میکنی", "می کند": "میکند",
|
||||
"می کنیم": "میکنیم", "می کنید": "میکنید", "می کنند": "میکنند",
|
||||
"می شود": "میشود", "می شن": "میشن", "می شه": "میشه",
|
||||
"می گویم": "میگویم", "می گوید": "میگوید", "می گم": "میگم",
|
||||
"می گی": "میگی", "می گه": "میگه", "می گن": "میگن",
|
||||
"می خواهم": "میخواهم", "می خواهد": "میخواهد",
|
||||
"می خوام": "میخوام", "می خواد": "میخواد",
|
||||
"می دانم": "میدانم", "می داند": "میداند",
|
||||
"می دونم": "میدونم", "می دم": "میدم", "می دی": "میدی",
|
||||
"می ده": "میده", "می دن": "میدن",
|
||||
"می برم": "میبرم", "می برد": "میبرد",
|
||||
"می رم": "میرم", "می ره": "میره", "می رن": "میرن",
|
||||
"می روم": "میروم", "می رود": "میرود",
|
||||
"می آید": "میآید", "می این": "میاین",
|
||||
"می شنوم": "میشنوم", "می شنوی": "میشنوی", "می شنود": "میشنود",
|
||||
"می بینم": "میبینم", "می بینی": "میبینی", "می بیند": "میبیند",
|
||||
"نمی کنم": "نمیکنم", "نمی کند": "نمیکند",
|
||||
"نمی شود": "نمیشود", "نمی شه": "نمیشه",
|
||||
"نمی گم": "نمیگم", "نمی گه": "نمیگه",
|
||||
"نمی خوام": "نمیخوام", "نمی خواد": "نمیخواد",
|
||||
"نمی دانم": "نمیدانم", "نمی دونم": "نمیدونم",
|
||||
"نمی رم": "نمیرم", "نمی ره": "نمیره", "نمی آید": "نمیآید",
|
||||
"نمی این": "نمیاین", "نمی بینم": "نمیبینم", "نمی بیند": "نمیبیند",
|
||||
};
|
||||
const POLISH_PREFIXES = new Set(["می", "نمی"]);
|
||||
const POLISH_SUFFIXES = new Set(["ها", "های", "هایی", "تر", "ترین"]);
|
||||
const POLISH_PUNCT_EDGES = "،؛:.!?؟…«»()\"'-–—,";
|
||||
const POLISH_CLOSING_PUNCT = "،؛:.!?؟…»)";
|
||||
|
||||
function polishSplitEdges(token) {
|
||||
// Mirror Python's str.strip(chars): peel edge punctuation both sides.
|
||||
let start = 0;
|
||||
let end = token.length;
|
||||
while (start < end && POLISH_PUNCT_EDGES.includes(token[start])) start++;
|
||||
while (end > start && POLISH_PUNCT_EDGES.includes(token[end - 1])) end--;
|
||||
return [token.slice(0, start), token.slice(start, end), token.slice(end)];
|
||||
}
|
||||
|
||||
function polishZwnjInWord(word) {
|
||||
if (word.startsWith("نمی") && word.length > 3) return "نمی" + _ZWNJ + word.slice(3);
|
||||
if (word.startsWith("می") && word.length > 2) return "می" + _ZWNJ + word.slice(2);
|
||||
return word;
|
||||
}
|
||||
|
||||
function polishFuse(tokens) {
|
||||
const out = [];
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const tok = tokens[i];
|
||||
const bare = tok.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("") || tok;
|
||||
const isClean = tok === bare;
|
||||
if (POLISH_PREFIXES.has(bare) && i + 1 < tokens.length && isClean) {
|
||||
const fused = POLISH_FUSED_PREFIXES[`${tok} ${tokens[i + 1]}`] ?? `${tok}${_ZWNJ}${tokens[i + 1]}`;
|
||||
out.push(fused);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (POLISH_SUFFIXES.has(bare) && out.length && isClean) {
|
||||
const prev = out[out.length - 1];
|
||||
const prevCore = prev.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("");
|
||||
if (prevCore && /[\u0600-\u06FF]/.test(prevCore[prevCore.length - 1])) {
|
||||
out[out.length - 1] = prev + _ZWNJ + bare;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(tok);
|
||||
}
|
||||
return out.join(" ");
|
||||
}
|
||||
|
||||
function polishTokens(text) {
|
||||
const tokens = text.split(/\s+/).filter(Boolean);
|
||||
const fixed = [];
|
||||
for (const token of tokens) {
|
||||
const [leading, core, trailing] = polishSplitEdges(token);
|
||||
if (!core) { fixed.push(token); continue; }
|
||||
const repaired = POLISH_ZWNJ_WORDS.has(core) ? polishZwnjInWord(core) : core;
|
||||
fixed.push(leading + repaired + trailing);
|
||||
}
|
||||
const fused = polishFuse(fixed).split(/\s+/);
|
||||
const repaired = [];
|
||||
for (const token of fused) {
|
||||
const core = polishSplitEdges(token)[1];
|
||||
const prev = repaired.length ? repaired[repaired.length - 1] : "";
|
||||
const prevCore = prev.split("").filter((c) => !POLISH_PUNCT_EDGES.includes(c)).join("");
|
||||
if (core && POLISH_SPLIT_IMPERATIVES[core] && (prevCore === "بی" || prevCore === "به")) {
|
||||
repaired[repaired.length - 1] = POLISH_SPLIT_IMPERATIVES[core];
|
||||
continue;
|
||||
}
|
||||
repaired.push(token);
|
||||
}
|
||||
return repaired.join(" ");
|
||||
}
|
||||
|
||||
function polishSpacing(text) {
|
||||
text = text.split(_ZWNJ + " ").join(_ZWNJ).split(" " + _ZWNJ).join(_ZWNJ);
|
||||
let out = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (POLISH_CLOSING_PUNCT.includes(ch) && out.endsWith(" ")) out = out.slice(0, -1);
|
||||
out += ch;
|
||||
const nxt = text[i + 1] || "";
|
||||
if (POLISH_CLOSING_PUNCT.includes(ch) && nxt && !POLISH_CLOSING_PUNCT.includes(nxt) && nxt !== " ") {
|
||||
const prevCh = out.length >= 2 ? out[out.length - 2] : "";
|
||||
const digitClass = /[0-9\u06F0-\u06F9]/;
|
||||
const isDecimal = ch === "." && digitClass.test(prevCh) && digitClass.test(nxt);
|
||||
if (!isDecimal) out += " ";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function polishTranscript(text) {
|
||||
if (!text || !text.trim()) return text;
|
||||
return polishSpacing(polishTokens(polishChars(text))).trim();
|
||||
}
|
||||
|
||||
function polishTranscriptParagraph(text) {
|
||||
return text.split("\n").map((line) => polishTranscript(line)).join("\n");
|
||||
}
|
||||
|
||||
// ---------- Persian punctuation restoration ----------
|
||||
// Same rule family as backend/sokhan/core/punctuation.py (the worker
|
||||
@@ -60,16 +261,45 @@ function restorePunctuationParagraph(text) {
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
const worker = new Worker("worker.js?v=3", { type: "module" });
|
||||
let busy = false;
|
||||
// ---------- small formatting helpers ----------
|
||||
|
||||
const FA_DIGITS = "۰۱۲۳۴۵۶۷۸۹";
|
||||
const faDigits = (s) => String(s).replace(/\d/g, (d) => FA_DIGITS[d]);
|
||||
|
||||
function mmss(t) {
|
||||
const s = Math.max(0, Math.floor(t));
|
||||
const m = Math.floor(s / 60);
|
||||
return `${faDigits(String(m).padStart(2, "0"))}:${faDigits(String(s % 60).padStart(2, "0"))}`;
|
||||
}
|
||||
|
||||
const DEVICE_LABELS = { webgpu: "WebGPU", wasm: "CPU (WASM)" };
|
||||
|
||||
// ---------- stage pills ----------
|
||||
|
||||
function setStage(n) {
|
||||
stageEls.forEach((el, i) => {
|
||||
el.classList.toggle("active", i + 1 === n);
|
||||
el.classList.toggle("done", n > i + 1);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- worker plumbing ----------
|
||||
|
||||
let worker = null;
|
||||
let busy = false;
|
||||
let runId = 0; // generation counter: any late async callback from a
|
||||
// cancelled/stale run is dropped instead of touching the UI
|
||||
let tickerHandle = null;
|
||||
let baseStatus = "";
|
||||
let lastAudioSeconds = 0;
|
||||
let lastResult = null; // { text, segments } for the timestamp toggle
|
||||
|
||||
const downloads = new Map(); // file -> { loaded, total }
|
||||
|
||||
worker.onmessage = (event) => {
|
||||
function onWorkerMessage(event) {
|
||||
const { type, payload } = event.data;
|
||||
if (type === "progress") {
|
||||
setStage(2);
|
||||
downloads.set(payload.file, payload);
|
||||
const loaded = [...downloads.values()].reduce((s, d) => s + d.loaded, 0);
|
||||
const total = [...downloads.values()].reduce((s, d) => s + d.total, 0);
|
||||
@@ -77,48 +307,146 @@ worker.onmessage = (event) => {
|
||||
const pct = Math.round((loaded / total) * 100);
|
||||
barEl.style.display = "block";
|
||||
barFill.style.width = `${pct}%`;
|
||||
statusEl.textContent = `در حال دانلود مدل … ${pct}%`;
|
||||
setBaseStatus(`در حال دانلود مدل … ${faDigits(pct)}٪`);
|
||||
}
|
||||
} else if (type === "device") {
|
||||
badgeEl.textContent = `روی ${DEVICE_LABELS[payload] || payload}`;
|
||||
badgeEl.style.display = "inline-block";
|
||||
} else if (type === "status" && payload === "ready") {
|
||||
setStage(3);
|
||||
barEl.style.display = "none";
|
||||
statusEl.textContent = "مدل آماده است — در حال پیادهسازی …";
|
||||
setBaseStatus("مدل آماده است — در حال پیادهسازی …");
|
||||
} else if (type === "status") {
|
||||
statusEl.textContent = payload;
|
||||
setBaseStatus(payload);
|
||||
} else if (type === "chunk-progress") {
|
||||
const { done, total, elapsed } = payload;
|
||||
const pct = Math.min(99, Math.round((done / Math.max(1, total)) * 100));
|
||||
barEl.style.display = "block";
|
||||
barFill.style.width = `${pct}%`;
|
||||
let eta = "";
|
||||
if (done >= 1 && done < total) {
|
||||
const per = elapsed / done;
|
||||
const remain = Math.round((total - done) * per);
|
||||
if (remain > 3) eta = ` — تخمین پایان: ~${faDigits(remain)} ثانیه`;
|
||||
}
|
||||
setBaseStatus(
|
||||
`در حال پیادهسازی — قطعهٔ ${faDigits(done)} از ${faDigits(total)} (${faDigits(pct)}٪)${eta}`
|
||||
);
|
||||
} else if (type === "result") {
|
||||
finish(payload.text, payload.elapsed);
|
||||
finish(payload);
|
||||
} else if (type === "error") {
|
||||
busy = false;
|
||||
unlock();
|
||||
barEl.style.display = "none";
|
||||
statusEl.textContent = "خطا: " + payload;
|
||||
fail("خطا: " + payload);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function wireWorker() {
|
||||
worker.onmessage = onWorkerMessage;
|
||||
worker.onerror = (e) => {
|
||||
console.error(e);
|
||||
if (busy) fail("خطای worker: " + (e.message || "نامشخص"));
|
||||
};
|
||||
}
|
||||
|
||||
function spawnWorker() {
|
||||
worker = new Worker("worker.js?v=4", { type: "module" });
|
||||
wireWorker();
|
||||
}
|
||||
|
||||
function setBaseStatus(text) {
|
||||
baseStatus = text;
|
||||
statusEl.textContent = text;
|
||||
}
|
||||
|
||||
function tick() {
|
||||
const startedAt = Number(statusEl.dataset.started || 0);
|
||||
if (!startedAt) return;
|
||||
const sec = Math.round((Date.now() - startedAt) / 1000);
|
||||
if (sec >= 5) statusEl.textContent = `${baseStatus} — ${faDigits(sec)} ثانیه گذشته`;
|
||||
}
|
||||
|
||||
function startTicker() {
|
||||
stopTicker();
|
||||
statusEl.dataset.started = String(Date.now());
|
||||
tickerHandle = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function stopTicker() {
|
||||
if (tickerHandle) clearInterval(tickerHandle);
|
||||
tickerHandle = null;
|
||||
delete statusEl.dataset.started;
|
||||
}
|
||||
|
||||
function setStatus(text) {
|
||||
// One-shot status (not part of the ticking base line).
|
||||
stopTicker();
|
||||
baseStatus = text;
|
||||
statusEl.textContent = text;
|
||||
}
|
||||
|
||||
function startWork(message) {
|
||||
// runId is owned by the entry points (sample/file/mic/cancel); startWork
|
||||
// must not bump it — transcribeRaw compares its own id after this call.
|
||||
busy = true;
|
||||
lock();
|
||||
downloads.clear();
|
||||
refEl.style.display = "none";
|
||||
badgeEl.style.display = "none";
|
||||
transcriptEl.textContent = "(در حال پردازش…)";
|
||||
metaEl.textContent = "";
|
||||
setStatus(message);
|
||||
copyBtn.style.display = "none";
|
||||
lastResult = null;
|
||||
barEl.style.display = "none";
|
||||
barFill.style.width = "0%";
|
||||
cancelBtn.style.display = "inline-block";
|
||||
setBaseStatus(message);
|
||||
startTicker();
|
||||
}
|
||||
|
||||
function finish(text, elapsedSeconds) {
|
||||
setStatus("تمام شد — میتوانید کلیپ دیگری امتحان کنید.");
|
||||
transcriptEl.textContent =
|
||||
restorePunctuationParagraph(text) || "(متنی تشخیص داده نشد — شاید صدا کوتاه یا نویزی بود.)";
|
||||
const audioSeconds = window.__lastAudioSeconds || 0;
|
||||
metaEl.textContent =
|
||||
`زمان پردازش: ${elapsedSeconds.toFixed(1)} ثانیه` +
|
||||
(audioSeconds ? ` برای ${audioSeconds.toFixed(1)} ثانیه صدا` : "") +
|
||||
" — کاملاً روی دستگاه شما.";
|
||||
function endRun() {
|
||||
busy = false;
|
||||
stopTicker();
|
||||
unlock();
|
||||
cancelBtn.style.display = "none";
|
||||
barEl.style.display = "none";
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
endRun();
|
||||
setStage(0);
|
||||
statusEl.textContent = message;
|
||||
transcriptEl.textContent = "(پردازش انجام نشد.)";
|
||||
}
|
||||
|
||||
function finish(payload) {
|
||||
lastResult = { text: payload.text || "", segments: payload.segments || [] };
|
||||
endRun();
|
||||
setStage(4);
|
||||
setStatus("تمام شد — میتوانید کلیپ دیگری امتحان کنید.");
|
||||
renderTranscript();
|
||||
const device = DEVICE_LABELS[payload.device] || payload.device || "";
|
||||
metaEl.textContent =
|
||||
`زمان پردازش: ${faDigits(payload.elapsed.toFixed(1))} ثانیه` +
|
||||
(lastAudioSeconds ? ` برای ${faDigits(lastAudioSeconds.toFixed(1))} ثانیه صدا` : "") +
|
||||
(payload.windows > 1 ? ` در ${faDigits(payload.windows)} قطعه` : "") +
|
||||
(device ? ` روی ${device}` : "") +
|
||||
" — کاملاً روی دستگاه شما.";
|
||||
copyBtn.style.display = "inline-block";
|
||||
}
|
||||
|
||||
function renderTranscript() {
|
||||
if (!lastResult) return;
|
||||
if (stampChk.checked && lastResult.segments.length) {
|
||||
const lines = lastResult.segments.map(
|
||||
(s) =>
|
||||
`[${mmss(s.start)}–${mmss(s.end)}] ` +
|
||||
restorePunctuation(polishTranscript(s.text))
|
||||
);
|
||||
transcriptEl.textContent = lines.join("\n");
|
||||
} else {
|
||||
transcriptEl.textContent =
|
||||
restorePunctuationParagraph(polishTranscriptParagraph(lastResult.text)) ||
|
||||
"(متنی تشخیص داده نشد — شاید صدا کوتاه یا نویزی بود.)";
|
||||
}
|
||||
}
|
||||
|
||||
function lock() {
|
||||
@@ -138,22 +466,44 @@ function unlock() {
|
||||
// ---------- audio -> 16 kHz mono Float32 ----------
|
||||
|
||||
async function decodeTo16k(arrayBuffer) {
|
||||
const ctx = new AudioContext({ sampleRate: 16000 });
|
||||
// Decode at the context's natural rate (never a forced 16 kHz context —
|
||||
// Chromium can hang forever on opus/webm there), then resample offline
|
||||
// to exactly 16 kHz mono. A watchdog turns a wedged decode into a
|
||||
// visible error instead of an eternal spinner.
|
||||
const decodeCtx = new AudioContext();
|
||||
let decoded;
|
||||
try {
|
||||
const buffer = await ctx.decodeAudioData(arrayBuffer);
|
||||
// Mix down to mono if the clip has multiple channels.
|
||||
let data = buffer.getChannelData(0);
|
||||
if (buffer.numberOfChannels > 1) {
|
||||
data = new Float32Array(buffer.length);
|
||||
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||||
const ch = buffer.getChannelData(c);
|
||||
for (let i = 0; i < ch.length; i++) data[i] += ch[i] / buffer.numberOfChannels;
|
||||
}
|
||||
}
|
||||
return { audio: data, seconds: buffer.duration };
|
||||
decoded = await Promise.race([
|
||||
decodeCtx.decodeAudioData(arrayBuffer),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error("زمان زیادی برای رمزگشایی صدا گذشت")),
|
||||
DECODE_TIMEOUT_MS
|
||||
)
|
||||
),
|
||||
]);
|
||||
} finally {
|
||||
ctx.close();
|
||||
decodeCtx.close().catch(() => {});
|
||||
}
|
||||
const frames = Math.max(1, Math.ceil(decoded.duration * SAMPLE_RATE));
|
||||
const offline = new OfflineAudioContext(1, frames, SAMPLE_RATE);
|
||||
const source = offline.createBufferSource();
|
||||
source.buffer = decoded;
|
||||
source.connect(offline.destination);
|
||||
source.start();
|
||||
const rendered = await offline.startRendering();
|
||||
// slice(): detach from the OfflineAudioContext's internal buffer so the
|
||||
// Float32Array's own buffer is transferable to the worker.
|
||||
return { audio: rendered.getChannelData(0).slice(), seconds: decoded.duration };
|
||||
}
|
||||
|
||||
function tooLong(seconds) {
|
||||
return (
|
||||
`این صدا ${faDigits(Math.round(seconds / 60))} دقیقه است؛ دموی مرورگری برای ` +
|
||||
`کلیپهای تا ${faDigits(ABS_MAX_SECONDS / 60)} دقیقه طراحی شده (روی CPU سقف کمتر است). ` +
|
||||
"برای فایلهای بلندتر، نسخهٔ سلفهاست را اجرا کنید: " +
|
||||
"github.com/Abolfazlrwm/sokhan/tree/main/deploy"
|
||||
);
|
||||
}
|
||||
|
||||
async function transcribeArrayBuffer(arrayBuffer, sourceLabel) {
|
||||
@@ -164,22 +514,41 @@ async function transcribeArrayBuffer(arrayBuffer, sourceLabel) {
|
||||
// Core flow without the busy guard — for callers that manage `busy`
|
||||
// themselves (the sample button fetches first, then starts the pipeline).
|
||||
async function transcribeRaw(arrayBuffer, sourceLabel) {
|
||||
const id = ++runId;
|
||||
startWork(`در حال آمادهسازی صدا (${sourceLabel}) …`);
|
||||
setStage(1);
|
||||
try {
|
||||
const { audio, seconds } = await decodeTo16k(arrayBuffer);
|
||||
if (id !== runId) return; // cancelled while decoding
|
||||
if (seconds < 0.3) {
|
||||
busy = false;
|
||||
unlock();
|
||||
endRun();
|
||||
setStage(0);
|
||||
transcriptEl.textContent = "(صدا خیلی کوتاه است.)";
|
||||
setStatus("صدا خیلی کوتاه است — حداقل نیم ثانیه لازم است.");
|
||||
return;
|
||||
}
|
||||
window.__lastAudioSeconds = seconds;
|
||||
worker.postMessage({ kind: "transcribe", audio, modelId: modelSel.value });
|
||||
lastAudioSeconds = seconds;
|
||||
if (seconds > ABS_MAX_SECONDS) {
|
||||
endRun();
|
||||
setStage(0);
|
||||
transcriptEl.textContent = "(فایل بیش از حد بلند است.)";
|
||||
setStatus(tooLong(seconds));
|
||||
return;
|
||||
}
|
||||
setStage(3); // worker will drop back to stage 2 if the model needs downloading
|
||||
setBaseStatus("در حال آمادهسازی مدل …");
|
||||
// Transfer the buffer: the audio is not needed on this thread anymore.
|
||||
worker.postMessage(
|
||||
{ kind: "transcribe", audio, modelId: modelSel.value, seconds },
|
||||
[audio.buffer]
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
busy = false;
|
||||
unlock();
|
||||
setStatus("خطا در خواندن فایل صوتی: " + err.message);
|
||||
if (id !== runId) return;
|
||||
fail(
|
||||
"خطا در خواندن فایل صوتی: " + err.message +
|
||||
" — اگر فایل OGG است، سافاری از آن پشتیبانی نمیکند؛ Chrome یا فایل MP3/WAV را امتحان کنید."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,23 +556,31 @@ async function transcribeRaw(arrayBuffer, sourceLabel) {
|
||||
|
||||
sampleBtn.onclick = async () => {
|
||||
if (busy) return;
|
||||
const id = ++runId;
|
||||
busy = true;
|
||||
lock();
|
||||
downloads.clear();
|
||||
refEl.style.display = "none";
|
||||
badgeEl.style.display = "none";
|
||||
transcriptEl.textContent = "(در حال پردازش…)";
|
||||
metaEl.textContent = "";
|
||||
setStatus("در حال دریافت کلیپ نمونه (از فیکسچر بنچمارک پروژه) …");
|
||||
copyBtn.style.display = "none";
|
||||
cancelBtn.style.display = "inline-block";
|
||||
setStage(1);
|
||||
setBaseStatus("در حال دریافت کلیپ نمونه (از فیکسچر بنچمارک پروژه) …");
|
||||
startTicker();
|
||||
try {
|
||||
const res = await fetch(SAMPLE_URL);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
if (id !== runId) return;
|
||||
refEl.innerHTML = `<b>متن مرجع (انسان):</b> ${SAMPLE_REFERENCE}`;
|
||||
refEl.style.display = "block";
|
||||
await transcribeRaw(await res.arrayBuffer(), "نمونه");
|
||||
const ab = await res.arrayBuffer();
|
||||
busy = false; // transcribeRaw owns the guard from here (no await between this and startWork)
|
||||
await transcribeRaw(ab, "نمونه");
|
||||
} catch (err) {
|
||||
busy = false;
|
||||
unlock();
|
||||
setStatus("دریافت نمونه ناموفق بود: " + err.message);
|
||||
if (id !== runId) return;
|
||||
fail("دریافت نمونه ناموفق بود: " + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -227,6 +604,10 @@ micBtn.onclick = async () => {
|
||||
micBtn.classList.remove("recording");
|
||||
const blob = new Blob(recordChunks, { type: recorder.mimeType });
|
||||
recorder = null;
|
||||
if (blob.size > FILE_CAP_MB * 1024 * 1024) {
|
||||
setStatus(`ضبط شما ${faDigits(Math.round(blob.size / 1048576))} مگابایت است؛ سقف دمو ${faDigits(FILE_CAP_MB)} مگابایت است.`);
|
||||
return;
|
||||
}
|
||||
await transcribeArrayBuffer(await blob.arrayBuffer(), "ضبط میکروفن");
|
||||
};
|
||||
recorder.start();
|
||||
@@ -241,6 +622,44 @@ micBtn.onclick = async () => {
|
||||
fileInput.onchange = async () => {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
if (!file) return;
|
||||
await transcribeArrayBuffer(await file.arrayBuffer(), "فایل");
|
||||
fileInput.value = "";
|
||||
if (file.size > FILE_CAP_MB * 1024 * 1024) {
|
||||
setStatus(
|
||||
`فایل ${faDigits(Math.round(file.size / 1048576))} مگابایت است؛ سقف دمو ` +
|
||||
`${faDigits(FILE_CAP_MB)} مگابایت است — کلیپ را کوتاهتر کنید.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
await transcribeArrayBuffer(await file.arrayBuffer(), "فایل");
|
||||
};
|
||||
|
||||
// ---------- cancel / copy / timestamp toggle ----------
|
||||
|
||||
cancelBtn.onclick = () => {
|
||||
runId += 1;
|
||||
worker.terminate();
|
||||
spawnWorker(); // fresh worker; model files stay in the browser cache
|
||||
busy = false;
|
||||
recorder = null;
|
||||
endRun();
|
||||
setStage(0);
|
||||
setStatus("لغو شد — مدل در حافظهٔ مرورگر مانده و اجرای بعدی سریع است.");
|
||||
transcriptEl.textContent = "(لغو شد.)";
|
||||
};
|
||||
|
||||
copyBtn.onclick = async () => {
|
||||
if (!lastResult) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(transcriptEl.textContent);
|
||||
copyBtn.textContent = "کپی شد";
|
||||
setTimeout(() => {
|
||||
copyBtn.textContent = "کپی متن";
|
||||
}, 1500);
|
||||
} catch (err) {
|
||||
setStatus("کپی ناموفق بود: " + err.message);
|
||||
}
|
||||
};
|
||||
|
||||
stampChk.onchange = renderTranscript;
|
||||
|
||||
spawnWorker();
|
||||
+41
-6
@@ -48,6 +48,22 @@
|
||||
button.primary:hover:not(:disabled) { color: #fff; filter: brightness(1.07); }
|
||||
button.recording { background: var(--err); border: none; color: #fff; }
|
||||
#status { font-size: 0.92rem; color: var(--muted); min-height: 1.6em; margin: 14px 0 6px; }
|
||||
.stages { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 4px; }
|
||||
.stages span { font-size: 0.78rem; color: var(--muted); border: 1px solid var(--line);
|
||||
border-radius: 99px; padding: 3px 10px; background: #fff; opacity: .55; }
|
||||
.stages span.active { opacity: 1; color: #fff; font-weight: 600; border-color: transparent;
|
||||
background: linear-gradient(135deg, var(--accent), var(--accent-2)); }
|
||||
.stages span.done { opacity: .9; color: var(--ok); border-color: #a7f3d0; background: #ecfdf5; }
|
||||
.badge { display: inline-block; font-size: 0.75rem; border-radius: 99px; padding: 2px 9px;
|
||||
background: #eef2ff; color: var(--accent); font-weight: 600; }
|
||||
#cancel { display: none; border-color: var(--err); color: var(--err); font-size: 0.85rem;
|
||||
padding: 5px 12px; }
|
||||
#cancel:hover:not(:disabled) { background: var(--err); color: #fff; }
|
||||
.trow { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;
|
||||
gap: 8px; margin-bottom: 8px; }
|
||||
label.chk { font-size: 0.82rem; color: var(--muted); display: flex; gap: 6px; align-items: center;
|
||||
cursor: pointer; }
|
||||
button.mini { font-size: 0.82rem; padding: 5px 12px; }
|
||||
.bar { height: 8px; background: #eef0f5; border-radius: 99px; overflow: hidden; display: none; }
|
||||
.bar > div { height: 100%; width: 0%; border-radius: 99px;
|
||||
background: linear-gradient(90deg, var(--accent), var(--accent-2)); transition: width .2s ease; }
|
||||
@@ -77,12 +93,18 @@
|
||||
<div class="privacy">🔒 حریم خصوصی کامل: صدا فقط در مرورگر شما پردازش میشود — به هیچ سروری ارسال نمیشود.</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="stages" id="stages">
|
||||
<span>۱ · آمادهسازی صدا</span>
|
||||
<span>۲ · دانلود مدل</span>
|
||||
<span>۳ · پیادهسازی</span>
|
||||
<span>۴ · پایان</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div>
|
||||
<label class="field" for="model">کدام مدل؟ (اولین بار دانلود میشود)</label>
|
||||
<select id="model">
|
||||
<option value="Xenova/whisper-base" selected>پایه (base) — سریع، دانلود ~۷۵ مگابایت</option>
|
||||
<option value="Xenova/whisper-small">کوچک (small) — دقیقتر اما کندتر</option>
|
||||
<option value="Xenova/whisper-small" selected>کوچک (small) — دقیقتر، دانلود ~۲۵۰ مگابایت (پیشنهادی)</option>
|
||||
<option value="Xenova/whisper-base">پایه (base) — سریعتر، دانلود ~۷۵ مگابایت</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="flex:1"></div>
|
||||
@@ -96,18 +118,31 @@
|
||||
|
||||
<div id="status">برای شروع، «نمونهی آماده» را بزنید یا صدا ضبط/انتخاب کنید.</div>
|
||||
<div class="bar" id="bar"><div></div></div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<span class="badge" id="badge" style="display:none"></span>
|
||||
<div style="flex:1"></div>
|
||||
<button id="cancel">لغو پردازش</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label class="field">متن پیادهشده</label>
|
||||
<div class="trow">
|
||||
<label class="field">متن پیادهشده</label>
|
||||
<div class="row" style="gap:10px">
|
||||
<label class="chk"><input type="checkbox" id="stamp"> خطبهخط با زمان</label>
|
||||
<button class="mini" id="copy" style="display:none">کپی متن</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="transcript" dir="rtl">(اینجا نوشته میشود…)</div>
|
||||
<div id="meta"></div>
|
||||
<div id="ref"></div>
|
||||
</div>
|
||||
|
||||
<p class="note">
|
||||
صادقانه: این دمو چکپوینتهای <b>پایهی</b> Whisper را در مرورگر اجرا میکند
|
||||
(Common Voice فارسی محاورهای و پرنویز است؛ انتظار خطا داشته باشید).
|
||||
صادقانه: دقت Whisper روی Common Voice فارسی (محاورهای و پرنویز) محدود است.
|
||||
متن خروجی با پولیش ارتوگرافی فارسی (نیمفاصله، حروف عربی، فعلهای شکسته) تمیز میشود —
|
||||
همان پستپروسس نسخهٔ سرور.
|
||||
در Chrome و Edge با WebGPU خیلی سریعتر است؛ سایر مرورگرها روی WASM با سقف مدت اجرا میکنند.
|
||||
چکپوینت ریزتنظیمشدهی Sokhan روی <a href="https://huggingface.co/Abol0pati/whisper-small-fa-sokhan">Hub</a>
|
||||
موجود است و اپ Gradio آن برای اجرای روی سرور خودتان در
|
||||
<a href="https://github.com/Abolfazlrwm/sokhan/tree/main/space/gradio">space/gradio/</a>
|
||||
@@ -122,6 +157,6 @@
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<script type="module" src="demo.js?v=2"></script>
|
||||
<script type="module" src="demo.js?v=4"></script>
|
||||
</body>
|
||||
</html>
|
||||
+185
-31
@@ -1,25 +1,63 @@
|
||||
// Sokhan demo worker — runs Whisper entirely in the browser via
|
||||
// transformers.js. The worker keeps model download + inference off the UI
|
||||
// thread. Nothing about this app calls a server: the model and the audio
|
||||
// both live on the visitor's machine.
|
||||
// thread and reports per-window progress so a long clip always feels
|
||||
// alive instead of sitting at an eternal "processing" state.
|
||||
// Nothing about this app calls a server: the model and the audio both
|
||||
// live on the visitor's machine.
|
||||
//
|
||||
// Speed model:
|
||||
// - WebGPU (Chrome/Edge with a working GPU adapter): fp32 encoder and
|
||||
// q4 decoder on the GPU — the fast path, several times faster than WASM.
|
||||
// - WASM SIMD fallback (Firefox / Safari / no adapter): q8 everywhere.
|
||||
// Correct but single-threaded, so durations are capped and progress is
|
||||
// reported per 30-second window with an ETA.
|
||||
//
|
||||
// Chunking is done here (30 s windows, 5 s overlap, timestamp-midpoint
|
||||
// trimming) instead of relying on the pipeline's chunk_length_s, because
|
||||
// transformers.js 3.8.1 exposes no per-chunk callback — and owning the
|
||||
// loop is what makes real progress reporting and clean caps possible.
|
||||
// Segments whose midpoint falls in the non-overlapping core of each
|
||||
// window are kept, which removes seam duplication without the token-level
|
||||
// LCS merge the pipeline does internally.
|
||||
|
||||
import { pipeline, env } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
|
||||
|
||||
// The model repos live on the HF Hub; never look for local copies.
|
||||
env.allowLocalModels = false;
|
||||
|
||||
const SAMPLE_RATE = 16000;
|
||||
const WINDOW_SECONDS = 30; // whisper's native window
|
||||
const STRIDE_SECONDS = 5; // overlap on each side of a window
|
||||
const WINDOW = WINDOW_SECONDS * SAMPLE_RATE;
|
||||
const JUMP = WINDOW - 2 * STRIDE_SECONDS * SAMPLE_RATE; // 20 s of new audio per window
|
||||
const MAX_SECONDS = { webgpu: 1800, wasm: 600 };
|
||||
|
||||
let asr = null;
|
||||
let currentModelId = null;
|
||||
let currentDevice = null;
|
||||
|
||||
async function loadModel(modelId) {
|
||||
if (asr && currentModelId === modelId) return;
|
||||
currentModelId = null;
|
||||
asr = null;
|
||||
post("status", `در حال دانلود مدل ${modelId} …`);
|
||||
function post(type, payload) {
|
||||
self.postMessage({ type, payload });
|
||||
}
|
||||
|
||||
async function gpuAvailable() {
|
||||
try {
|
||||
if (!self.navigator || !self.navigator.gpu) return false;
|
||||
const adapter = await self.navigator.gpu.requestAdapter();
|
||||
return !!adapter;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModel(modelId, device) {
|
||||
post("status", `در حال دانلود مدل ${modelId} (${device === "webgpu" ? "WebGPU" : "CPU"}) …`);
|
||||
const config =
|
||||
device === "webgpu"
|
||||
? { device: "webgpu", dtype: { encoder_model: "fp32", decoder_model_merged: "q4" } }
|
||||
: { device: "wasm", dtype: { encoder_model: "q8", decoder_model_merged: "q8" } };
|
||||
asr = await pipeline("automatic-speech-recognition", modelId, {
|
||||
// q8 keeps whisper-base at ~75 MB and runs on plain WASM SIMD —
|
||||
// deterministic on every browser, no WebGPU requirement.
|
||||
dtype: { encoder_model: "q8", decoder_model_merged: "q8" },
|
||||
...config,
|
||||
progress_callback: (p) => {
|
||||
if (p.status === "progress" && p.total) {
|
||||
post("progress", { file: p.file, loaded: p.loaded, total: p.total });
|
||||
@@ -27,38 +65,154 @@ async function loadModel(modelId) {
|
||||
},
|
||||
});
|
||||
currentModelId = modelId;
|
||||
currentDevice = device;
|
||||
post("device", device);
|
||||
post("status", "ready");
|
||||
}
|
||||
|
||||
async function transcribe(audioF32, modelId) {
|
||||
await loadModel(modelId);
|
||||
post("status", "در حال پیادهسازی …");
|
||||
const start = performance.now();
|
||||
const out = await asr(audioF32, {
|
||||
language: "fa",
|
||||
task: "transcribe",
|
||||
chunk_length_s: 30,
|
||||
stride_length_s: 5,
|
||||
});
|
||||
const elapsed = (performance.now() - start) / 1000;
|
||||
post("result", { text: (out.text || "").trim(), elapsed });
|
||||
/** Load the requested model on the fastest device this browser supports. */
|
||||
async function loadBest(modelId) {
|
||||
if (asr && currentModelId === modelId) return;
|
||||
asr = null;
|
||||
currentModelId = null;
|
||||
currentDevice = null;
|
||||
if (await gpuAvailable()) {
|
||||
try {
|
||||
await loadModel(modelId, "webgpu");
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error("WebGPU load failed; falling back to WASM", err);
|
||||
post("status", "WebGPU در دسترس نبود — بازگشت به حالت CPU …");
|
||||
asr = null;
|
||||
}
|
||||
}
|
||||
await loadModel(modelId, "wasm");
|
||||
}
|
||||
|
||||
function post(type, payload) {
|
||||
self.postMessage({ type, payload });
|
||||
function countWindows(seconds) {
|
||||
if (!(seconds > 0)) seconds = 1;
|
||||
if (seconds <= WINDOW_SECONDS) return 1;
|
||||
return 1 + Math.ceil((seconds - WINDOW_SECONDS) / (JUMP / SAMPLE_RATE));
|
||||
}
|
||||
|
||||
/**
|
||||
* One 30-second window -> trimmed segments with GLOBAL timestamps.
|
||||
* The window is transcribed with return_timestamps; segments whose
|
||||
* midpoint lies inside the window's non-overlapping core are kept, so
|
||||
* consecutive windows never duplicate the phrase spoken across a seam.
|
||||
*/
|
||||
async function transcribeWindow(samples, offsetSeconds, isFirst, isLast) {
|
||||
const out = await asr(samples, {
|
||||
language: "fa",
|
||||
task: "transcribe",
|
||||
return_timestamps: true,
|
||||
});
|
||||
const windowStart = offsetSeconds;
|
||||
const coreStart = windowStart + (isFirst ? 0 : STRIDE_SECONDS);
|
||||
const coreEnd =
|
||||
windowStart + samples.length / SAMPLE_RATE - (isLast ? 0 : STRIDE_SECONDS);
|
||||
const segments = [];
|
||||
for (const s of out.chunks || []) {
|
||||
const t0 = Array.isArray(s.timestamp) ? s.timestamp[0] ?? 0 : 0;
|
||||
const t1 = Array.isArray(s.timestamp) ? s.timestamp[1] ?? t0 : t0;
|
||||
const start = windowStart + t0;
|
||||
const end = windowStart + t1;
|
||||
const mid = (start + end) / 2;
|
||||
if (mid < coreStart || mid > coreEnd) continue;
|
||||
const text = (s.text || "").trim();
|
||||
if (!text) continue;
|
||||
segments.push({ start, end, text });
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
async function transcribe(audio, modelId, seconds) {
|
||||
await loadBest(modelId);
|
||||
|
||||
if (!seconds || seconds <= 0) seconds = audio.length / SAMPLE_RATE;
|
||||
const cap = MAX_SECONDS[currentDevice] ?? MAX_SECONDS.wasm;
|
||||
if (seconds > cap) {
|
||||
post(
|
||||
"error",
|
||||
`این فایل ${Math.round(seconds / 60)} دقیقه است؛ سقف دموی مرورگری روی ` +
|
||||
`${currentDevice === "webgpu" ? "WebGPU" : "CPU"} حدود ${Math.round(cap / 60)} دقیقه است. ` +
|
||||
"برای فایلهای بلندتر، نسخهٔ سلفهاست (backend) را اجرا کنید."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
post("status", "در حال پیادهسازی …");
|
||||
const total = countWindows(seconds);
|
||||
const started = performance.now();
|
||||
const segments = [];
|
||||
let offset = 0;
|
||||
let done = 0;
|
||||
let retriedOnWasm = false;
|
||||
|
||||
while (true) {
|
||||
const offsetEnd = offset + WINDOW;
|
||||
const sub = audio.subarray(offset, Math.min(offsetEnd, audio.length));
|
||||
const isFirst = offset === 0;
|
||||
const isLast = offsetEnd >= audio.length;
|
||||
let windowSegments;
|
||||
try {
|
||||
windowSegments = await transcribeWindow(
|
||||
sub,
|
||||
offset / SAMPLE_RATE,
|
||||
isFirst,
|
||||
isLast
|
||||
);
|
||||
} catch (err) {
|
||||
if (currentDevice === "webgpu" && !retriedOnWasm) {
|
||||
// Driver hiccup on the GPU path: reload once on CPU and redo the
|
||||
// current window; earlier windows stay valid.
|
||||
console.error("WebGPU inference failed; retrying on WASM", err);
|
||||
asr = null;
|
||||
currentModelId = null;
|
||||
await loadModel(modelId, "wasm");
|
||||
retriedOnWasm = true;
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
segments.push(...windowSegments);
|
||||
done += 1;
|
||||
const elapsed = (performance.now() - started) / 1000;
|
||||
post("chunk-progress", { done, total, elapsed });
|
||||
if (isLast) break;
|
||||
offset += JUMP;
|
||||
}
|
||||
|
||||
segments.sort((a, b) => a.start - b.start);
|
||||
const text = segments
|
||||
.map((s) => s.text)
|
||||
.join(" ")
|
||||
.replace(/\s{2,}/g, " ")
|
||||
.trim();
|
||||
const elapsed = (performance.now() - started) / 1000;
|
||||
post("result", {
|
||||
text,
|
||||
segments,
|
||||
elapsed,
|
||||
device: currentDevice,
|
||||
windows: done,
|
||||
});
|
||||
}
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
// Dedicated worker: only accept commands from the page that created us.
|
||||
// Belt-and-braces same-origin guard — the demo page and this script are
|
||||
// always served from the same origin, so anything else is not ours.
|
||||
if (event.origin !== self.location.origin) return;
|
||||
const { kind, modelId, audio } = event.data;
|
||||
// Defence-in-depth origin check. A dedicated worker can only ever be
|
||||
// messaged by the page that created it (the browser enforces this), and
|
||||
// Chromium 158+ posts such messages with an EMPTY event.origin — a
|
||||
// strict `event.origin !== self.location.origin` comparison therefore
|
||||
// swallowed every command and left the demo hanging at "processing"
|
||||
// forever. Reject only origins that are present AND foreign.
|
||||
if (event.origin && event.origin !== self.location.origin) return;
|
||||
const { kind, modelId, audio, seconds } = event.data;
|
||||
try {
|
||||
if (kind === "load") {
|
||||
await loadModel(modelId);
|
||||
await loadBest(modelId);
|
||||
} else if (kind === "transcribe") {
|
||||
await transcribe(audio, modelId);
|
||||
await transcribe(audio, modelId, seconds);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
+16
-5
@@ -122,11 +122,22 @@ current ML stack surfaced and are fixed:
|
||||
|
||||
- The GPU-scale run exists (2026-11-18, free Colab T4): `whisper-small` +
|
||||
LoRA on 500 clips / ≈45 minutes of speech, 3 epochs in ~7 minutes —
|
||||
fixture WER 80.5% → 79.3% (see the fine-tune row in
|
||||
`benchmarks/README.md`). Real, but small; the same notebook at
|
||||
`MAX_SAMPLES = 0` (the full 10-hour manifest, ~1.5–2 h on a T4) is the
|
||||
next run, ideally paired with a larger speaker-disjoint hold-out than
|
||||
the default 2% eval split.
|
||||
under the v1 harness that was fixture WER 80.5% → 79.3%; re-measured
|
||||
under the v2 harness (orthography prompt + polish, see
|
||||
`benchmarks/README.md`) it lands at 75.0%. Real, but small; the same
|
||||
notebook at `MAX_SAMPLES = 0` (the full 10-hour manifest, ~1.5–2 h on a
|
||||
T4) is the next run, ideally paired with a larger speaker-disjoint
|
||||
hold-out than the default 2% eval split.
|
||||
- **Next-level run (recommended): LoRA on `whisper-medium`.** The measured
|
||||
untuned gap (small 75.0% vs medium 56.2% WER under v2) shows the base
|
||||
model is the bottleneck, not the adapter size. The same notebook with
|
||||
`MODEL_NAME = "openai/whisper-medium"` fits a free T4 (~1.5 GB LoRA
|
||||
state in int8 bf16); even 2–3 hours of Persian speech there should
|
||||
undercut every `small`-class number by a wide margin.
|
||||
- To put the fine-tuned engine **inside the browser demo**, run
|
||||
[export_web_onnx.py](export_web_onnx.py) (merge → ONNX → int8 → Hub) on
|
||||
Colab and add the resulting repo id to `space/index.html`. No new demo
|
||||
code is needed — the worker loads any Xenova-style whisper repo.
|
||||
- The default eval split (2%) is small; a proper report should freeze a
|
||||
larger, speaker-disjoint hold-out.
|
||||
- Data augmentation (noise, speed perturbation) is a known next step for
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export a fine-tuned Sokhan whisper checkpoint to a transformers.js web model.
|
||||
|
||||
Bridges the training world (PEFT LoRA adapter, PyTorch) and the browser
|
||||
demo (transformers.js ONNX). Run this on a machine with the model files —
|
||||
a free Colab T4 is enough — then wire the resulting HF repo id into
|
||||
space/index.html as a new <option> (Xenova-format ONNX is loaded by the
|
||||
same worker code path).
|
||||
|
||||
What it does:
|
||||
|
||||
1. loads the base whisper checkpoint and the Sokhan LoRA adapter,
|
||||
2. merges the adapter (`merge_and_unload`) and saves a plain transformers
|
||||
model + tokenizer + feature extractor,
|
||||
3. exports the merged model to ONNX the way transformers.js expects
|
||||
(encoder + decoder-merged, no monolith),
|
||||
4. quantizes to int8/q4 files for the browser dtypes,
|
||||
5. uploads the finished model repo to the Hugging Face Hub.
|
||||
|
||||
Usage (Colab / any machine with ~4 GB RAM):
|
||||
|
||||
pip install transformers peft torch optimum onnxruntime "av<14" \
|
||||
"huggingface_hub>=0.26" onnx
|
||||
python training/export_web_onnx.py \
|
||||
--base openai/whisper-small \
|
||||
--adapter Abol0pati/whisper-small-fa-sokhan \
|
||||
--repo Abol0pati/whisper-small-fa-sokhan-web \
|
||||
--push
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def merge_lora(base: str, adapter: str, out_dir: Path) -> None:
|
||||
from peft import PeftModel
|
||||
from transformers import AutoFeatureExtractor, AutoModelForSpeechSeq2Seq, AutoTokenizer
|
||||
|
||||
print(f"[1/4] loading base {base} and adapter {adapter}")
|
||||
model = AutoModelForSpeechSeq2Seq.from_pretrained(base)
|
||||
model = PeftModel.from_pretrained(model, adapter)
|
||||
merged = model.merge_and_unload()
|
||||
print("[2/4] saving merged transformers checkpoint")
|
||||
merged.save_pretrained(out_dir)
|
||||
AutoTokenizer.from_pretrained(base).save_pretrained(out_dir)
|
||||
AutoFeatureExtractor.from_pretrained(base).save_pretrained(out_dir)
|
||||
# generation config must carry forced decoder ids the demo relies on
|
||||
if hasattr(merged, "generation_config"):
|
||||
merged.generation_config.save_pretrained(out_dir)
|
||||
|
||||
|
||||
def export_onnx(model_dir: Path, onnx_dir: Path) -> None:
|
||||
print("[3/4] exporting ONNX (encoder + decoder-merged)")
|
||||
subprocess.run(
|
||||
[
|
||||
"optimum-cli", "export", "onnx",
|
||||
"--model", str(model_dir),
|
||||
"--task", "automatic-speech-recognition",
|
||||
"--monolith", "false",
|
||||
"--device", "cpu",
|
||||
str(onnx_dir),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
# int8 quantization for the wasm/q8 dtype path
|
||||
from onnxruntime.quantization import QuantType, quantize_dynamic
|
||||
|
||||
for onnx_file in list(onnx_dir.rglob("*.onnx")):
|
||||
if "_quantized" in onnx_file.stem or "_q4" in onnx_file.stem:
|
||||
continue
|
||||
quantize_dynamic(
|
||||
str(onnx_file),
|
||||
str(onnx_file.with_name(onnx_file.stem + "_quantized.onnx")),
|
||||
weight_type=QuantType.QInt8,
|
||||
)
|
||||
# tokenizer/processing configs ride along for transformers.js
|
||||
for name in (
|
||||
"config.json", "generation_config.json", "preprocessor_config.json",
|
||||
"tokenizer_config.json", "tokenizer.json", "special_tokens_map.json",
|
||||
):
|
||||
src = model_dir / name
|
||||
if src.exists():
|
||||
shutil.copy(src, onnx_dir / name)
|
||||
(onnx_dir / "onnx").mkdir(exist_ok=True)
|
||||
for onnx_file in list(onnx_dir.glob("*.onnx")):
|
||||
shutil.move(str(onnx_file), onnx_dir / "onnx" / onnx_file.name)
|
||||
|
||||
|
||||
def push(repo: str, onnx_dir: Path) -> None:
|
||||
from huggingface_hub import HfApi
|
||||
|
||||
print(f"[4/4] uploading to {repo}")
|
||||
api = HfApi(token=None) # token comes from HF_TOKEN env / cached login
|
||||
api.create_repo(repo, repo_type="model", exist_ok=True)
|
||||
api.upload_folder(folder_path=str(onnx_dir), repo_id=repo, repo_type="model")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--base", default="openai/whisper-small")
|
||||
ap.add_argument("--adapter", default="Abol0pati/whisper-small-fa-sokhan")
|
||||
ap.add_argument("--repo", default="Abol0pati/whisper-small-fa-sokhan-web")
|
||||
ap.add_argument("--push", action="store_true", help="upload the finished repo to the Hub")
|
||||
args = ap.parse_args()
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="sokhan-web-export-") as tmp:
|
||||
root = Path(tmp)
|
||||
merged_dir = root / "merged"
|
||||
onnx_dir = root / "onnx"
|
||||
merge_lora(args.base, args.adapter, merged_dir)
|
||||
export_onnx(merged_dir, onnx_dir)
|
||||
if args.push:
|
||||
push(args.repo, onnx_dir)
|
||||
else:
|
||||
keep = Path("sokhan-web-model")
|
||||
if keep.exists():
|
||||
shutil.rmtree(keep)
|
||||
shutil.copytree(onnx_dir, keep)
|
||||
print(f"kept local copy at ./{keep}")
|
||||
print("done — add the repo id as a new <option> in space/index.html")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+14
-8
@@ -55,20 +55,26 @@ human-verified references, beam_size=5, the same Persian normalization
|
||||
applied to reference and hypothesis. Session 2026-11-18,
|
||||
faster-whisper 1.2.1 / CTranslate2 4.9.0, CPU int8.
|
||||
|
||||
| model | WER | CER |
|
||||
| model | WER (v1 harness) | WER (v2 harness: orthography prompt + polish) |
|
||||
| --- | --- | --- |
|
||||
| openai whisper-small (baseline) | 80.5% | 26.7% |
|
||||
| **whisper-small-fa-sokhan** | **79.3%** | **24.9%** |
|
||||
| openai whisper-small (baseline) | 80.5% | 75.0% |
|
||||
| **whisper-small-fa-sokhan** | **79.3%** | **75.0%** |
|
||||
| openai whisper-medium (untuned, for scale) | — | 56.2% |
|
||||
|
||||
In-training held-out eval (10 clips): WER 85.1% → 81.6%; training loss
|
||||
3.63 → 1.75.
|
||||
3.63 → 1.75. With a Persian orthography initial prompt alone (no polish),
|
||||
this checkpoint measures 72.0% vs 76.8% without — the prompt is worth
|
||||
−4.8 WER points on this model, more than the LoRA itself contributed.
|
||||
|
||||
**Honest caveats.** A 12-clip fixture puts the -1.2 WER margin near the
|
||||
**Honest caveats.** A 12-clip fixture puts the small margins near the
|
||||
noise floor; the direction matches the in-training eval but the ceiling
|
||||
is unknown until the same notebook runs over the full ~10-hour manifest
|
||||
(`MAX_SAMPLES=0`, ~2 h on a free T4). Common Voice fa is colloquial and
|
||||
noisy — these WER numbers are much higher than typical read-speech
|
||||
benchmarks. Do not cite this model as production-ready Persian ASR yet.
|
||||
(`MAX_SAMPLES=0`, ~2 h on a free T4) — and the measured untuned
|
||||
small-vs-medium gap (75.0% vs 56.2%) says the next fine-tune should
|
||||
target `whisper-medium`, not more data on `small`. Common Voice fa is
|
||||
colloquial and noisy — these WER numbers are much higher than typical
|
||||
read-speech benchmarks. Do not cite this model as production-ready
|
||||
Persian ASR yet.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
+7
-3
@@ -5,10 +5,14 @@ COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
# NEXT_PUBLIC_ variables are inlined into the client bundle at build time,
|
||||
# so the API base URL is provided as a build argument.
|
||||
ARG NEXT_PUBLIC_API_BASE=http://localhost:8000
|
||||
# Both are baked into the build. The browser calls the API through this
|
||||
# app's own /api path, proxied to API_PROXY_TARGET (the compose service by
|
||||
# default). NEXT_PUBLIC_API_BASE stays empty unless the API is served from
|
||||
# its own host.
|
||||
ARG NEXT_PUBLIC_API_BASE=
|
||||
ARG API_PROXY_TARGET=http://api:8000
|
||||
ENV NEXT_PUBLIC_API_BASE=$NEXT_PUBLIC_API_BASE
|
||||
ENV API_PROXY_TARGET=$API_PROXY_TARGET
|
||||
|
||||
RUN npm run build
|
||||
|
||||
|
||||
+12
-2
@@ -15,13 +15,20 @@
|
||||
"new": "New transcription",
|
||||
"archive": "Archive",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی"
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "Switch to dark theme",
|
||||
"themeToLight": "Switch to light theme",
|
||||
"signIn": "Sign in",
|
||||
"signOut": "Sign out",
|
||||
"accountMenu": "Account",
|
||||
"accountMenuFor": "Account menu for {email}",
|
||||
"signedInLabel": "Signed in as",
|
||||
"signedIn": "Signed in"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "From speech to text, in moments",
|
||||
"subheadline": "Upload an audio file or record straight away — Sokhan turns it into an accurate Persian transcript and hands you a short summary alongside.",
|
||||
"startCta": "Get started",
|
||||
"loginCta": "Sign in",
|
||||
"featuresTitle": "Where Sokhan helps",
|
||||
"featuresSubtitle": "From lecture notes to a friend's voice message — every recording deserves its text.",
|
||||
"featureLectureTitle": "Lectures & meetings",
|
||||
@@ -53,6 +60,8 @@
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"passwordLabel": "Password",
|
||||
"passwordPlaceholder": "••••••••",
|
||||
"showPassword": "Show password",
|
||||
"hidePassword": "Hide password",
|
||||
"codeLabel": "Connect code",
|
||||
"codePlaceholder": "Enter your connect code",
|
||||
"codeHint": "Have a connect code? No email or password needed.",
|
||||
@@ -100,6 +109,7 @@
|
||||
"statusFailed": "Failed",
|
||||
"progressLabel": "Processing progress",
|
||||
"percent": "{value}%",
|
||||
"preparing": "Getting ready…",
|
||||
"emptyTitle": "No transcriptions yet",
|
||||
"emptyDesc": "Upload your first file and it will show up here.",
|
||||
"emptyCta": "New transcription",
|
||||
|
||||
+12
-2
@@ -15,13 +15,20 @@
|
||||
"new": "رونویسی تازه",
|
||||
"archive": "آرشیو",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی"
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "تم تیره",
|
||||
"themeToLight": "تم روشن",
|
||||
"signIn": "ورود",
|
||||
"signOut": "خروج",
|
||||
"accountMenu": "حساب کاربری",
|
||||
"accountMenuFor": "منوی حساب {email}",
|
||||
"signedInLabel": "وارد شده با",
|
||||
"signedIn": "وارد شدهای"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "از گفتار به متن، در چند لحظه",
|
||||
"subheadline": "فایل صوتی را بارگذاری کن یا مستقیم ضبط کن؛ سخن آن را با دقت بالا به متن فارسی تبدیل میکند و خلاصهای کوتاه هم کنارش تحویل میدهد.",
|
||||
"startCta": "شروع کنید",
|
||||
"loginCta": "ورود",
|
||||
"featuresTitle": "سخن کجا به کارت میآید؟",
|
||||
"featuresSubtitle": "از جزوهٔ درس تا پیام صوتی دوستان؛ هر صدایی متن خودش را دارد.",
|
||||
"featureLectureTitle": "درس و جلسه",
|
||||
@@ -53,6 +60,8 @@
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"passwordLabel": "رمز عبور",
|
||||
"passwordPlaceholder": "••••••••",
|
||||
"showPassword": "نمایش رمز عبور",
|
||||
"hidePassword": "پنهان کردن رمز عبور",
|
||||
"codeLabel": "کد اتصال",
|
||||
"codePlaceholder": "کد اتصال را وارد کن",
|
||||
"codeHint": "اگر کد اتصال داری، لازم نیست ایمیل و رمز عبور وارد کنی.",
|
||||
@@ -100,6 +109,7 @@
|
||||
"statusFailed": "ناموفق",
|
||||
"progressLabel": "پیشرفت پردازش",
|
||||
"percent": "{value}٪",
|
||||
"preparing": "در حال آمادهسازی…",
|
||||
"emptyTitle": "هنوز رونویسیای نداری",
|
||||
"emptyDesc": "اولین فایل را بارگذاری کن تا همینجا فهرست شود.",
|
||||
"emptyCta": "رونویسی تازه",
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import createNextIntlPlugin from "next-intl/plugin";
|
||||
|
||||
// The dashboard talks to the API through its own origin (/api/*), so the
|
||||
// httpOnly session cookie is always first-party: it works on localhost,
|
||||
// 127.0.0.1, a LAN address or a real domain alike, without CORS. The
|
||||
// target is baked into the build (standalone output); compose passes the
|
||||
// in-network address, `next dev` defaults to a local API.
|
||||
const apiProxyTarget = (process.env.API_PROXY_TARGET || "http://localhost:8000").replace(/\/$/, "");
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: "standalone",
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${apiProxyTarget}/:path*` }];
|
||||
},
|
||||
experimental: {
|
||||
// Uploads and transcript downloads can outlast the 30 s proxy default.
|
||||
proxyTimeout: 10 * 60 * 1000,
|
||||
},
|
||||
};
|
||||
|
||||
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
|
||||
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
deleteJob,
|
||||
downloadTranscript,
|
||||
getJob,
|
||||
getToken,
|
||||
type JobDetail,
|
||||
type TranscriptFormat,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
@@ -67,6 +67,7 @@ export default function JobDetailPage() {
|
||||
const { id: jobId } = useParams<{ id: string }>();
|
||||
const locale = useLocale();
|
||||
const t = useTranslations("jobDetail");
|
||||
const tj = useTranslations("jobs");
|
||||
const tc = useTranslations("common");
|
||||
const te = useTranslations("errors");
|
||||
const router = useRouter();
|
||||
@@ -80,12 +81,9 @@ export default function JobDetailPage() {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
router.replace("/login");
|
||||
return;
|
||||
}
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
@@ -275,12 +273,15 @@ export default function JobDetailPage() {
|
||||
<h2 className="font-bold text-stone-900">{t("processingTitle")}</h2>
|
||||
<p className="mt-1.5 text-sm leading-7 text-stone-600">{t("processingDesc")}</p>
|
||||
<div className="mt-4">
|
||||
<ProgressBar value={job.progress} label={t("metaDuration")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500">
|
||||
{new Intl.NumberFormat(locale).format(
|
||||
Math.min(100, Math.max(0, Math.round(job.progress))),
|
||||
)}
|
||||
٪
|
||||
<ProgressBar value={job.progress} label={tj("progressLabel")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500" aria-live="polite">
|
||||
{job.progress > 0
|
||||
? tj("percent", {
|
||||
value: new Intl.NumberFormat(locale).format(
|
||||
Math.min(100, Math.round(job.progress)),
|
||||
),
|
||||
})
|
||||
: tj("preparing")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Clock, Search } from "lucide-react";
|
||||
import { Link, useRouter } from "@/i18n/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import {
|
||||
ApiError,
|
||||
getToken,
|
||||
listJobs,
|
||||
searchJobs,
|
||||
type JobListItem,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
function formatDate(iso: string, locale: string): string {
|
||||
@@ -24,21 +24,22 @@ function formatDate(iso: string, locale: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
const REFRESH_INTERVAL_MS = 3000;
|
||||
|
||||
export default function JobsPage() {
|
||||
const t = useTranslations("jobs");
|
||||
const tc = useTranslations("common");
|
||||
const te = useTranslations("errors");
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const nf = new Intl.NumberFormat(locale);
|
||||
|
||||
const [query, setQuery] = useState("");
|
||||
const [items, setItems] = useState<JobListItem[] | null>(null);
|
||||
const [listError, setListError] = useState<string | null>(null);
|
||||
// Bumped to re-fetch the list while any job is still queued or processing.
|
||||
const [refreshTick, setRefreshTick] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
const seqRef = useRef(0);
|
||||
useEffect(() => {
|
||||
@@ -72,7 +73,15 @@ export default function JobsPage() {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [query]);
|
||||
}, [query, refreshTick]);
|
||||
|
||||
const hasRunningJobs =
|
||||
items?.some((job) => job.status === "queued" || job.status === "processing") ?? false;
|
||||
useEffect(() => {
|
||||
if (!hasRunningJobs) return;
|
||||
const timer = setTimeout(() => setRefreshTick((tick) => tick + 1), REFRESH_INTERVAL_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [hasRunningJobs, items]);
|
||||
|
||||
const hasQuery = query.trim().length > 0;
|
||||
|
||||
@@ -169,13 +178,15 @@ export default function JobsPage() {
|
||||
<StatusBadge status={job.status} />
|
||||
</div>
|
||||
</div>
|
||||
{job.status === "processing" ? (
|
||||
{job.status === "queued" || job.status === "processing" ? (
|
||||
<div className="mt-4">
|
||||
<ProgressBar value={job.progress} label={t("progressLabel")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500">
|
||||
{t("percent", {
|
||||
value: nf.format(Math.min(100, Math.max(0, job.progress))),
|
||||
})}
|
||||
{job.progress > 0
|
||||
? t("percent", {
|
||||
value: nf.format(Math.min(100, Math.round(job.progress))),
|
||||
})
|
||||
: t("preparing")}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import localFont from "next/font/local";
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { SiteHeader } from "@/components/site-header";
|
||||
import { themeInitScript } from "@/lib/theme";
|
||||
import "../globals.css";
|
||||
|
||||
// Fonts are self-hosted (see src/fonts/README.txt): builds must never depend
|
||||
@@ -47,7 +48,10 @@ export async function generateMetadata({
|
||||
}
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: "#0f766e",
|
||||
themeColor: [
|
||||
{ media: "(prefers-color-scheme: light)", color: "#0f766e" },
|
||||
{ media: "(prefers-color-scheme: dark)", color: "#134e4a" },
|
||||
],
|
||||
};
|
||||
|
||||
export default async function LocaleLayout({
|
||||
@@ -64,7 +68,10 @@ export default async function LocaleLayout({
|
||||
const t = await getTranslations("common");
|
||||
|
||||
return (
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"}>
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"} suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
|
||||
</head>
|
||||
<body
|
||||
className={`${vazirmatn.variable} ${inter.variable} flex min-h-screen flex-col bg-stone-50 text-stone-900 antialiased`}
|
||||
>
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api";
|
||||
import { ApiError, login, register, startSession, tokenLogin } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
type Mode = "login" | "register" | "code";
|
||||
|
||||
@@ -13,10 +15,17 @@ export default function LoginPage() {
|
||||
const t = useTranslations("login");
|
||||
const te = useTranslations("errors");
|
||||
const router = useRouter();
|
||||
const { ready, signedIn } = useSession();
|
||||
|
||||
// Already signed in: the login form has nothing to offer.
|
||||
useEffect(() => {
|
||||
if (ready && signedIn) router.replace("/new");
|
||||
}, [ready, signedIn, router]);
|
||||
|
||||
const [mode, setMode] = useState<Mode>("login");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [code, setCode] = useState("");
|
||||
const [emailError, setEmailError] = useState<string | null>(null);
|
||||
const [passwordError, setPasswordError] = useState<string | null>(null);
|
||||
@@ -27,6 +36,7 @@ export default function LoginPage() {
|
||||
function switchMode(next: Mode) {
|
||||
if (next === mode) return;
|
||||
setMode(next);
|
||||
setShowPassword(false);
|
||||
setEmailError(null);
|
||||
setPasswordError(null);
|
||||
setCodeError(null);
|
||||
@@ -71,8 +81,7 @@ export default function LoginPage() {
|
||||
: mode === "register"
|
||||
? await register(email.trim(), password)
|
||||
: await tokenLogin(code.trim());
|
||||
setToken(result.api_token);
|
||||
router.push("/new");
|
||||
startSession(result);
|
||||
} catch (error) {
|
||||
setPending(false);
|
||||
if (error instanceof ApiError) {
|
||||
@@ -176,21 +185,39 @@ export default function LoginPage() {
|
||||
>
|
||||
{t("passwordLabel")}
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type="password"
|
||||
dir="ltr"
|
||||
autoComplete={mode === "register" ? "new-password" : "current-password"}
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordError) setPasswordError(null);
|
||||
}}
|
||||
placeholder={t("passwordPlaceholder")}
|
||||
aria-invalid={passwordError ? true : undefined}
|
||||
className={inputClasses}
|
||||
/>
|
||||
{/* The field is always LTR, so the toggle sits at its physical right. */}
|
||||
<div className="relative" dir="ltr">
|
||||
<input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
dir="ltr"
|
||||
autoComplete={mode === "register" ? "new-password" : "current-password"}
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordError) setPasswordError(null);
|
||||
}}
|
||||
placeholder={t("passwordPlaceholder")}
|
||||
aria-invalid={passwordError ? true : undefined}
|
||||
className={`${inputClasses} pr-11`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((shown) => !shown)}
|
||||
aria-label={showPassword ? t("hidePassword") : t("showPassword")}
|
||||
aria-pressed={showPassword}
|
||||
aria-controls="login-password"
|
||||
title={showPassword ? t("hidePassword") : t("showPassword")}
|
||||
className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-e-lg text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-5 w-5" aria-hidden="true" />
|
||||
) : (
|
||||
<Eye className="h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{passwordError ? (
|
||||
<p className="mt-1.5 text-sm text-red-700">{passwordError}</p>
|
||||
) : mode === "register" ? (
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useEffect, useRef, useState, type DragEvent, type FormEvent } from "rea
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { ChevronDown, FileText, Mic, Square, Upload } from "lucide-react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, getQuota, getToken, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { ApiError, getQuota, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
@@ -43,9 +44,7 @@ export default function NewJobPage() {
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
@@ -69,12 +69,6 @@ export default async function LandingPage({
|
||||
{t("startCta")}
|
||||
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
</Link>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
{t("loginCta")}
|
||||
</Link>
|
||||
</div>
|
||||
<svg
|
||||
viewBox="0 0 200 48"
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--font-vazir: var(--font-vazirmatn, Vazirmatn), var(--font-inter, Inter), ui-sans-serif,
|
||||
system-ui, sans-serif;
|
||||
--animate-progress-indeterminate: progress-indeterminate 1.4s ease-in-out infinite;
|
||||
|
||||
@keyframes progress-indeterminate {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -21,3 +33,75 @@ html[lang="en"] body {
|
||||
background-color: #99f6e4;
|
||||
color: #134e4a;
|
||||
}
|
||||
|
||||
html.dark {
|
||||
color-scheme: dark;
|
||||
|
||||
--color-stone-50: oklch(14.7% 0.004 49.25);
|
||||
--color-stone-100: oklch(26.8% 0.007 34.298);
|
||||
--color-stone-200: oklch(30% 0.007 34.298);
|
||||
--color-stone-300: oklch(40% 0.01 67.558);
|
||||
--color-stone-400: oklch(55.3% 0.013 58.071);
|
||||
--color-stone-500: oklch(70.9% 0.01 56.259);
|
||||
--color-stone-600: oklch(80% 0.005 56.366);
|
||||
--color-stone-700: oklch(86.9% 0.005 56.366);
|
||||
--color-stone-800: oklch(92.3% 0.003 48.717);
|
||||
--color-stone-900: oklch(97% 0.001 106.424);
|
||||
--color-stone-950: oklch(98.5% 0.001 106.423);
|
||||
|
||||
--color-teal-50: oklch(27.7% 0.046 192.524);
|
||||
--color-teal-100: oklch(32% 0.055 190);
|
||||
--color-teal-200: oklch(38.6% 0.063 188.416);
|
||||
--color-teal-800: oklch(85.5% 0.138 181.071);
|
||||
--color-teal-900: oklch(91% 0.096 180.426);
|
||||
--color-teal-950: oklch(95.3% 0.051 180.801);
|
||||
|
||||
--color-red-50: oklch(25.8% 0.092 26.042);
|
||||
--color-red-100: oklch(30% 0.11 26);
|
||||
--color-red-200: oklch(39.6% 0.141 25.723);
|
||||
--color-red-700: oklch(80.8% 0.114 19.571);
|
||||
--color-red-800: oklch(88.5% 0.062 18.334);
|
||||
--color-red-900: oklch(93.6% 0.032 17.717);
|
||||
|
||||
--color-amber-100: oklch(27.9% 0.077 45.635);
|
||||
--color-amber-800: oklch(92.4% 0.12 95.746);
|
||||
|
||||
--color-emerald-100: oklch(26.2% 0.051 172.552);
|
||||
--color-emerald-800: oklch(90.5% 0.093 164.15);
|
||||
|
||||
--sokhan-surface: oklch(19% 0.005 56);
|
||||
}
|
||||
|
||||
html.dark body {
|
||||
background-color: var(--color-stone-50);
|
||||
color: var(--color-stone-900);
|
||||
}
|
||||
|
||||
html.dark ::selection {
|
||||
background-color: #115e59;
|
||||
color: #f0fdfa;
|
||||
}
|
||||
|
||||
html.dark .bg-white {
|
||||
background-color: var(--sokhan-surface);
|
||||
}
|
||||
html.dark .bg-white\/90 {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 90%, transparent);
|
||||
}
|
||||
html.dark .supports-\[backdrop-filter\]\:bg-white\/75 {
|
||||
@supports (backdrop-filter: var(--tw)) {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 75%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
html.dark .text-teal-600,
|
||||
html.dark .text-teal-700 {
|
||||
color: oklch(77.7% 0.152 181.912);
|
||||
}
|
||||
html.dark .text-teal-700\/60 {
|
||||
color: color-mix(in oklab, oklch(77.7% 0.152 181.912) 60%, transparent);
|
||||
}
|
||||
|
||||
html.dark * {
|
||||
--tw-ring-offset-color: var(--sokhan-surface);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { ChevronDown, LogOut, UserRound } from "lucide-react";
|
||||
|
||||
/**
|
||||
* The signed-in account in the header: an avatar with the email's initial
|
||||
* that opens a small menu showing the full address and Sign out. The full
|
||||
* email no longer has to squeeze into the header row (where it was
|
||||
* truncated or hidden on narrow screens).
|
||||
*/
|
||||
export function AccountMenu({
|
||||
email,
|
||||
signingOut,
|
||||
onSignOut,
|
||||
}: {
|
||||
email: string | null;
|
||||
signingOut: boolean;
|
||||
onSignOut: () => void;
|
||||
}) {
|
||||
const t = useTranslations("nav");
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const signOutRef = useRef<HTMLButtonElement>(null);
|
||||
const menuId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
signOutRef.current?.focus();
|
||||
|
||||
function onPointerDown(event: PointerEvent) {
|
||||
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
}
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const initial = email ? email.charAt(0).toUpperCase() : null;
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="relative">
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-label={email ? t("accountMenuFor", { email }) : t("accountMenu")}
|
||||
className="flex items-center gap-1 rounded-full p-0.5 text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<span
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-teal-100 text-sm font-bold text-teal-800"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{initial ?? <UserRound className="h-5 w-5" />}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={`hidden h-4 w-4 transition-transform sm:block ${open ? "rotate-180" : ""}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
id={menuId}
|
||||
role="menu"
|
||||
aria-label={t("accountMenu")}
|
||||
className="absolute end-0 top-full z-50 mt-2 w-64 overflow-hidden rounded-xl border border-stone-200 bg-white shadow-lg"
|
||||
>
|
||||
<div className="border-b border-stone-100 px-4 py-3">
|
||||
<p className="text-xs text-stone-500">{email ? t("signedInLabel") : t("accountMenu")}</p>
|
||||
{email ? (
|
||||
<p
|
||||
dir="ltr"
|
||||
className="mt-0.5 break-all text-start text-sm font-medium text-stone-900"
|
||||
>
|
||||
{email}
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-0.5 text-sm font-medium text-stone-900">{t("signedIn")}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
ref={signOutRef}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onSignOut();
|
||||
}}
|
||||
disabled={signingOut}
|
||||
className="flex w-full items-center gap-2 px-4 py-2.5 text-sm font-medium text-stone-700 transition-colors hover:bg-stone-50 hover:text-stone-900 focus-visible:bg-stone-50 focus-visible:outline-none disabled:opacity-60"
|
||||
>
|
||||
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
{t("signOut")}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -34,8 +34,14 @@ export function StatusBadge({ status }: { status: JobStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determinate bar once the worker reports progress. While nothing has been
|
||||
* reported yet (queued, model loading, first seconds of decoding) it shows
|
||||
* a moving bar instead of an empty track that looks stuck.
|
||||
*/
|
||||
export function ProgressBar({ value, label }: { value: number; label?: string }) {
|
||||
const clamped = Math.min(100, Math.max(0, value));
|
||||
const indeterminate = clamped <= 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -43,13 +49,18 @@ export function ProgressBar({ value, label }: { value: number; label?: string })
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={Math.round(clamped)}
|
||||
aria-valuenow={indeterminate ? undefined : Math.round(clamped)}
|
||||
aria-busy={indeterminate || undefined}
|
||||
aria-label={label}
|
||||
>
|
||||
<div
|
||||
className="h-full rounded-full bg-teal-700 transition-[width] duration-500 ease-out"
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
{indeterminate ? (
|
||||
<div className="h-full w-2/5 rounded-full bg-teal-700/70 animate-progress-indeterminate motion-reduce:w-full motion-reduce:animate-pulse" />
|
||||
) : (
|
||||
<div
|
||||
className="h-full rounded-full bg-teal-700 transition-[width] duration-500 ease-out"
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { AudioLines } from "lucide-react";
|
||||
import { AudioLines, LogIn } from "lucide-react";
|
||||
import { AccountMenu } from "@/components/account-menu";
|
||||
import { Link, usePathname, useRouter } from "@/i18n/navigation";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
import { logout } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
export function SiteHeader() {
|
||||
const t = useTranslations("nav");
|
||||
const locale = useLocale();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const { ready, signedIn, email } = useSession();
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
|
||||
async function handleSignOut() {
|
||||
setSigningOut(true);
|
||||
await logout();
|
||||
setSigningOut(false);
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
const otherLocale = locale === "fa" ? "en" : "fa";
|
||||
|
||||
@@ -60,6 +74,20 @@ export function SiteHeader() {
|
||||
>
|
||||
{otherLocale === "en" ? "EN" : "فا"}
|
||||
</button>
|
||||
<ThemeToggle />
|
||||
{ready && signedIn && (
|
||||
<AccountMenu email={email} signingOut={signingOut} onSignOut={handleSignOut} />
|
||||
)}
|
||||
{ready && !signedIn && pathname !== "/login" && (
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg bg-teal-700 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-teal-600 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<LogIn className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signIn")}</span>
|
||||
<span className="sr-only sm:hidden">{t("signIn")}</span>
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { THEME_STORAGE_KEY, type Theme } from "@/lib/theme";
|
||||
|
||||
function applyTheme(theme: Theme) {
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const t = useTranslations("nav");
|
||||
const [theme, setTheme] = useState<Theme | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(document.documentElement.classList.contains("dark") ? "dark" : "light");
|
||||
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = (event: MediaQueryListEvent) => {
|
||||
let saved: string | null = null;
|
||||
try {
|
||||
saved = window.localStorage.getItem(THEME_STORAGE_KEY);
|
||||
} catch {
|
||||
}
|
||||
if (saved === "light" || saved === "dark") return;
|
||||
const next: Theme = event.matches ? "dark" : "light";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
};
|
||||
media.addEventListener("change", onChange);
|
||||
return () => media.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
const isDark = theme === "dark";
|
||||
|
||||
function toggle() {
|
||||
const next: Theme = isDark ? "light" : "dark";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
try {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, next);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
const label = isDark ? t("themeToLight") : t("themeToDark");
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg border border-stone-300 text-stone-700 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700"
|
||||
>
|
||||
{isDark ? (
|
||||
<Sun className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Moon className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
+116
-31
@@ -1,10 +1,19 @@
|
||||
// Browser client for the Sokhan REST API. Authenticated requests carry the
|
||||
// stored API token as a Bearer header; a 401 clears the token and bounces
|
||||
// the user back to the login screen.
|
||||
// Browser client for the Sokhan REST API. The dashboard authenticates with
|
||||
// the httpOnly session cookie the API sets at sign-in: script never sees the
|
||||
// token, every request goes out with credentials, and writes carry the
|
||||
// session's CSRF token. A 401 marks the session signed out and bounces the
|
||||
// user back to the login screen.
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000";
|
||||
// Same-origin by default: next.config.mjs proxies /api/* to the backend, so
|
||||
// the session cookie is first-party wherever the dashboard is served from.
|
||||
// Set NEXT_PUBLIC_API_BASE only for an API on its own host.
|
||||
const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "/api").replace(/\/$/, "");
|
||||
|
||||
export const TOKEN_STORAGE_KEY = "sokhan_token";
|
||||
/** Fired on this tab whenever the session state changes. */
|
||||
export const SESSION_CHANGE_EVENT = "sokhan:session-change";
|
||||
// Earlier versions kept the token in localStorage; it is wiped on load.
|
||||
const LEGACY_STORAGE_KEYS = ["sokhan_token", "sokhan_email"];
|
||||
const SAFE_METHODS = new Set(["GET", "HEAD"]);
|
||||
|
||||
export type JobStatus = "queued" | "processing" | "completed" | "failed";
|
||||
export type TranscriptFormat = "txt" | "srt" | "vtt" | "json" | "docx";
|
||||
@@ -13,6 +22,14 @@ export interface AuthResponse {
|
||||
id: string;
|
||||
email: string;
|
||||
api_token: string;
|
||||
csrf_token: string | null;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
/** "unknown" until GET /auth/session has answered once. */
|
||||
status: "unknown" | "signedIn" | "signedOut";
|
||||
email: string | null;
|
||||
csrfToken: string | null;
|
||||
}
|
||||
|
||||
export interface QuotaInfo {
|
||||
@@ -92,19 +109,93 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
|
||||
const UNKNOWN_SESSION: SessionState = { status: "unknown", email: null, csrfToken: null };
|
||||
const SIGNED_OUT: SessionState = { status: "signedOut", email: null, csrfToken: null };
|
||||
|
||||
let session: SessionState = UNKNOWN_SESSION;
|
||||
let sessionRequest: Promise<void> | null = null;
|
||||
let otherTabs: BroadcastChannel | null = null;
|
||||
|
||||
function setSession(next: SessionState, broadcast = true): void {
|
||||
session = next;
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(new Event(SESSION_CHANGE_EVENT));
|
||||
if (broadcast) otherTabs?.postMessage("changed");
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
|
||||
/** The current session snapshot; a new object only when it changes. */
|
||||
export function getSessionState(): SessionState {
|
||||
return session;
|
||||
}
|
||||
|
||||
export function clearToken(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
/** The server snapshot: nothing is known before hydration. */
|
||||
export function getUnknownSessionState(): SessionState {
|
||||
return UNKNOWN_SESSION;
|
||||
}
|
||||
|
||||
/** Ask the API who is signed in (deduplicated while a request is in flight). */
|
||||
export function loadSession(): Promise<void> {
|
||||
if (typeof window === "undefined") return Promise.resolve();
|
||||
if (!otherTabs && "BroadcastChannel" in window) {
|
||||
otherTabs = new BroadcastChannel("sokhan-session");
|
||||
otherTabs.onmessage = () => {
|
||||
sessionRequest = null;
|
||||
void loadSession();
|
||||
};
|
||||
for (const key of LEGACY_STORAGE_KEYS) {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Storage disabled: nothing to clean up.
|
||||
}
|
||||
}
|
||||
}
|
||||
sessionRequest ??= (async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/auth/session`, { credentials: "include" });
|
||||
if (!response.ok) {
|
||||
setSession(SIGNED_OUT, false);
|
||||
return;
|
||||
}
|
||||
const body = (await response.json()) as { email: string; csrf_token: string };
|
||||
setSession({ status: "signedIn", email: body.email, csrfToken: body.csrf_token }, false);
|
||||
} catch {
|
||||
setSession(SIGNED_OUT, false);
|
||||
} finally {
|
||||
sessionRequest = null;
|
||||
}
|
||||
})();
|
||||
return sessionRequest;
|
||||
}
|
||||
|
||||
/** Record a successful sign-in; the API has already set the cookie. */
|
||||
export function startSession(auth: AuthResponse): void {
|
||||
setSession({ status: "signedIn", email: auth.email, csrfToken: auth.csrf_token });
|
||||
}
|
||||
|
||||
function csrfHeaders(method: string, headers: Headers): Headers {
|
||||
if (!SAFE_METHODS.has(method) && session.csrfToken) {
|
||||
headers.set("X-CSRF-Token", session.csrfToken);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the session on the server (which also clears the cookie), then
|
||||
* mark it signed out locally. The local sign-out happens even when the API
|
||||
* is unreachable, so signing out always works from the user's point of view.
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: csrfHeaders("POST", new Headers()),
|
||||
});
|
||||
} catch {
|
||||
// Offline or API down: the local sign-out below still happens.
|
||||
}
|
||||
setSession(SIGNED_OUT);
|
||||
}
|
||||
|
||||
function redirectToLogin(): void {
|
||||
@@ -116,7 +207,7 @@ function redirectToLogin(): void {
|
||||
|
||||
function handleAuthFailure(response: Response): void {
|
||||
if (response.status === 401) {
|
||||
clearToken();
|
||||
setSession(SIGNED_OUT);
|
||||
redirectToLogin();
|
||||
}
|
||||
}
|
||||
@@ -131,15 +222,16 @@ interface RequestOptions {
|
||||
async function requestJson<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = "GET", body, headers: extraHeaders, authenticated = false } = options;
|
||||
|
||||
const headers = new Headers(extraHeaders);
|
||||
if (authenticated) {
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
const headers = csrfHeaders(method, new Headers(extraHeaders));
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}${path}`, { method, headers, body });
|
||||
response = await fetch(`${API_BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
}
|
||||
@@ -229,15 +321,12 @@ export async function searchJobs(query: string): Promise<JobListResponse> {
|
||||
}
|
||||
|
||||
export async function deleteJob(id: string): Promise<void> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}/jobs/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers,
|
||||
headers: csrfHeaders("DELETE", new Headers()),
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
@@ -248,15 +337,11 @@ export async function deleteJob(id: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function downloadTranscript(id: string, format: TranscriptFormat): Promise<Blob> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE}/jobs/${encodeURIComponent(id)}/transcript?format=${format}`,
|
||||
{ headers },
|
||||
{ credentials: "include" },
|
||||
);
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Reactive view of the dashboard session for client components. The token
|
||||
// itself lives in an httpOnly cookie the page cannot read, so the state
|
||||
// comes from GET /auth/session (see api.ts) and is kept in sync across this
|
||||
// tab (SESSION_CHANGE_EVENT) and other tabs (a BroadcastChannel).
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import {
|
||||
SESSION_CHANGE_EVENT,
|
||||
getSessionState,
|
||||
getUnknownSessionState,
|
||||
loadSession,
|
||||
} from "@/lib/api";
|
||||
|
||||
// Accounts created by the Telegram bot get a synthetic address that means
|
||||
// nothing to the user, so it is not shown.
|
||||
const SYNTHETIC_EMAIL_SUFFIX = "@telegram.sokhan.local";
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
window.addEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
if (getSessionState().status === "unknown") void loadSession();
|
||||
return () => window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
/** False during SSR and until the API has said who is signed in. */
|
||||
ready: boolean;
|
||||
signedIn: boolean;
|
||||
/** The account email, or null when unknown or a Telegram placeholder. */
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
export function useSession(): Session {
|
||||
const state = useSyncExternalStore(subscribe, getSessionState, getUnknownSessionState);
|
||||
const email =
|
||||
state.email && !state.email.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? state.email : null;
|
||||
return { ready: state.status !== "unknown", signedIn: state.status === "signedIn", email };
|
||||
}
|
||||
|
||||
/** Send a signed-out visitor to the login page once the session is known. */
|
||||
export function useRequireSignIn(): void {
|
||||
const { ready, signedIn } = useSession();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (ready && !signedIn) router.replace("/login");
|
||||
}, [ready, signedIn, router]);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export const THEME_STORAGE_KEY = "sokhan-theme";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
export const themeInitScript = `(function(){try{var t=localStorage.getItem("${THEME_STORAGE_KEY}");if(t!=="light"&&t!=="dark"){t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}document.documentElement.classList.toggle("dark",t==="dark")}catch(e){}})();`;
|
||||
@@ -4,5 +4,6 @@ import { routing } from "./i18n/routing";
|
||||
export default createMiddleware(routing);
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"],
|
||||
// /api is the proxied backend: it must not get a locale prefix.
|
||||
matcher: ["/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
|
||||
};
|
||||
Reference in new issue
Block a user