Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53becfa1de
|
No files matched your search
+6
-10
@@ -76,16 +76,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
### 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.
|
||||
- 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.
|
||||
|
||||
## [1.4.1] - 2026-11-26
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
+19
-1
@@ -10,11 +10,13 @@ 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.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 +29,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; "
|
||||
@@ -68,6 +78,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"}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()) == []
|
||||
@@ -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
|
||||
@@ -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",
|
||||
|
||||
@@ -100,7 +100,6 @@
|
||||
"statusFailed": "ناموفق",
|
||||
"progressLabel": "پیشرفت پردازش",
|
||||
"percent": "{value}٪",
|
||||
"preparing": "در حال آمادهسازی…",
|
||||
"emptyTitle": "هنوز رونویسیای نداری",
|
||||
"emptyDesc": "اولین فایل را بارگذاری کن تا همینجا فهرست شود.",
|
||||
"emptyCta": "رونویسی تازه",
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user