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
31 changed files with 247 additions and 541 deletions

No files matched your search

-9
View File
@@ -106,9 +106,6 @@ 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
@@ -132,12 +129,6 @@ 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.
+13 -25
View File
@@ -5,31 +5,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### Security
- **`POST /auth/telegram` could be used to take over any Telegram user's
account.** It minted a fresh API token for whatever `telegram_id` the
caller sent, with no proof the caller was the bot. It now requires the
`X-Bot-Secret` header to match the new `BOT_API_SECRET` (constant-time
compare; 403 on mismatch, 503 while unset). **Breaking for deployments
with the bot:** set the same `BOT_API_SECRET` on the API and the bot; the
bot refuses to start without it.
- Request bodies above `MAX_UPLOAD_MB` (plus 1 MiB multipart allowance) are
now refused with 413 by a middleware, up front from `Content-Length` or
mid-stream for chunked uploads. Before, the size check ran only after the
whole body had been spooled to disk and read into memory, so one
multi-gigabyte upload could exhaust the API container's disk or RAM.
- Webhook `callback_url`s can no longer target internal addresses. Any
user could point the worker at loopback, private, link-local (cloud
metadata) or LAN hosts. Literal private hosts are now rejected at upload
(422), every resolved address is checked again at connect time (defeating
DNS rebinding), redirects are not followed and proxy env vars are ignored.
**Breaking for receivers on private addresses:** set
`WEBHOOK_ALLOW_PRIVATE_TARGETS=true` on trusted single-tenant installs.
- `POST /auth/login` is throttled: after `LOGIN_MAX_FAILURES` (10) failures
per client address and email within `LOGIN_FAILURE_WINDOW_SECONDS` (900)
it answers 429 with `Retry-After`; a successful login clears the count.
### Added
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
@@ -99,6 +74,19 @@ 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
-3
View File
@@ -225,12 +225,9 @@ 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) |
-3
View File
@@ -224,12 +224,9 @@ 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) |
-40
View File
@@ -1,40 +0,0 @@
from fastapi import HTTPException
from starlette.responses import JSONResponse
from starlette.types import ASGIApp, Message, Receive, Scope, Send
MULTIPART_OVERHEAD_BYTES = 1024 * 1024
_DETAIL = "request body too large"
_PAYLOAD_TOO_LARGE = 413
class BodySizeLimitMiddleware:
def __init__(self, app: ASGIApp, max_body_bytes: int) -> None:
self.app = app
self.max_body_bytes = max_body_bytes
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
declared = dict(scope.get("headers") or []).get(b"content-length")
if declared is not None and declared.isdigit() and int(declared) > self.max_body_bytes:
response = JSONResponse(
{"detail": _DETAIL}, status_code=_PAYLOAD_TOO_LARGE
)
await response(scope, receive, send)
return
received = 0
async def limited_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_body_bytes:
raise HTTPException(_PAYLOAD_TOO_LARGE, _DETAIL)
return message
await self.app(scope, limited_receive, send)
-11
View File
@@ -44,14 +44,3 @@ 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")
+3 -38
View File
@@ -11,15 +11,12 @@ Deliberately lightweight for v1:
import re
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session
from sokhan.api.deps import require_bot
from sokhan.auth import generate_token, hash_password, token_hash, verify_password
from sokhan.config import get_settings
from sokhan.core.throttle import FailureThrottle
from sokhan.db import get_db
from sokhan.models import User
from sokhan.schemas import AuthResponse
@@ -79,44 +76,12 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
return AuthResponse(id=user.id, email=user.email, api_token=token)
_login_throttle: FailureThrottle | None = None
def get_login_throttle() -> FailureThrottle:
global _login_throttle
if _login_throttle is None:
settings = get_settings()
_login_throttle = FailureThrottle(
settings.login_max_failures, settings.login_failure_window_seconds
)
return _login_throttle
def reset_login_throttle() -> None:
global _login_throttle
_login_throttle = None
@router.post("/login", response_model=AuthResponse)
def login(
payload: Credentials, request: Request, session: Session = Depends(get_db)
) -> AuthResponse:
def login(payload: Credentials, 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)
@@ -132,7 +97,7 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
@router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)])
@router.post("/telegram", response_model=AuthResponse)
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
"""Register-or-login used by the Telegram bot.
+6 -7
View File
@@ -14,7 +14,6 @@ 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
@@ -54,16 +53,16 @@ def create_job(
if callback_url is not None:
callback_url = callback_url.strip() or None
settings = get_settings()
if callback_url:
if len(callback_url) > 2048:
if callback_url and (
len(callback_url) > 2048
or not callback_url.lower().startswith(("http://", "https://"))
):
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY,
"callback_url must be an http(s) URL of at most 2048 characters",
)
problem = callback_url_problem(callback_url, settings.webhook_allow_private_targets)
if problem:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, problem)
settings = get_settings()
data = file.file.read()
if not data:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "empty file")
-6
View File
@@ -74,8 +74,6 @@ class Settings(BaseSettings):
# Leave empty to disable the admin endpoints entirely.
admin_api_key: str = ""
bot_api_secret: str = ""
# LLM summaries (optional, behind a feature flag)
summary_enabled: bool = False
llm_api_base: str = ""
@@ -93,10 +91,6 @@ 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)
-48
View File
@@ -1,48 +0,0 @@
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)
+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 -102
View File
@@ -21,17 +21,13 @@ 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
@@ -93,99 +89,6 @@ 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,
@@ -193,11 +96,7 @@ def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float
headers={"Content-Type": "application/json", **headers},
method="POST",
)
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:
with urllib.request.urlopen(request, timeout=timeout) as response:
response.read()
-5
View File
@@ -14,7 +14,6 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sokhan import __version__
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
from sokhan.config import get_settings
from sokhan.db import configure, create_all
@@ -53,10 +52,6 @@ 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,
+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:
-3
View File
@@ -29,18 +29,15 @@ 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()
+3 -33
View File
@@ -1,4 +1,3 @@
import pytest
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
@@ -52,43 +51,14 @@ def test_token_login_rejects_bad_code(client):
assert response.status_code == 401
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)
def test_telegram_register_or_login(client):
first = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
assert first.status_code == 200
second = client.post("/auth/telegram", json=body, headers=bot_secret)
second = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
assert second.status_code == 200
assert first.json()["id"] == second.json()["id"]
def test_telegram_login_rejects_callers_without_the_bot_secret(client, bot_secret):
body = {"telegram_id": 12345}
missing = client.post("/auth/telegram", json=body)
wrong = client.post("/auth/telegram", json=body, headers={"X-Bot-Secret": "guess"})
assert missing.status_code == 403
assert wrong.status_code == 403
def test_telegram_login_is_disabled_without_a_configured_secret(client):
response = client.post(
"/auth/telegram", json={"telegram_id": 12345}, headers={"X-Bot-Secret": ""}
)
assert response.status_code == 503
def test_jobs_require_token(client):
response = client.get("/jobs")
assert response.status_code == 401
-49
View File
@@ -1,49 +0,0 @@
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"
-55
View File
@@ -1,55 +0,0 @@
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
+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
-50
View File
@@ -341,53 +341,3 @@ 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)
-1
View File
@@ -50,7 +50,6 @@ class SokhanClient:
response = self._client.post(
f"{self.settings.api_base_url}/auth/telegram",
json={"telegram_id": telegram_id, "username": username},
headers={"X-Bot-Secret": self.settings.bot_api_secret},
)
if response.status_code != 200:
raise BackendError(f"register failed with status {response.status_code}")
-2
View File
@@ -9,7 +9,6 @@ class BotSettings:
telegram_bot_token: str
api_base_url: str
web_base_url: str
bot_api_secret: str = ""
def load_settings() -> BotSettings:
@@ -17,5 +16,4 @@ def load_settings() -> BotSettings:
telegram_bot_token=os.environ.get("TELEGRAM_BOT_TOKEN", ""),
api_base_url=os.environ.get("API_BASE_URL", "http://localhost:8000").rstrip("/"),
web_base_url=os.environ.get("WEB_BASE_URL", "http://localhost:3000").rstrip("/"),
bot_api_secret=os.environ.get("BOT_API_SECRET", ""),
)
-7
View File
@@ -30,13 +30,6 @@ def main() -> None:
file=sys.stderr,
)
raise SystemExit(1)
if not settings.bot_api_secret:
print(
"BOT_API_SECRET is not set. Set the same value on the API and the bot; "
"the API refuses Telegram logins without it.",
file=sys.stderr,
)
raise SystemExit(1)
bot = Bot(settings.telegram_bot_token)
dispatcher = Dispatcher()
-18
View File
@@ -88,21 +88,3 @@ 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"
-4
View File
@@ -48,15 +48,11 @@ services:
LOW_CONFIDENCE_THRESHOLD: ${LOW_CONFIDENCE_THRESHOLD:-0.5}
STREAMING_DECODE: ${STREAMING_DECODE:-true}
WEBHOOK_SIGNING_SECRET: ${WEBHOOK_SIGNING_SECRET:-}
WEBHOOK_ALLOW_PRIVATE_TARGETS: ${WEBHOOK_ALLOW_PRIVATE_TARGETS:-false}
LOGIN_MAX_FAILURES: ${LOGIN_MAX_FAILURES:-10}
LOGIN_FAILURE_WINDOW_SECONDS: ${LOGIN_FAILURE_WINDOW_SECONDS:-900}
FREE_MINUTES_PER_USER_PER_MONTH: ${FREE_MINUTES_PER_USER_PER_MONTH:-30}
PLAN_FREE_MAX_FILE_MINUTES: ${PLAN_FREE_MAX_FILE_MINUTES:-10}
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}
PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200}
ADMIN_API_KEY: ${ADMIN_API_KEY:-}
BOT_API_SECRET: ${BOT_API_SECRET:-}
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
LLM_API_BASE: ${LLM_API_BASE:-}
+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>
);
}