Author SHA1 Message Date
ahp ad23bbfa43 fix(web): live progress in the archive and a working state at 0%
- the archive re-fetches every 3 s while any job is queued or
  processing; it loaded once, so its progress bars never moved
- ProgressBar shows a moving bar while no progress has been reported
  yet, with "Getting ready" in place of 0%, and falls back to a pulse
  under prefers-reduced-motion
- the job page uses the translated percent string, so English no
  longer shows the Persian percent sign
2026-11-26 17:58:10 +03:30
ahp 36262770d0 fix(worker): report job progress while a chunk is transcribed
Progress was only saved after each 30-second chunk, so a clip shorter
than 30 s (one chunk) sat at 0% for the whole job, model load included,
and then jumped to 100%.

- the Whisper engine calls an optional on_progress callback with how far
  into the chunk it is, as faster-whisper yields each segment
- the pipeline maps that onto overall progress (by chunk count, or by
  the duration estimate when streaming) and saves it monotonically,
  below 100 and at most once a second
- engines opt in with reports_progress; ones with the plain
  three-argument transcribe keep working unchanged
2026-11-26 17:58:10 +03:30
13 changed files with 235 additions and 120 deletions

No files matched your search

+10 -6
View File
@@ -76,12 +76,16 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
### 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.
- 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
+3 -22
View File
@@ -25,14 +25,6 @@ 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)
@@ -110,23 +102,12 @@ 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.
Raises StorageUnavailableError when the directory or file cannot be
written; a partially written file is removed first.
"""
"""Persist an upload under DATA_DIR/audio with a safe extension."""
suffix = Path(original_filename).suffix.lower()
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
suffix = ".bin"
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
path = audio_dir() / f"{job_id}{suffix}"
path.write_bytes(data)
return path
+36 -2
View File
@@ -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
+1 -19
View File
@@ -10,13 +10,11 @@ import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sokhan import __version__
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")
@@ -29,14 +27,6 @@ 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; "
@@ -78,14 +68,6 @@ 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"}
+37 -4
View File
@@ -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
@@ -41,7 +42,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
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
@@ -50,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,
@@ -123,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:
-51
View File
@@ -1,8 +1,5 @@
import io
import shutil
from pathlib import Path
import pytest
from docx import Document
@@ -191,51 +188,3 @@ 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()) == []
+91
View File
@@ -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
+1
View File
@@ -100,6 +100,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",
+1
View File
@@ -100,6 +100,7 @@
"statusFailed": "ناموفق",
"progressLabel": "پیشرفت پردازش",
"percent": "{value}٪",
"preparing": "در حال آماده‌سازی…",
"emptyTitle": "هنوز رونویسی‌ای نداری",
"emptyDesc": "اولین فایل را بارگذاری کن تا همین‌جا فهرست شود.",
"emptyCta": "رونویسی تازه",
+10 -6
View File
@@ -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();
@@ -275,12 +276,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>
+19 -5
View File
@@ -24,6 +24,8 @@ function formatDate(iso: string, locale: string): string {
}
}
const REFRESH_INTERVAL_MS = 3000;
export default function JobsPage() {
const t = useTranslations("jobs");
const tc = useTranslations("common");
@@ -35,6 +37,8 @@ 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");
@@ -72,7 +76,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 +181,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}
+10
View File
@@ -3,6 +3,16 @@
@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 {
+16 -5
View File
@@ -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>
);
}