Author SHA1 Message Date
ahp 1219089a3c docs(contributing): add a Persian translation of the contribution guide
- CONTRIBUTING.fa.md follows the original section by section, in the
  same order, with the terminology README.fa.md already uses (رونویسی،
  ورکر، سلف‌هاست، داشبورد، فاین‌تیون)
- commands, code blocks, paths and commit prefixes stay in English so
  they remain copy-pasteable; no command or number was changed
- both files get a language switcher line, like the READMEs

Closes #31
2026-11-26 18:02:10 +03:30
12 changed files with 91 additions and 234 deletions

No files matched your search

+3 -13
View File
@@ -52,6 +52,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
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.
- `CONTRIBUTING.fa.md`: a Persian translation of the contribution guide,
with a language switcher in both files like the READMEs (#31).
### Changed
- **Demo hang fix**: audio was decoded inside an `AudioContext` forced to
@@ -74,19 +77,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
pyproject.toml files, web/package.json, the landing site copy, the demo
Space metadata and the fine-tuned model card.
### Fixed
- 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.
## [1.4.1] - 2026-11-26
### Security
+64
View File
@@ -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 را ببینید.
+2
View File
@@ -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
+2 -36
View File
@@ -10,7 +10,6 @@ from __future__ import annotations
import logging
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Protocol
@@ -37,30 +36,15 @@ 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,
@@ -89,11 +73,7 @@ class FasterWhisperTranscriber:
return self._model
def transcribe(
self,
samples: np.ndarray,
sample_rate: int,
language: str,
on_progress: ProgressCallback | None = None,
self, samples: np.ndarray, sample_rate: int, language: str
) -> list[Segment]:
model = self._load()
settings = get_settings()
@@ -106,13 +86,8 @@ 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
@@ -132,14 +107,8 @@ 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,
on_progress: ProgressCallback | None = None,
self, samples: np.ndarray, sample_rate: int, language: str
) -> list[Segment]:
duration = len(samples) / sample_rate
segments: list[Segment] = []
@@ -163,9 +132,6 @@ 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
+4 -37
View File
@@ -19,7 +19,6 @@ never hold a transaction open.
"""
import logging
import time
from collections.abc import Iterator
from dataclasses import replace
from typing import Any
@@ -42,7 +41,7 @@ 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, reports_progress
from sokhan.core.transcribe import Transcriber, get_transcriber
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
@@ -51,11 +50,6 @@ 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,
@@ -129,38 +123,11 @@ 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)
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)
chunk_segments.append(
engine.transcribe(chunk.samples, SAMPLE_RATE, job.language)
)
if chunk_total is not None:
job.progress = round(position / chunk_total * 100.0, 1)
elif estimated_duration:
-91
View File
@@ -1,91 +0,0 @@
"""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
-1
View File
@@ -100,7 +100,6 @@
"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",
-1
View File
@@ -100,7 +100,6 @@
"statusFailed": "ناموفق",
"progressLabel": "پیشرفت پردازش",
"percent": "{value}٪",
"preparing": "در حال آماده‌سازی…",
"emptyTitle": "هنوز رونویسی‌ای نداری",
"emptyDesc": "اولین فایل را بارگذاری کن تا همین‌جا فهرست شود.",
"emptyCta": "رونویسی تازه",
+6 -10
View File
@@ -67,7 +67,6 @@ 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();
@@ -276,15 +275,12 @@ 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={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")}
<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))),
)}
٪
</p>
</div>
</div>
+5 -19
View File
@@ -24,8 +24,6 @@ function formatDate(iso: string, locale: string): string {
}
}
const REFRESH_INTERVAL_MS = 3000;
export default function JobsPage() {
const t = useTranslations("jobs");
const tc = useTranslations("common");
@@ -37,8 +35,6 @@ export default function JobsPage() {
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");
@@ -76,15 +72,7 @@ export default function JobsPage() {
cancelled = true;
clearTimeout(timer);
};
}, [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]);
}, [query]);
const hasQuery = query.trim().length > 0;
@@ -181,15 +169,13 @@ export default function JobsPage() {
<StatusBadge status={job.status} />
</div>
</div>
{job.status === "queued" || job.status === "processing" ? (
{job.status === "processing" ? (
<div className="mt-4">
<ProgressBar value={job.progress} label={t("progressLabel")} />
<p className="mt-1.5 text-xs text-stone-500">
{job.progress > 0
? t("percent", {
value: nf.format(Math.min(100, Math.round(job.progress))),
})
: t("preparing")}
{t("percent", {
value: nf.format(Math.min(100, Math.max(0, job.progress))),
})}
</p>
</div>
) : null}
-10
View File
@@ -3,16 +3,6 @@
@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 {
+5 -16
View File
@@ -34,14 +34,8 @@ 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
@@ -49,18 +43,13 @@ export function ProgressBar({ value, label }: { value: number; label?: string })
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={indeterminate ? undefined : Math.round(clamped)}
aria-busy={indeterminate || undefined}
aria-valuenow={Math.round(clamped)}
aria-label={label}
>
{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
className="h-full rounded-full bg-teal-700 transition-[width] duration-500 ease-out"
style={{ width: `${clamped}%` }}
/>
</div>
);
}