Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3437ee230
|
||
|
|
ace0b764ba
|
||
|
|
064e7a0bd5
|
||
|
|
9d35436cce
|
||
|
|
bcce7ac897
|
||
|
|
9ccf51e3c9
|
||
|
|
3895219768
|
||
|
|
b22dd5d161
|
||
|
|
032b8de9e8
|
||
|
|
3123e2006c
|
||
|
|
1219089a3c
|
||
|
|
a29dae7f56
|
||
|
|
d254527881
|
||
|
|
53becfa1de
|
||
|
|
4d2c060a29
|
||
|
|
f1f8a9919b
|
||
|
|
ea821ff70b
|
||
|
|
ad23bbfa43
|
||
|
|
36262770d0
|
||
|
|
d93d98c102
|
||
|
|
a2bab55d25
|
||
|
|
9e6d8fc91a
|
||
|
|
8a585fc718
|
||
|
|
57be6ca2ce
|
||
|
|
103f72f41e
|
||
|
|
ee42254ab1
|
||
|
|
9d15525500
|
||
|
|
c902ab4469
|
||
|
|
1304b13999
|
No files matched your search
@@ -1,5 +1,6 @@
|
||||
# Sokhan configuration
|
||||
# Copy this file to .env and adjust the values.
|
||||
# For docker compose, copy it to deploy/.env instead.
|
||||
# Every variable below has a working default for local development.
|
||||
|
||||
# --- Core ---
|
||||
@@ -117,6 +118,9 @@ LLM_MODEL=
|
||||
# --- Telegram bot (optional) ---
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
|
||||
# Shared secret between the bot and the API; set the same value on both.
|
||||
BOT_API_SECRET=
|
||||
|
||||
# URL the bot puts in messages so users can open their archive in the browser.
|
||||
WEB_BASE_URL=http://localhost:3000
|
||||
|
||||
@@ -144,6 +148,12 @@ WEBHOOK_SIGNING_SECRET=
|
||||
# best-effort and never flips the job status).
|
||||
WEBHOOK_TIMEOUT_SECONDS=4.0
|
||||
WEBHOOK_ATTEMPTS=2
|
||||
# Allow callbacks to private/loopback addresses (trusted installs only).
|
||||
WEBHOOK_ALLOW_PRIVATE_TARGETS=false
|
||||
|
||||
# --- Login brute-force guard ---
|
||||
LOGIN_MAX_FAILURES=10
|
||||
LOGIN_FAILURE_WINDOW_SECONDS=900
|
||||
|
||||
# --- Deployment (deploy/docker-compose.yml) ---
|
||||
# Required: the compose file refuses to start without a real password.
|
||||
|
||||
@@ -7,6 +7,41 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
### Security
|
||||
|
||||
- **`POST /auth/telegram` could be used to take over any Telegram user's
|
||||
account.** It minted a fresh API token for whatever `telegram_id` the
|
||||
caller sent, with no proof the caller was the bot. It now requires the
|
||||
`X-Bot-Secret` header to match the new `BOT_API_SECRET` (constant-time
|
||||
compare; 403 on mismatch, 503 while unset). **Breaking for deployments
|
||||
with the bot:** set the same `BOT_API_SECRET` on the API and the bot; the
|
||||
bot refuses to start without it.
|
||||
- Request bodies above `MAX_UPLOAD_MB` (plus 1 MiB multipart allowance) are
|
||||
now refused with 413 by a middleware, up front from `Content-Length` or
|
||||
mid-stream for chunked uploads. Before, the size check ran only after the
|
||||
whole body had been spooled to disk and read into memory, so one
|
||||
multi-gigabyte upload could exhaust the API container's disk or RAM.
|
||||
- Webhook `callback_url`s can no longer target internal addresses. Any
|
||||
user could point the worker at loopback, private, link-local (cloud
|
||||
metadata) or LAN hosts. Literal private hosts are now rejected at upload
|
||||
(422), every resolved address is checked again at connect time (defeating
|
||||
DNS rebinding), redirects are not followed and proxy env vars are ignored.
|
||||
**Breaking for receivers on private addresses:** set
|
||||
`WEBHOOK_ALLOW_PRIVATE_TARGETS=true` on trusted single-tenant installs.
|
||||
- `POST /auth/login` is throttled: after `LOGIN_MAX_FAILURES` (10) failures
|
||||
per client address and email within `LOGIN_FAILURE_WINDOW_SECONDS` (900)
|
||||
it answers 429 with `Retry-After`; a successful login clears the count.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Compose: the Whisper model cache now lives on the `sokhan-data` volume
|
||||
(`HF_HOME=/data/huggingface`). Previously it sat in the container's own
|
||||
filesystem, so every recreate (`down`/`up`, `--build`, a new image)
|
||||
re-downloaded the weights — and transcription failed outright where the
|
||||
Hugging Face Hub is unreachable.
|
||||
- Compose: the postgres healthcheck probes the configured `POSTGRES_USER` and
|
||||
`POSTGRES_DB` instead of a hardcoded `sokhan`.
|
||||
- Quickstart (both READMEs) and `.env.example` now say to copy the env file to
|
||||
`deploy/.env`; the missing-password error names that path too. Copying it to
|
||||
the repo root left `POSTGRES_PASSWORD` unset for compose.
|
||||
- Sign-in through the dashboard flows (register, login, connect code) now
|
||||
also sets the token as an `HttpOnly; SameSite=lax` session cookie
|
||||
(`Secure` whenever the browser uses HTTPS), and the API accepts it in place of a bearer header. Every
|
||||
@@ -61,6 +96,11 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
fine-tuned 0.75 / medium 0.5625); the weekly benchmark workflow now
|
||||
guards `small` **and** `medium`; regression-gate test updated to the
|
||||
committed baseline.
|
||||
- Dashboard dark mode: a sun/moon toggle in the header, defaulting to the OS
|
||||
preference until the user picks one (saved in localStorage, applied before
|
||||
first paint so there is no flash). Implemented by remapping the Tailwind
|
||||
palette under `html.dark` in `globals.css`, so existing pages needed no
|
||||
per-class changes.
|
||||
- Brand refresh: a hero banner in both READMEs (`docs/assets/banner.png`),
|
||||
a redesigned 1280x640 social preview (`docs/assets/social-preview.png` —
|
||||
upload it once in Settings → General → Social preview) and a 512px app
|
||||
@@ -75,7 +115,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
worker with timestamp-midpoint trimming, enabling the progress stream
|
||||
and duration caps: 30 min on WebGPU, 10 min on WASM, 60 MB per file —
|
||||
no input can wedge the demo at an eternal "processing" state anymore.
|
||||
- A show/hide toggle (eye icon) on the login page's password field.
|
||||
|
||||
- `CONTRIBUTING.fa.md`: a Persian translation of the contribution guide,
|
||||
with a language switcher in both files like the READMEs (#31).
|
||||
- `POST /auth/logout` revokes the caller's token (204). An account has a
|
||||
single active token, so it signs out every client holding it.
|
||||
|
||||
@@ -106,13 +149,44 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
under it. Applied across LICENSE, both READMEs, CITATION.cff, both
|
||||
pyproject.toml files, web/package.json, the landing site copy, the demo
|
||||
Space metadata and the fine-tuned model card.
|
||||
- The header shows the signed-in account as an avatar with the email's
|
||||
initial. It opens a menu with the full email and Sign out, instead of a
|
||||
truncated email that disappeared on narrow screens.
|
||||
|
||||
### Fixed
|
||||
|
||||
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
|
||||
read-only volume) now answers **503** with a short message on `POST /jobs`
|
||||
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
|
||||
the log. The real `OSError` is logged server-side, a partially written
|
||||
file is removed, and the API logs an error at startup when `DATA_DIR`
|
||||
is not writable.
|
||||
- The punctuation post-pass no longer splits numbers written with a
|
||||
thousands separator: `1,000` stayed `1، 000` (Persian comma plus a
|
||||
space). A comma between digits followed by exactly three digits is now
|
||||
kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`.
|
||||
The edge cases from #30 (slash dates, Latin digits in Persian sentences,
|
||||
abbreviations, ellipses, repeated marks) are pinned by tests.
|
||||
- The Telegram bot recovers when the API revokes the token it cached for a
|
||||
chat (a newer sign-in or a logout of the same account). Every request
|
||||
used to fail from then on; the bot now drops the token, re-registers
|
||||
once and retries, and `/start` only shows a connect code that works.
|
||||
- Job progress now moves while a chunk is being transcribed, not only
|
||||
between 30-second chunks. A clip shorter than 30 s is a single chunk, so
|
||||
its progress sat at 0% for the whole job and then jumped to 100%. The
|
||||
Whisper engine reports how far into the chunk it is as each segment is
|
||||
decoded; the worker saves that at most once a second.
|
||||
- The archive page refreshes itself while any job is queued or processing;
|
||||
its progress bars never moved before. A job with no progress reported yet
|
||||
shows a moving bar and "Getting ready" instead of an empty, stuck-looking
|
||||
bar at 0%, and the job page shows the percentage with the right sign in
|
||||
English.
|
||||
|
||||
### Removed
|
||||
|
||||
- The landing page's separate sign-in button; signing in lives in
|
||||
the header, and "Get started" sends signed-out visitors to the login
|
||||
page.
|
||||
|
||||
## [1.4.1] - 2026-11-26
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# مشارکت در سخن
|
||||
|
||||
[English](CONTRIBUTING.md) | **فارسی**
|
||||
|
||||
ممنون که به سخن سر زدید. این مخزن یک کیت گفتار به متنِ فارسی است که
|
||||
میشود سلفهاستش کرد: یک بکاند FastAPI با موتور faster-whisper، یک ورکر
|
||||
Celery، یک داشبورد Next.js (فارسیمحور و راستبهچپ)، یک ربات تلگرام
|
||||
اختیاری، یک پایپلاین فاینتیونِ LoRA با نتایجِ اندازهگیریشده، و یک دموی
|
||||
عمومیِ مرورگری روی Hugging Face.
|
||||
|
||||
## راهاندازی محیط توسعه
|
||||
|
||||
برای بکاند و ربات Python 3.12 و برای داشبورد وب Node 22 لازم است:
|
||||
|
||||
pip install -e "backend[dev]" -e "bot[dev]"
|
||||
cd web && npm ci
|
||||
|
||||
وابستگیهای سنگین (torch / faster-whisper) فقط برای ابزارهای آموزش و
|
||||
بنچمارک لازماند:
|
||||
|
||||
pip install -r training/requirements.txt -r benchmarks/requirements.txt
|
||||
pip install -r space/gradio/requirements.txt # self-hostable Gradio demo
|
||||
|
||||
## تستها، لینت و نظم کامیتها
|
||||
|
||||
CI روی هر push و pull request همین دستورها را اجرا میکند:
|
||||
|
||||
ruff check backend bot training benchmarks space deploy
|
||||
mypy --config-file backend/pyproject.toml backend/sokhan
|
||||
pytest backend/tests bot/tests
|
||||
cd web && npm ci && npm run build
|
||||
|
||||
هوکهای pre-commit (ruff بهعلاوهٔ چند بررسی پایه) را برای هر کلون یک بار
|
||||
فعال کنید:
|
||||
|
||||
pip install pre-commit && pre-commit install
|
||||
|
||||
پیام کامیتها از Conventional Commits پیروی میکنند (`feat:`، `fix:`،
|
||||
`docs:`، ...) و نسخهگذاری پروژه بر اساس Semantic Versioning است؛ هر
|
||||
تغییری که کاربر میبیند یک خط در CHANGELOG.md میگیرد.
|
||||
|
||||
## دموی مرورگری و ورکفلوی sync-space
|
||||
|
||||
`space/` دموی استاتیکی است که Whisper در آن کاملاً سمتِ مرورگر اجرا
|
||||
میشود (transformers.js). ورکفلوی `Sync demo Space` با هر pushای که به
|
||||
`space/` دست بزند، آن را با سکرتِ `HF_TOKEN` در Actions مخزن روی
|
||||
hf.co/spaces/Abol0pati/sokhan-fa-demo منتشر میکند - برای همین دموی
|
||||
عمومی هیچوقت از `main` عقب نمیماند. `space/gradio/` یک اپ جدا و
|
||||
سلفهاستشدنی است که چکپوینتِ فاینتیونشده را با همان تنظیمات موتورِ
|
||||
محیط production سرو میکند؛ این اپ عمداً روی Space عمومی آپلود نمیشود
|
||||
(قیمتگذاری ۲۰۲۶ هاگینگفیس، Spaceهای میزبانیشدهٔ Gradio/Docker را پشت
|
||||
اشتراک PRO قفل کرده است).
|
||||
|
||||
## قاعدهٔ «اول اندازهگیری»
|
||||
|
||||
هر ادعایی دربارهٔ دقت (WER، CER، سرعت) که در README، کارت مدل یا
|
||||
changelog میآید باید از `benchmarks/benchmark_wer.py` (یا ارزیابیِ
|
||||
نوتبوک) آمده باشد و فیکسچر و سختافزارش ذکر شده باشد. هیچ عددِ ساختگی
|
||||
پذیرفته نیست.
|
||||
|
||||
## امنیت
|
||||
|
||||
گزارشهای امنیتی را بهصورت issue عمومی باز نکنید - برای افشای خصوصی
|
||||
SECURITY.md را ببینید.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Contributing to Sokhan
|
||||
|
||||
**English** | [فارسی](CONTRIBUTING.fa.md)
|
||||
|
||||
Thanks for looking into Sokhan. This repo is a self-hostable Persian
|
||||
speech-to-text kit: a FastAPI backend with a faster-whisper engine, a
|
||||
Celery worker, a Next.js (Persian-first, RTL) dashboard, an optional
|
||||
|
||||
+8
-1
@@ -145,6 +145,8 @@ faster-whisper، یک ورکر Celery، یک داشبورد Next.js که فار
|
||||
```bash
|
||||
git clone https://github.com/Abolfazlrwm/sokhan.git
|
||||
cd sokhan
|
||||
cp .env.example deploy/.env # compose فایل .env کنار فایل compose را میخواند
|
||||
# در deploy/.env مقدار POSTGRES_PASSWORD را یک رمز طولانی و تصادفی بگذارید
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
@@ -152,7 +154,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
|
||||
- API و مستندات: http://localhost:8000/docs
|
||||
|
||||
ورکر مدل Whisper تنظیمشده را در اولین رونویسی دانلود میکند
|
||||
(`WHISPER_MODEL_SIZE`، پیشفرض `small`). برای فعالکردن خلاصهسازی،
|
||||
(`WHISPER_MODEL_SIZE`، پیشفرض `small`) و آن را روی ولوم `sokhan-data`
|
||||
(`HF_HOME=/data/huggingface`) نگه میدارد، پس ساخت دوبارهٔ کانتینرها مدل را
|
||||
دوباره دانلود نمیکند. برای فعالکردن خلاصهسازی،
|
||||
`SUMMARY_ENABLED=true` و متغیرهای LLM خود را در فایل `.env` کنار
|
||||
`docker-compose.yml` بگذارید. برای اعمال مهاجرتهای اسکیما بهصورت دستی:
|
||||
|
||||
@@ -225,9 +229,12 @@ 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` | خالی (همان origin، `/api`) | آدرس API که اپ وب صدا میزند، فقط وقتی API روی هاست جدا است (زمان build) |
|
||||
|
||||
@@ -143,6 +143,8 @@ default — a GPU is not required.
|
||||
```bash
|
||||
git clone https://github.com/Abolfazlrwm/sokhan.git
|
||||
cd sokhan
|
||||
cp .env.example deploy/.env # compose reads the .env next to the compose file
|
||||
# edit deploy/.env and set POSTGRES_PASSWORD to a long random value
|
||||
docker compose -f deploy/docker-compose.yml up -d --build
|
||||
```
|
||||
|
||||
@@ -150,7 +152,9 @@ docker compose -f deploy/docker-compose.yml up -d --build
|
||||
- API and docs: http://localhost:8000/docs
|
||||
|
||||
The worker downloads the configured Whisper model on first transcription
|
||||
(`WHISPER_MODEL_SIZE`, default `small`). To enable summaries, set
|
||||
(`WHISPER_MODEL_SIZE`, default `small`) and caches it on the `sokhan-data`
|
||||
volume (`HF_HOME=/data/huggingface`), so recreating the containers does not
|
||||
download it again. To enable summaries, set
|
||||
`SUMMARY_ENABLED=true` and your LLM variables in a `.env` file next to
|
||||
`docker-compose.yml`. To apply schema migrations manually:
|
||||
|
||||
@@ -224,9 +228,12 @@ 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` | empty (same-origin `/api`) | API address the web app calls, only for an API on its own host (build-time) |
|
||||
|
||||
+3
-3
@@ -12,9 +12,9 @@ COPY alembic ./alembic
|
||||
|
||||
RUN pip install --no-cache-dir .
|
||||
|
||||
# Non-root runtime user; uvicorn binds 8000 (unprivileged) and the app keeps
|
||||
# no local writable state (postgres via DATABASE_URL).
|
||||
RUN useradd --system --uid 1000 --create-home appuser
|
||||
RUN useradd --system --uid 1000 --create-home appuser \
|
||||
&& mkdir -p /data/audio \
|
||||
&& chown -R appuser:appuser /data
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import HTTPException
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
MULTIPART_OVERHEAD_BYTES = 1024 * 1024
|
||||
|
||||
_DETAIL = "request body too large"
|
||||
_PAYLOAD_TOO_LARGE = 413
|
||||
|
||||
|
||||
class BodySizeLimitMiddleware:
|
||||
def __init__(self, app: ASGIApp, max_body_bytes: int) -> None:
|
||||
self.app = app
|
||||
self.max_body_bytes = max_body_bytes
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
declared = dict(scope.get("headers") or []).get(b"content-length")
|
||||
if declared is not None and declared.isdigit() and int(declared) > self.max_body_bytes:
|
||||
response = JSONResponse(
|
||||
{"detail": _DETAIL}, status_code=_PAYLOAD_TOO_LARGE
|
||||
)
|
||||
await response(scope, receive, send)
|
||||
return
|
||||
|
||||
received = 0
|
||||
|
||||
async def limited_receive() -> Message:
|
||||
nonlocal received
|
||||
message = await receive()
|
||||
if message["type"] == "http.request":
|
||||
received += len(message.get("body", b""))
|
||||
if received > self.max_body_bytes:
|
||||
raise HTTPException(_PAYLOAD_TOO_LARGE, _DETAIL)
|
||||
return message
|
||||
|
||||
await self.app(scope, limited_receive, send)
|
||||
@@ -74,3 +74,14 @@ def require_admin(x_admin_key: str | None = Header(default=None)) -> None:
|
||||
)
|
||||
if x_admin_key is None or not secrets.compare_digest(x_admin_key, settings.admin_api_key):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid admin key")
|
||||
|
||||
|
||||
def require_bot(x_bot_secret: str | None = Header(default=None)) -> None:
|
||||
settings = get_settings()
|
||||
if not settings.bot_api_secret:
|
||||
raise HTTPException(
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
"telegram login disabled: set BOT_API_SECRET on the API and the bot",
|
||||
)
|
||||
if x_bot_secret is None or not secrets.compare_digest(x_bot_secret, settings.bot_api_secret):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "invalid bot secret")
|
||||
@@ -23,7 +23,7 @@ from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.api.deps import SESSION_COOKIE, get_current_user, get_request_token
|
||||
from sokhan.api.deps import SESSION_COOKIE, get_current_user, get_request_token, require_bot
|
||||
from sokhan.auth import (
|
||||
csrf_token_for,
|
||||
generate_token,
|
||||
@@ -32,6 +32,7 @@ from sokhan.auth import (
|
||||
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, SessionOut
|
||||
@@ -141,6 +142,24 @@ def register(
|
||||
return _start_session(request, response, user, token)
|
||||
|
||||
|
||||
_login_throttle: FailureThrottle | None = None
|
||||
|
||||
|
||||
def get_login_throttle() -> FailureThrottle:
|
||||
global _login_throttle
|
||||
if _login_throttle is None:
|
||||
settings = get_settings()
|
||||
_login_throttle = FailureThrottle(
|
||||
settings.login_max_failures, settings.login_failure_window_seconds
|
||||
)
|
||||
return _login_throttle
|
||||
|
||||
|
||||
def reset_login_throttle() -> None:
|
||||
global _login_throttle
|
||||
_login_throttle = None
|
||||
|
||||
|
||||
@router.post("/login", response_model=AuthResponse)
|
||||
def login(
|
||||
payload: Credentials,
|
||||
@@ -149,9 +168,21 @@ def login(
|
||||
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)
|
||||
@@ -204,7 +235,7 @@ def logout(
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/telegram", response_model=AuthResponse)
|
||||
@router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)])
|
||||
def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
"""Register-or-login used by the Telegram bot.
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from sokhan.api.serializers import job_to_detail, job_to_out
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.core.audio import delete_audio, probe_duration_seconds, save_upload
|
||||
from sokhan.core.formats import to_docx, to_json_transcript, to_srt, to_txt, to_vtt
|
||||
from sokhan.core.webhooks import callback_url_problem
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import Job, JobStatus, Segment, User
|
||||
from sokhan.schemas import JobCreated, JobDetailOut, JobListResponse
|
||||
@@ -53,16 +54,16 @@ def create_job(
|
||||
|
||||
if callback_url is not None:
|
||||
callback_url = callback_url.strip() or None
|
||||
if callback_url and (
|
||||
len(callback_url) > 2048
|
||||
or not callback_url.lower().startswith(("http://", "https://"))
|
||||
):
|
||||
settings = get_settings()
|
||||
if callback_url:
|
||||
if len(callback_url) > 2048:
|
||||
raise HTTPException(
|
||||
status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
"callback_url must be an http(s) URL of at most 2048 characters",
|
||||
)
|
||||
|
||||
settings = get_settings()
|
||||
problem = callback_url_problem(callback_url, settings.webhook_allow_private_targets)
|
||||
if problem:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, problem)
|
||||
data = file.file.read()
|
||||
if not data:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "empty file")
|
||||
|
||||
@@ -74,6 +74,8 @@ class Settings(BaseSettings):
|
||||
# Leave empty to disable the admin endpoints entirely.
|
||||
admin_api_key: str = ""
|
||||
|
||||
bot_api_secret: str = ""
|
||||
|
||||
# Dashboard session cookie (httpOnly). AUTH_COOKIE_SECURE=auto sets the
|
||||
# Secure attribute whenever the browser came in over HTTPS (directly or
|
||||
# via X-Forwarded-Proto); true/false force it. The web app proxies the
|
||||
@@ -100,6 +102,10 @@ class Settings(BaseSettings):
|
||||
webhook_signing_secret: str = ""
|
||||
webhook_timeout_seconds: float = 4.0
|
||||
webhook_attempts: int = 2
|
||||
webhook_allow_private_targets: bool = False
|
||||
|
||||
login_max_failures: int = 10
|
||||
login_failure_window_seconds: int = 900
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
|
||||
@@ -25,6 +25,14 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
|
||||
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
|
||||
|
||||
|
||||
class StorageUnavailableError(Exception):
|
||||
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
|
||||
|
||||
It is a server fault, not a bad upload, so the API answers 503 and the
|
||||
real OSError stays in the server log instead of reaching the client.
|
||||
"""
|
||||
|
||||
|
||||
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
|
||||
"""Decode any media file to mono float32 PCM at 16 kHz."""
|
||||
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
|
||||
@@ -102,12 +110,23 @@ def audio_dir() -> Path:
|
||||
|
||||
|
||||
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension."""
|
||||
"""Persist an upload under DATA_DIR/audio with a safe extension.
|
||||
|
||||
Raises StorageUnavailableError when the directory or file cannot be
|
||||
written; a partially written file is removed first.
|
||||
"""
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
|
||||
suffix = ".bin"
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
path.write_bytes(data)
|
||||
try:
|
||||
path = audio_dir() / f"{job_id}{suffix}"
|
||||
except OSError as exc:
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
try:
|
||||
path.write_bytes(data)
|
||||
except OSError as exc:
|
||||
delete_audio(path)
|
||||
raise StorageUnavailableError(str(exc)) from exc
|
||||
return path
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ puts the transcript back into publishable shape with three conservative,
|
||||
deterministic rule families — no model call, no LLM dependency:
|
||||
|
||||
1. Script fix: the Latin comma, question mark and semicolon become their
|
||||
Persian counterparts (، ؟ ؛).
|
||||
Persian counterparts (، ؟ ؛). A comma that groups digits ("1,000",
|
||||
"12,500,000") is a thousands separator, not punctuation, and is kept.
|
||||
2. Spacing: no space *before* punctuation, exactly one space *after* clause
|
||||
and sentence punctuation. `.` and `:` are deliberately left alone so
|
||||
decimals ("3.5") and clock times ("12:30") survive.
|
||||
@@ -26,6 +27,12 @@ import re
|
||||
# Latin forms that should not survive in a Persian transcript.
|
||||
_LATIN_TO_PERSIAN = str.maketrans({",": "،", "?": "؟", ";": "؛"})
|
||||
|
||||
# A comma between a digit and exactly three more digits groups a number.
|
||||
# \d matches Persian digits too, so "۱,۲۰۰" is covered.
|
||||
_THOUSANDS_COMMA = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")
|
||||
# Stands in for a thousands comma while the Latin marks are translated.
|
||||
_KEPT_COMMA = "\x00"
|
||||
|
||||
_CLAUSE = "،؛"
|
||||
_SENTENCE_END = "؟!…."
|
||||
_PUNCT_CHARS = _CLAUSE + _SENTENCE_END + ":."
|
||||
@@ -73,7 +80,8 @@ def _has_terminal(text: str) -> bool:
|
||||
|
||||
def restore_punctuation(text: str) -> str:
|
||||
"""Return `text` with Persian punctuation restored; safe to re-apply."""
|
||||
cleaned = text.translate(_LATIN_TO_PERSIAN).strip()
|
||||
cleaned = _THOUSANDS_COMMA.sub(_KEPT_COMMA, text)
|
||||
cleaned = cleaned.translate(_LATIN_TO_PERSIAN).replace(_KEPT_COMMA, ",").strip()
|
||||
cleaned = _SPACE_BEFORE.sub(r"\1", cleaned)
|
||||
cleaned = _SPACE_AFTER.sub(r"\1 ", cleaned)
|
||||
cleaned = _WS_RUNS.sub(" ", cleaned).strip()
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Hashable
|
||||
|
||||
|
||||
class FailureThrottle:
|
||||
def __init__(
|
||||
self,
|
||||
max_failures: int,
|
||||
window_seconds: float,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> None:
|
||||
self.max_failures = max_failures
|
||||
self.window_seconds = window_seconds
|
||||
self._clock = clock
|
||||
self._failures: dict[Hashable, deque[float]] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _prune(self, key: Hashable, now: float) -> deque[float]:
|
||||
stamps = self._failures.get(key)
|
||||
if stamps is None:
|
||||
return deque()
|
||||
while stamps and now - stamps[0] >= self.window_seconds:
|
||||
stamps.popleft()
|
||||
if not stamps:
|
||||
del self._failures[key]
|
||||
return stamps
|
||||
|
||||
def retry_after(self, key: Hashable) -> int:
|
||||
if self.max_failures <= 0:
|
||||
return 0
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
stamps = self._prune(key, now)
|
||||
if len(stamps) < self.max_failures:
|
||||
return 0
|
||||
return max(1, int(stamps[0] + self.window_seconds - now + 0.999))
|
||||
|
||||
def record_failure(self, key: Hashable) -> None:
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
self._prune(key, now)
|
||||
self._failures.setdefault(key, deque()).append(now)
|
||||
|
||||
def reset(self, key: Hashable) -> None:
|
||||
with self._lock:
|
||||
self._failures.pop(key, None)
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
@@ -36,15 +37,30 @@ class Segment:
|
||||
speaker: str | None = None
|
||||
|
||||
|
||||
# Called with the fraction (0..1) of the current chunk decoded so far.
|
||||
ProgressCallback = Callable[[float], None]
|
||||
|
||||
|
||||
class Transcriber(Protocol):
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
) -> list[Segment]: ...
|
||||
|
||||
|
||||
def reports_progress(engine: object) -> bool:
|
||||
"""Whether `engine.transcribe` accepts an `on_progress` callback.
|
||||
|
||||
Opt-in via a class attribute, so third-party engines and test doubles
|
||||
with the plain three-argument signature keep working unchanged.
|
||||
"""
|
||||
return bool(getattr(engine, "reports_progress", False))
|
||||
|
||||
|
||||
class FasterWhisperTranscriber:
|
||||
"""Chunk-local transcription with faster-whisper."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_size: str | None = None,
|
||||
@@ -73,7 +89,11 @@ class FasterWhisperTranscriber:
|
||||
return self._model
|
||||
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
self,
|
||||
samples: np.ndarray,
|
||||
sample_rate: int,
|
||||
language: str,
|
||||
on_progress: ProgressCallback | None = None,
|
||||
) -> list[Segment]:
|
||||
model = self._load()
|
||||
settings = get_settings()
|
||||
@@ -86,8 +106,13 @@ class FasterWhisperTranscriber:
|
||||
if language and language != "auto":
|
||||
options["language"] = language
|
||||
segments_iter, _info = model.transcribe(samples, **options) # type: ignore[arg-type]
|
||||
chunk_seconds = len(samples) / sample_rate
|
||||
segments: list[Segment] = []
|
||||
# faster-whisper decodes lazily, segment by segment, so each step of
|
||||
# this loop is real work done: report how far into the chunk it is.
|
||||
for segment in segments_iter:
|
||||
if on_progress is not None and chunk_seconds > 0:
|
||||
on_progress(min(1.0, float(segment.end) / chunk_seconds))
|
||||
text = segment.text.strip()
|
||||
if not text:
|
||||
continue
|
||||
@@ -107,8 +132,14 @@ class FasterWhisperTranscriber:
|
||||
class FakeTranscriber:
|
||||
"""Deterministic engine for tests: one or two fixed Persian segments."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def transcribe(
|
||||
self, samples: np.ndarray, sample_rate: int, language: str
|
||||
self,
|
||||
samples: np.ndarray,
|
||||
sample_rate: int,
|
||||
language: str,
|
||||
on_progress: ProgressCallback | None = None,
|
||||
) -> list[Segment]:
|
||||
duration = len(samples) / sample_rate
|
||||
segments: list[Segment] = []
|
||||
@@ -132,6 +163,9 @@ class FakeTranscriber:
|
||||
confidence=0.741,
|
||||
)
|
||||
)
|
||||
if on_progress is not None and duration > 0:
|
||||
for segment in segments:
|
||||
on_progress(min(1.0, segment.end / duration))
|
||||
return segments
|
||||
|
||||
|
||||
|
||||
@@ -21,13 +21,17 @@ transport so tests need no network.
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from sokhan.config import get_settings
|
||||
|
||||
@@ -89,6 +93,99 @@ def verify_signature(
|
||||
return hmac.compare_digest(mac.hexdigest(), provided)
|
||||
|
||||
|
||||
class BlockedTargetError(OSError):
|
||||
pass
|
||||
|
||||
|
||||
def is_public_address(address: str) -> bool:
|
||||
ip = ipaddress.ip_address(address.split("%", 1)[0])
|
||||
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
|
||||
ip = ip.ipv4_mapped
|
||||
return ip.is_global and not ip.is_multicast
|
||||
|
||||
|
||||
def callback_url_problem(url: str, allow_private: bool) -> str | None:
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
host = parts.hostname
|
||||
parts.port # noqa: B018
|
||||
except ValueError:
|
||||
return "callback_url is not a valid URL"
|
||||
if parts.scheme.lower() not in ("http", "https") or not host:
|
||||
return "callback_url must be an http(s) URL with a host"
|
||||
if allow_private:
|
||||
return None
|
||||
if host == "localhost" or host.endswith(".localhost"):
|
||||
return "callback_url must point to a public address"
|
||||
try:
|
||||
if not is_public_address(host):
|
||||
return "callback_url must point to a public address"
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _guarded_create_connection(
|
||||
address: tuple[str, int],
|
||||
timeout: float | object = socket._GLOBAL_DEFAULT_TIMEOUT, # type: ignore[attr-defined]
|
||||
source_address: tuple[str, int] | None = None,
|
||||
*args: object,
|
||||
**kwargs: object,
|
||||
) -> socket.socket:
|
||||
host, port = address
|
||||
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
||||
if not infos:
|
||||
raise BlockedTargetError(f"{host} did not resolve")
|
||||
for info in infos:
|
||||
if not is_public_address(str(info[4][0])):
|
||||
raise BlockedTargetError(f"{host} resolves to non-public address {info[4][0]}")
|
||||
last_error: OSError | None = None
|
||||
for info in infos:
|
||||
try:
|
||||
return socket.create_connection(
|
||||
(str(info[4][0]), port), timeout, source_address # type: ignore[arg-type]
|
||||
)
|
||||
except OSError as exc:
|
||||
last_error = exc
|
||||
raise last_error or BlockedTargetError(f"could not connect to {host}")
|
||||
|
||||
|
||||
class _GuardedHTTPConnection(http.client.HTTPConnection):
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._create_connection = _guarded_create_connection # type: ignore[assignment]
|
||||
|
||||
|
||||
class _GuardedHTTPSConnection(http.client.HTTPSConnection):
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._create_connection = _guarded_create_connection # type: ignore[assignment]
|
||||
|
||||
|
||||
class _GuardedHTTPHandler(urllib.request.HTTPHandler):
|
||||
def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
|
||||
return self.do_open(_GuardedHTTPConnection, req)
|
||||
|
||||
|
||||
class _GuardedHTTPSHandler(urllib.request.HTTPSHandler):
|
||||
def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse:
|
||||
return self.do_open(_GuardedHTTPSConnection, req, context=self._context) # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _public_only_opener() -> urllib.request.OpenerDirector:
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}),
|
||||
_GuardedHTTPHandler(),
|
||||
_GuardedHTTPSHandler(),
|
||||
_NoRedirectHandler(),
|
||||
)
|
||||
|
||||
|
||||
def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float) -> None:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
@@ -96,7 +193,11 @@ def _default_post(url: str, body: bytes, headers: dict[str, str], timeout: float
|
||||
headers={"Content-Type": "application/json", **headers},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
if get_settings().webhook_allow_private_targets:
|
||||
opener = urllib.request.build_opener()
|
||||
else:
|
||||
opener = _public_only_opener()
|
||||
with opener.open(request, timeout=timeout) as response:
|
||||
response.read()
|
||||
|
||||
|
||||
|
||||
+24
-1
@@ -10,11 +10,14 @@ import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from sokhan import __version__
|
||||
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir
|
||||
from sokhan.db import configure, create_all
|
||||
|
||||
logger = logging.getLogger("sokhan")
|
||||
@@ -27,6 +30,14 @@ def create_app() -> FastAPI:
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
configure()
|
||||
create_all()
|
||||
try:
|
||||
audio_dir()
|
||||
except OSError as exc:
|
||||
logger.error(
|
||||
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
|
||||
"it is; in Docker check the volume is owned by the app user",
|
||||
exc,
|
||||
)
|
||||
if not settings.celery_enabled:
|
||||
logger.warning(
|
||||
"CELERY_ENABLED=false - jobs run inline in the API process; "
|
||||
@@ -52,6 +63,10 @@ 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,
|
||||
@@ -70,6 +85,14 @@ def create_app() -> FastAPI:
|
||||
app.include_router(routes_openai.router)
|
||||
app.include_router(routes_admin.router)
|
||||
|
||||
@app.exception_handler(StorageUnavailableError)
|
||||
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
|
||||
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
content={"detail": "upload storage is unavailable, try again later"},
|
||||
)
|
||||
|
||||
@app.get("/")
|
||||
def root() -> dict:
|
||||
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -29,15 +29,18 @@ def app(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("PLAN_PRO_MAX_FILE_MINUTES", "180")
|
||||
monkeypatch.setenv("PLAN_PRO_MONTHLY_MINUTES", "1200")
|
||||
|
||||
from sokhan.api.routes_auth import reset_login_throttle
|
||||
from sokhan.config import get_settings
|
||||
|
||||
get_settings.cache_clear()
|
||||
reset_login_throttle()
|
||||
db.reset()
|
||||
db.configure(f"sqlite:///{tmp_path / 'test.sqlite3'}")
|
||||
db.create_all()
|
||||
yield create_app()
|
||||
db.reset()
|
||||
get_settings.cache_clear()
|
||||
reset_login_throttle()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import pytest
|
||||
|
||||
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
|
||||
|
||||
@@ -51,14 +52,43 @@ def test_token_login_rejects_bad_code(client):
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_telegram_register_or_login(client):
|
||||
first = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
|
||||
BOT_SECRET = "bot-shared-secret"
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def bot_secret(monkeypatch):
|
||||
from sokhan.config import get_settings
|
||||
|
||||
monkeypatch.setenv("BOT_API_SECRET", BOT_SECRET)
|
||||
get_settings.cache_clear()
|
||||
yield {"X-Bot-Secret": BOT_SECRET}
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_telegram_register_or_login(client, bot_secret):
|
||||
body = {"telegram_id": 12345, "username": "amin"}
|
||||
first = client.post("/auth/telegram", json=body, headers=bot_secret)
|
||||
assert first.status_code == 200
|
||||
second = client.post("/auth/telegram", json={"telegram_id": 12345, "username": "amin"})
|
||||
second = client.post("/auth/telegram", json=body, headers=bot_secret)
|
||||
assert second.status_code == 200
|
||||
assert first.json()["id"] == second.json()["id"]
|
||||
|
||||
|
||||
def test_telegram_login_rejects_callers_without_the_bot_secret(client, bot_secret):
|
||||
body = {"telegram_id": 12345}
|
||||
missing = client.post("/auth/telegram", json=body)
|
||||
wrong = client.post("/auth/telegram", json=body, headers={"X-Bot-Secret": "guess"})
|
||||
assert missing.status_code == 403
|
||||
assert wrong.status_code == 403
|
||||
|
||||
|
||||
def test_telegram_login_is_disabled_without_a_configured_secret(client):
|
||||
response = client.post(
|
||||
"/auth/telegram", json={"telegram_id": 12345}, headers={"X-Bot-Secret": ""}
|
||||
)
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_jobs_require_token(client):
|
||||
response = client.get("/jobs")
|
||||
assert response.status_code == 401
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sokhan.api.body_limit import MULTIPART_OVERHEAD_BYTES
|
||||
from sokhan.main import create_app
|
||||
|
||||
MIB = 1024 * 1024
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def small_cap_client(app, monkeypatch):
|
||||
from sokhan.config import get_settings
|
||||
|
||||
monkeypatch.setenv("MAX_UPLOAD_MB", "1")
|
||||
get_settings.cache_clear()
|
||||
with TestClient(create_app()) as test_client:
|
||||
yield test_client
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
def test_declared_oversized_body_is_rejected_up_front(small_cap_client, auth):
|
||||
too_big = b"\0" * (MIB + MULTIPART_OVERHEAD_BYTES + 1)
|
||||
response = small_cap_client.post(
|
||||
"/jobs", headers=auth, files={"file": ("big.wav", too_big, "audio/wav")}
|
||||
)
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
def test_chunked_oversized_body_is_cut_off_mid_stream(small_cap_client, auth):
|
||||
def body():
|
||||
for _ in range(4):
|
||||
yield b"\0" * MIB
|
||||
|
||||
response = small_cap_client.post(
|
||||
"/jobs",
|
||||
headers={**auth, "Content-Type": "multipart/form-data; boundary=x"},
|
||||
content=body(),
|
||||
)
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
def test_upload_under_the_cap_still_works(
|
||||
small_cap_client, auth, wav_bytes, fake_engine, wait_for_job
|
||||
):
|
||||
response = small_cap_client.post(
|
||||
"/jobs", headers=auth, files={"file": ("ok.wav", wav_bytes, "audio/wav")}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
job = wait_for_job(small_cap_client, auth, response.json()["id"])
|
||||
assert job["status"] == "completed"
|
||||
@@ -1,5 +1,8 @@
|
||||
import io
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from docx import Document
|
||||
|
||||
|
||||
@@ -188,3 +191,51 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
|
||||
|
||||
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
|
||||
assert client.get("/jobs", headers=headers).json()["total"] == 0
|
||||
|
||||
|
||||
def _make_data_dir_unwritable(tmp_path):
|
||||
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
|
||||
shutil.rmtree(tmp_path / "data")
|
||||
(tmp_path / "data").write_text("not a directory")
|
||||
|
||||
|
||||
def test_upload_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = _upload(client, auth, wav_bytes)
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
|
||||
# No job row is left behind for an upload that was never stored.
|
||||
assert client.get("/jobs", headers=auth).json()["total"] == 0
|
||||
|
||||
|
||||
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
|
||||
client, auth, wav_bytes, fake_engine, tmp_path
|
||||
):
|
||||
_make_data_dir_unwritable(tmp_path)
|
||||
|
||||
response = client.post(
|
||||
"/v1/audio/transcriptions",
|
||||
files={"file": ("test.wav", wav_bytes, "audio/wav")},
|
||||
data={"language": "fa", "response_format": "json"},
|
||||
headers=auth,
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
|
||||
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
|
||||
|
||||
def write_fails_midway(self, data):
|
||||
self.open("wb").write(data[:1])
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
|
||||
|
||||
with pytest.raises(StorageUnavailableError):
|
||||
save_upload(b"RIFF....", "job-1", "clip.wav")
|
||||
assert list(audio_dir().iterdir()) == []
|
||||
@@ -0,0 +1,55 @@
|
||||
import pytest
|
||||
from sokhan.core.throttle import FailureThrottle
|
||||
|
||||
REGISTER = {"email": "amin@example.com", "password": "parool-1234"}
|
||||
WRONG = {"email": REGISTER["email"], "password": "wrong-pass"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def tight_login_limit(app, monkeypatch):
|
||||
from sokhan.api.routes_auth import reset_login_throttle
|
||||
from sokhan.config import get_settings
|
||||
|
||||
monkeypatch.setenv("LOGIN_MAX_FAILURES", "3")
|
||||
get_settings.cache_clear()
|
||||
reset_login_throttle()
|
||||
|
||||
|
||||
def test_login_is_throttled_after_repeated_failures(client, tight_login_limit):
|
||||
client.post("/auth/register", json=REGISTER)
|
||||
for _ in range(3):
|
||||
assert client.post("/auth/login", json=WRONG).status_code == 401
|
||||
|
||||
blocked = client.post("/auth/login", json=REGISTER)
|
||||
assert blocked.status_code == 429
|
||||
assert int(blocked.headers["Retry-After"]) > 0
|
||||
|
||||
|
||||
def test_successful_login_clears_the_failure_count(client, tight_login_limit):
|
||||
client.post("/auth/register", json=REGISTER)
|
||||
for _ in range(2):
|
||||
client.post("/auth/login", json=WRONG)
|
||||
assert client.post("/auth/login", json=REGISTER).status_code == 200
|
||||
for _ in range(2):
|
||||
assert client.post("/auth/login", json=WRONG).status_code == 401
|
||||
|
||||
|
||||
def test_other_accounts_are_not_locked_out(client, tight_login_limit):
|
||||
client.post("/auth/register", json=REGISTER)
|
||||
other = {"email": "sara@example.org", "password": "parool-5678"}
|
||||
client.post("/auth/register", json=other)
|
||||
for _ in range(3):
|
||||
client.post("/auth/login", json=WRONG)
|
||||
assert client.post("/auth/login", json=other).status_code == 200
|
||||
|
||||
|
||||
def test_throttle_window_slides():
|
||||
now = [1000.0]
|
||||
throttle = FailureThrottle(max_failures=2, window_seconds=60, clock=lambda: now[0])
|
||||
throttle.record_failure("k")
|
||||
throttle.record_failure("k")
|
||||
assert throttle.retry_after("k") == 60
|
||||
now[0] += 30
|
||||
assert throttle.retry_after("k") == 30
|
||||
now[0] += 30
|
||||
assert throttle.retry_after("k") == 0
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Job progress moves while a chunk is being decoded, not only between chunks.
|
||||
|
||||
A clip shorter than the 30 s window is a single chunk, so chunk-level
|
||||
progress alone sat at 0% for the whole job and then jumped to 100%.
|
||||
"""
|
||||
|
||||
import sokhan.db as db
|
||||
from sokhan.core.transcribe import FakeTranscriber, Segment, reports_progress
|
||||
from sokhan.models import Job
|
||||
|
||||
|
||||
class SlowEngine:
|
||||
"""Reports four steps through the chunk and records what the DB shows."""
|
||||
|
||||
reports_progress = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.seen: list[float] = []
|
||||
|
||||
def transcribe(self, samples, sample_rate, language, on_progress=None):
|
||||
for fraction in (0.25, 0.5, 0.75, 1.0):
|
||||
on_progress(fraction)
|
||||
with db.session_scope() as other:
|
||||
job = other.query(Job).one()
|
||||
self.seen.append(job.progress)
|
||||
return [Segment(start=0.0, end=1.0, text="سلام")]
|
||||
|
||||
|
||||
class PlainEngine:
|
||||
"""A third-party engine with the original three-argument signature."""
|
||||
|
||||
def transcribe(self, samples, sample_rate, language):
|
||||
return [Segment(start=0.0, end=1.0, text="سلام")]
|
||||
|
||||
|
||||
def _upload(client, auth, wav_bytes):
|
||||
response = client.post(
|
||||
"/jobs",
|
||||
files={"file": ("clip.wav", wav_bytes, "audio/wav")},
|
||||
data={"language": "fa"},
|
||||
headers=auth,
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
def test_progress_is_saved_inside_a_single_chunk(
|
||||
client, auth, wav_bytes, wait_for_job, monkeypatch
|
||||
):
|
||||
engine = SlowEngine()
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: engine)
|
||||
ticks = iter(range(0, 1000, 2)) # every call is 2 s later: never throttled
|
||||
monkeypatch.setattr("sokhan.worker.pipeline._progress_clock", lambda: float(next(ticks)))
|
||||
|
||||
job_id = _upload(client, auth, wav_bytes)
|
||||
wait_for_job(client, auth, job_id)
|
||||
|
||||
assert engine.seen == sorted(engine.seen)
|
||||
assert 0 < engine.seen[0] < engine.seen[-1] <= 99.0
|
||||
assert client.get(f"/jobs/{job_id}", headers=auth).json()["progress"] == 100.0
|
||||
|
||||
|
||||
def test_progress_writes_are_throttled(client, auth, wav_bytes, wait_for_job, monkeypatch):
|
||||
engine = SlowEngine()
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: engine)
|
||||
monkeypatch.setattr("sokhan.worker.pipeline._progress_clock", lambda: 5.0)
|
||||
|
||||
wait_for_job(client, auth, _upload(client, auth, wav_bytes))
|
||||
|
||||
# Same instant for every report: only the first one reaches the database.
|
||||
assert len(set(engine.seen)) == 1
|
||||
|
||||
|
||||
def test_engines_without_progress_support_still_work(
|
||||
client, auth, wav_bytes, wait_for_job, monkeypatch
|
||||
):
|
||||
assert not reports_progress(PlainEngine())
|
||||
monkeypatch.setattr("sokhan.worker.pipeline.get_transcriber", lambda: PlainEngine())
|
||||
|
||||
job_id = _upload(client, auth, wav_bytes)
|
||||
|
||||
assert wait_for_job(client, auth, job_id)["status"] == "completed"
|
||||
|
||||
|
||||
def test_fake_engine_reports_fractions_up_to_the_end():
|
||||
seen: list[float] = []
|
||||
import numpy as np
|
||||
|
||||
FakeTranscriber().transcribe(np.zeros(16000 * 4, dtype=np.float32), 16000, "fa", seen.append)
|
||||
|
||||
assert seen == sorted(seen) and seen[-1] == 1.0
|
||||
@@ -51,3 +51,60 @@ def test_empty_and_whitespace_input_stay_empty():
|
||||
def test_statement_with_colon_gets_no_double_mark():
|
||||
assert restore_punctuation("این است") == "این است."
|
||||
assert restore_punctuation("این است:") == "این است:"
|
||||
|
||||
|
||||
# Edge cases from #30. Each test pins the behavior on real-world input; the
|
||||
# comments say why that behavior is the right one for a transcript.
|
||||
|
||||
|
||||
def test_slash_dates_are_left_intact():
|
||||
# `/` is not punctuation to this pass, so date groups never get spaced
|
||||
# or split, in Persian and in Latin digits alike.
|
||||
assert restore_punctuation("تاریخ ۱۴۰۴/۰۹/۰۲ است") == "تاریخ ۱۴۰۴/۰۹/۰۲ است."
|
||||
assert restore_punctuation("جلسه 2026/11/23 برگزار شد") == "جلسه 2026/11/23 برگزار شد."
|
||||
assert restore_punctuation("نسبت ۱/۲ است") == "نسبت ۱/۲ است."
|
||||
|
||||
|
||||
def test_latin_digits_and_words_inside_persian_sentences():
|
||||
assert restore_punctuation("۳ دستگاه RTX 4090 خریدیم") == "۳ دستگاه RTX 4090 خریدیم."
|
||||
assert restore_punctuation("قیمت ۳.۵ میلیون شد") == "قیمت ۳.۵ میلیون شد."
|
||||
assert restore_punctuation("نسخه 1.4.1 منتشر شد") == "نسخه 1.4.1 منتشر شد."
|
||||
assert restore_punctuation("ساعت ۱۲:۳۰ بیا") == "ساعت ۱۲:۳۰ بیا."
|
||||
|
||||
|
||||
def test_thousands_separators_are_not_turned_into_persian_commas():
|
||||
# A Latin comma followed by exactly three digits groups a number; turning
|
||||
# it into ، and spacing it ("1، 000") would split one number into two.
|
||||
assert restore_punctuation("قیمت 1,000 دلار شد") == "قیمت 1,000 دلار شد."
|
||||
assert restore_punctuation("جمعیت 12,500,000 نفر") == "جمعیت 12,500,000 نفر."
|
||||
assert restore_punctuation("مبلغ ۱,۲۰۰ تومان") == "مبلغ ۱,۲۰۰ تومان."
|
||||
|
||||
|
||||
def test_comma_between_numbers_that_is_not_grouping_stays_a_list_separator():
|
||||
assert restore_punctuation("RTX 4090,4080 و 3090") == "RTX 4090، 4080 و 3090."
|
||||
assert restore_punctuation("اعداد 1,2 و 3") == "اعداد 1، 2 و 3."
|
||||
|
||||
|
||||
def test_abbreviation_dots_are_kept_and_end_the_segment():
|
||||
# A trailing dot already counts as terminal punctuation, so nothing is
|
||||
# appended; a dot in the middle is left alone like a decimal point.
|
||||
assert restore_punctuation("Dr.") == "Dr."
|
||||
assert restore_punctuation("با Dr. Smith صحبت کردم") == "با Dr. Smith صحبت کردم."
|
||||
assert restore_punctuation("با دکتر. احمدی") == "با دکتر. احمدی."
|
||||
|
||||
|
||||
def test_ellipsis_forms_are_terminal_and_tightened():
|
||||
assert restore_punctuation("صبر کن…") == "صبر کن…"
|
||||
assert restore_punctuation("نمیدونم...") == "نمیدونم..."
|
||||
assert restore_punctuation("صبر کن ... بعد") == "صبر کن... بعد."
|
||||
# A trailing-off question keeps its ellipsis instead of gaining a ؟.
|
||||
assert restore_punctuation("کی میای...") == "کی میای..."
|
||||
|
||||
|
||||
def test_repeated_and_mixed_marks_are_preserved():
|
||||
# Repetition carries the speaker's emphasis; the pass only converts the
|
||||
# script of Latin marks and never collapses them.
|
||||
assert restore_punctuation("وای!!!") == "وای!!!"
|
||||
assert restore_punctuation("چرا!!!") == "چرا!!!"
|
||||
assert restore_punctuation("چی؟؟") == "چی؟؟"
|
||||
assert restore_punctuation("واقعا?!") == "واقعا؟!"
|
||||
@@ -341,3 +341,53 @@ def test_dead_endpoint_does_not_fail_the_job(
|
||||
detail = wait_for_job(client, auth, response.json()["id"])
|
||||
assert detail["status"] == "completed"
|
||||
assert "سلام بر تو" in detail["text"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"http://127.0.0.1:6379/",
|
||||
"http://localhost:8000/admin",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://10.0.0.5/hook",
|
||||
"http://[::1]/hook",
|
||||
"http://[::ffff:192.168.1.1]/hook",
|
||||
"https://",
|
||||
],
|
||||
)
|
||||
def test_callback_url_to_private_targets_is_rejected(client, auth, wav_bytes, url):
|
||||
response = _upload(client, auth, wav_bytes, callback_url=url)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
def test_private_callback_url_allowed_when_opted_in(
|
||||
client, auth, wav_bytes, monkeypatch, fake_engine, wait_for_job
|
||||
):
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.core import webhooks
|
||||
|
||||
monkeypatch.setenv("WEBHOOK_ALLOW_PRIVATE_TARGETS", "true")
|
||||
get_settings.cache_clear()
|
||||
delivered: list[str] = []
|
||||
monkeypatch.setattr(webhooks, "_default_post", lambda url, *rest: delivered.append(url))
|
||||
|
||||
response = _upload(client, auth, wav_bytes, callback_url="http://10.0.0.5/hook")
|
||||
assert response.status_code == 201
|
||||
wait_for_job(client, auth, response.json()["id"])
|
||||
get_settings.cache_clear()
|
||||
assert delivered == ["http://10.0.0.5/hook"]
|
||||
|
||||
|
||||
def test_delivery_refuses_hosts_that_resolve_privately(monkeypatch):
|
||||
import socket
|
||||
import urllib.error
|
||||
|
||||
from sokhan.core import webhooks
|
||||
|
||||
def fake_getaddrinfo(host, port, *args, **kwargs):
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))]
|
||||
|
||||
monkeypatch.setattr(webhooks.socket, "getaddrinfo", fake_getaddrinfo)
|
||||
with pytest.raises(urllib.error.URLError) as caught:
|
||||
webhooks._default_post("http://hooks.example/sokhan", b"{}", {}, 1.0)
|
||||
assert isinstance(caught.value.reason, webhooks.BlockedTargetError)
|
||||
@@ -59,6 +59,7 @@ 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}")
|
||||
|
||||
@@ -9,6 +9,7 @@ class BotSettings:
|
||||
telegram_bot_token: str
|
||||
api_base_url: str
|
||||
web_base_url: str
|
||||
bot_api_secret: str = ""
|
||||
|
||||
|
||||
def load_settings() -> BotSettings:
|
||||
@@ -16,4 +17,5 @@ def load_settings() -> BotSettings:
|
||||
telegram_bot_token=os.environ.get("TELEGRAM_BOT_TOKEN", ""),
|
||||
api_base_url=os.environ.get("API_BASE_URL", "http://localhost:8000").rstrip("/"),
|
||||
web_base_url=os.environ.get("WEB_BASE_URL", "http://localhost:3000").rstrip("/"),
|
||||
bot_api_secret=os.environ.get("BOT_API_SECRET", ""),
|
||||
)
|
||||
@@ -30,6 +30,13 @@ def main() -> None:
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
if not settings.bot_api_secret:
|
||||
print(
|
||||
"BOT_API_SECRET is not set. Set the same value on the API and the bot; "
|
||||
"the API refuses Telegram logins without it.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
bot = Bot(settings.telegram_bot_token)
|
||||
dispatcher = Dispatcher()
|
||||
|
||||
@@ -90,6 +90,24 @@ def test_get_plans_parses_catalogue():
|
||||
assert plans[1]["max_file_minutes"] == 180
|
||||
|
||||
|
||||
def test_register_telegram_sends_the_bot_secret():
|
||||
seen: dict[str, str | None] = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen["secret"] = request.headers.get("X-Bot-Secret")
|
||||
return httpx.Response(200, json={"id": "u1", "email": "tg", "api_token": "tok"})
|
||||
|
||||
settings = BotSettings(
|
||||
telegram_bot_token="t",
|
||||
api_base_url="http://api.test",
|
||||
web_base_url="http://web.test",
|
||||
bot_api_secret="shared",
|
||||
)
|
||||
with SokhanClient(settings, transport=httpx.MockTransport(handler)) as client:
|
||||
assert client.register_telegram(42, None) == "tok"
|
||||
assert seen["secret"] == "shared"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"call",
|
||||
[
|
||||
|
||||
@@ -5,12 +5,12 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-sokhan}
|
||||
# Required on purpose: shipping a default credential means every
|
||||
# deployment that forgets the .env runs an open database.
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-sokhan}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U sokhan"]
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
@@ -33,10 +33,11 @@ services:
|
||||
build:
|
||||
context: ../backend
|
||||
environment: &backend-env
|
||||
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (see .env.example)}@postgres:5432/${POSTGRES_DB:-sokhan}
|
||||
DATABASE_URL: postgresql+psycopg://${POSTGRES_USER:-sokhan}:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set (cp .env.example deploy/.env and edit it)}@postgres:5432/${POSTGRES_DB:-sokhan}
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
CELERY_ENABLED: "true"
|
||||
DATA_DIR: /data
|
||||
HF_HOME: /data/huggingface
|
||||
SOKHAN_CORS_ORIGINS: ${SOKHAN_CORS_ORIGINS:-}
|
||||
WHISPER_MODEL_SIZE: ${WHISPER_MODEL_SIZE:-medium}
|
||||
WHISPER_DEVICE: ${WHISPER_DEVICE:-cpu}
|
||||
@@ -48,11 +49,15 @@ 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:-}
|
||||
AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-auto}
|
||||
AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax}
|
||||
AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30}
|
||||
|
||||
@@ -16,16 +16,19 @@
|
||||
"archive": "Archive",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "Switch to dark theme",
|
||||
"themeToLight": "Switch to light theme",
|
||||
"signIn": "Sign in",
|
||||
"signOut": "Sign out",
|
||||
"signedInAs": "Signed in as {email}",
|
||||
"signOutOf": "Sign out of {email}"
|
||||
"accountMenu": "Account",
|
||||
"accountMenuFor": "Account menu for {email}",
|
||||
"signedInLabel": "Signed in as",
|
||||
"signedIn": "Signed in"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "From speech to text, in moments",
|
||||
"subheadline": "Upload an audio file or record straight away — Sokhan turns it into an accurate Persian transcript and hands you a short summary alongside.",
|
||||
"startCta": "Get started",
|
||||
"loginCta": "Sign in",
|
||||
"featuresTitle": "Where Sokhan helps",
|
||||
"featuresSubtitle": "From lecture notes to a friend's voice message — every recording deserves its text.",
|
||||
"featureLectureTitle": "Lectures & meetings",
|
||||
@@ -57,6 +60,8 @@
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"passwordLabel": "Password",
|
||||
"passwordPlaceholder": "••••••••",
|
||||
"showPassword": "Show password",
|
||||
"hidePassword": "Hide password",
|
||||
"codeLabel": "Connect code",
|
||||
"codePlaceholder": "Enter your connect code",
|
||||
"codeHint": "Have a connect code? No email or password needed.",
|
||||
@@ -104,6 +109,7 @@
|
||||
"statusFailed": "Failed",
|
||||
"progressLabel": "Processing progress",
|
||||
"percent": "{value}%",
|
||||
"preparing": "Getting ready…",
|
||||
"emptyTitle": "No transcriptions yet",
|
||||
"emptyDesc": "Upload your first file and it will show up here.",
|
||||
"emptyCta": "New transcription",
|
||||
|
||||
@@ -16,16 +16,19 @@
|
||||
"archive": "آرشیو",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "تم تیره",
|
||||
"themeToLight": "تم روشن",
|
||||
"signIn": "ورود",
|
||||
"signOut": "خروج",
|
||||
"signedInAs": "واردشده با {email}",
|
||||
"signOutOf": "خروج از حساب {email}"
|
||||
"accountMenu": "حساب کاربری",
|
||||
"accountMenuFor": "منوی حساب {email}",
|
||||
"signedInLabel": "وارد شده با",
|
||||
"signedIn": "وارد شدهای"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "از گفتار به متن، در چند لحظه",
|
||||
"subheadline": "فایل صوتی را بارگذاری کن یا مستقیم ضبط کن؛ سخن آن را با دقت بالا به متن فارسی تبدیل میکند و خلاصهای کوتاه هم کنارش تحویل میدهد.",
|
||||
"startCta": "شروع کنید",
|
||||
"loginCta": "ورود",
|
||||
"featuresTitle": "سخن کجا به کارت میآید؟",
|
||||
"featuresSubtitle": "از جزوهٔ درس تا پیام صوتی دوستان؛ هر صدایی متن خودش را دارد.",
|
||||
"featureLectureTitle": "درس و جلسه",
|
||||
@@ -57,6 +60,8 @@
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"passwordLabel": "رمز عبور",
|
||||
"passwordPlaceholder": "••••••••",
|
||||
"showPassword": "نمایش رمز عبور",
|
||||
"hidePassword": "پنهان کردن رمز عبور",
|
||||
"codeLabel": "کد اتصال",
|
||||
"codePlaceholder": "کد اتصال را وارد کن",
|
||||
"codeHint": "اگر کد اتصال داری، لازم نیست ایمیل و رمز عبور وارد کنی.",
|
||||
@@ -104,6 +109,7 @@
|
||||
"statusFailed": "ناموفق",
|
||||
"progressLabel": "پیشرفت پردازش",
|
||||
"percent": "{value}٪",
|
||||
"preparing": "در حال آمادهسازی…",
|
||||
"emptyTitle": "هنوز رونویسیای نداری",
|
||||
"emptyDesc": "اولین فایل را بارگذاری کن تا همینجا فهرست شود.",
|
||||
"emptyCta": "رونویسی تازه",
|
||||
|
||||
@@ -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();
|
||||
@@ -272,12 +273,15 @@ export default function JobDetailPage() {
|
||||
<h2 className="font-bold text-stone-900">{t("processingTitle")}</h2>
|
||||
<p className="mt-1.5 text-sm leading-7 text-stone-600">{t("processingDesc")}</p>
|
||||
<div className="mt-4">
|
||||
<ProgressBar value={job.progress} label={t("metaDuration")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500">
|
||||
{new Intl.NumberFormat(locale).format(
|
||||
Math.min(100, Math.max(0, Math.round(job.progress))),
|
||||
)}
|
||||
٪
|
||||
<ProgressBar value={job.progress} label={tj("progressLabel")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500" aria-live="polite">
|
||||
{job.progress > 0
|
||||
? tj("percent", {
|
||||
value: new Intl.NumberFormat(locale).format(
|
||||
Math.min(100, Math.round(job.progress)),
|
||||
),
|
||||
})
|
||||
: tj("preparing")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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");
|
||||
@@ -34,6 +36,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);
|
||||
|
||||
useRequireSignIn();
|
||||
|
||||
@@ -69,7 +73,15 @@ export default function JobsPage() {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [query]);
|
||||
}, [query, refreshTick]);
|
||||
|
||||
const hasRunningJobs =
|
||||
items?.some((job) => job.status === "queued" || job.status === "processing") ?? false;
|
||||
useEffect(() => {
|
||||
if (!hasRunningJobs) return;
|
||||
const timer = setTimeout(() => setRefreshTick((tick) => tick + 1), REFRESH_INTERVAL_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [hasRunningJobs, items]);
|
||||
|
||||
const hasQuery = query.trim().length > 0;
|
||||
|
||||
@@ -166,13 +178,15 @@ export default function JobsPage() {
|
||||
<StatusBadge status={job.status} />
|
||||
</div>
|
||||
</div>
|
||||
{job.status === "processing" ? (
|
||||
{job.status === "queued" || job.status === "processing" ? (
|
||||
<div className="mt-4">
|
||||
<ProgressBar value={job.progress} label={t("progressLabel")} />
|
||||
<p className="mt-1.5 text-xs text-stone-500">
|
||||
{t("percent", {
|
||||
value: nf.format(Math.min(100, Math.max(0, job.progress))),
|
||||
})}
|
||||
{job.progress > 0
|
||||
? t("percent", {
|
||||
value: nf.format(Math.min(100, Math.round(job.progress))),
|
||||
})
|
||||
: t("preparing")}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import localFont from "next/font/local";
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { SiteHeader } from "@/components/site-header";
|
||||
import { themeInitScript } from "@/lib/theme";
|
||||
import "../globals.css";
|
||||
|
||||
// Fonts are self-hosted (see src/fonts/README.txt): builds must never depend
|
||||
@@ -47,7 +48,10 @@ export async function generateMetadata({
|
||||
}
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: "#0f766e",
|
||||
themeColor: [
|
||||
{ media: "(prefers-color-scheme: light)", color: "#0f766e" },
|
||||
{ media: "(prefers-color-scheme: dark)", color: "#134e4a" },
|
||||
],
|
||||
};
|
||||
|
||||
export default async function LocaleLayout({
|
||||
@@ -64,7 +68,10 @@ export default async function LocaleLayout({
|
||||
const t = await getTranslations("common");
|
||||
|
||||
return (
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"}>
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"} suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
|
||||
</head>
|
||||
<body
|
||||
className={`${vazirmatn.variable} ${inter.variable} flex min-h-screen flex-col bg-stone-50 text-stone-900 antialiased`}
|
||||
>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, login, register, startSession, tokenLogin } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
@@ -24,6 +25,7 @@ export default function LoginPage() {
|
||||
const [mode, setMode] = useState<Mode>("login");
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [code, setCode] = useState("");
|
||||
const [emailError, setEmailError] = useState<string | null>(null);
|
||||
const [passwordError, setPasswordError] = useState<string | null>(null);
|
||||
@@ -34,6 +36,7 @@ export default function LoginPage() {
|
||||
function switchMode(next: Mode) {
|
||||
if (next === mode) return;
|
||||
setMode(next);
|
||||
setShowPassword(false);
|
||||
setEmailError(null);
|
||||
setPasswordError(null);
|
||||
setCodeError(null);
|
||||
@@ -182,21 +185,39 @@ export default function LoginPage() {
|
||||
>
|
||||
{t("passwordLabel")}
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type="password"
|
||||
dir="ltr"
|
||||
autoComplete={mode === "register" ? "new-password" : "current-password"}
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordError) setPasswordError(null);
|
||||
}}
|
||||
placeholder={t("passwordPlaceholder")}
|
||||
aria-invalid={passwordError ? true : undefined}
|
||||
className={inputClasses}
|
||||
/>
|
||||
{/* The field is always LTR, so the toggle sits at its physical right. */}
|
||||
<div className="relative" dir="ltr">
|
||||
<input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
dir="ltr"
|
||||
autoComplete={mode === "register" ? "new-password" : "current-password"}
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordError) setPasswordError(null);
|
||||
}}
|
||||
placeholder={t("passwordPlaceholder")}
|
||||
aria-invalid={passwordError ? true : undefined}
|
||||
className={`${inputClasses} pr-11`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword((shown) => !shown)}
|
||||
aria-label={showPassword ? t("hidePassword") : t("showPassword")}
|
||||
aria-pressed={showPassword}
|
||||
aria-controls="login-password"
|
||||
title={showPassword ? t("hidePassword") : t("showPassword")}
|
||||
className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-e-lg text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700"
|
||||
>
|
||||
{showPassword ? (
|
||||
<EyeOff className="h-5 w-5" aria-hidden="true" />
|
||||
) : (
|
||||
<Eye className="h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{passwordError ? (
|
||||
<p className="mt-1.5 text-sm text-red-700">{passwordError}</p>
|
||||
) : mode === "register" ? (
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import { ArrowRight, GraduationCap, TextSearch, Voicemail, type LucideIcon } from "lucide-react";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { LoginCta } from "@/components/login-cta";
|
||||
|
||||
const waveBars = [12, 20, 30, 22, 34, 40, 28, 16, 26, 36, 20, 30, 14, 24, 32, 18, 26, 12, 22, 16];
|
||||
|
||||
@@ -70,9 +69,6 @@ export default async function LandingPage({
|
||||
{t("startCta")}
|
||||
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
</Link>
|
||||
<LoginCta className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2">
|
||||
{t("loginCta")}
|
||||
</LoginCta>
|
||||
</div>
|
||||
<svg
|
||||
viewBox="0 0 200 48"
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--font-vazir: var(--font-vazirmatn, Vazirmatn), var(--font-inter, Inter), ui-sans-serif,
|
||||
system-ui, sans-serif;
|
||||
--animate-progress-indeterminate: progress-indeterminate 1.4s ease-in-out infinite;
|
||||
|
||||
@keyframes progress-indeterminate {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
@@ -21,3 +33,75 @@ html[lang="en"] body {
|
||||
background-color: #99f6e4;
|
||||
color: #134e4a;
|
||||
}
|
||||
|
||||
html.dark {
|
||||
color-scheme: dark;
|
||||
|
||||
--color-stone-50: oklch(14.7% 0.004 49.25);
|
||||
--color-stone-100: oklch(26.8% 0.007 34.298);
|
||||
--color-stone-200: oklch(30% 0.007 34.298);
|
||||
--color-stone-300: oklch(40% 0.01 67.558);
|
||||
--color-stone-400: oklch(55.3% 0.013 58.071);
|
||||
--color-stone-500: oklch(70.9% 0.01 56.259);
|
||||
--color-stone-600: oklch(80% 0.005 56.366);
|
||||
--color-stone-700: oklch(86.9% 0.005 56.366);
|
||||
--color-stone-800: oklch(92.3% 0.003 48.717);
|
||||
--color-stone-900: oklch(97% 0.001 106.424);
|
||||
--color-stone-950: oklch(98.5% 0.001 106.423);
|
||||
|
||||
--color-teal-50: oklch(27.7% 0.046 192.524);
|
||||
--color-teal-100: oklch(32% 0.055 190);
|
||||
--color-teal-200: oklch(38.6% 0.063 188.416);
|
||||
--color-teal-800: oklch(85.5% 0.138 181.071);
|
||||
--color-teal-900: oklch(91% 0.096 180.426);
|
||||
--color-teal-950: oklch(95.3% 0.051 180.801);
|
||||
|
||||
--color-red-50: oklch(25.8% 0.092 26.042);
|
||||
--color-red-100: oklch(30% 0.11 26);
|
||||
--color-red-200: oklch(39.6% 0.141 25.723);
|
||||
--color-red-700: oklch(80.8% 0.114 19.571);
|
||||
--color-red-800: oklch(88.5% 0.062 18.334);
|
||||
--color-red-900: oklch(93.6% 0.032 17.717);
|
||||
|
||||
--color-amber-100: oklch(27.9% 0.077 45.635);
|
||||
--color-amber-800: oklch(92.4% 0.12 95.746);
|
||||
|
||||
--color-emerald-100: oklch(26.2% 0.051 172.552);
|
||||
--color-emerald-800: oklch(90.5% 0.093 164.15);
|
||||
|
||||
--sokhan-surface: oklch(19% 0.005 56);
|
||||
}
|
||||
|
||||
html.dark body {
|
||||
background-color: var(--color-stone-50);
|
||||
color: var(--color-stone-900);
|
||||
}
|
||||
|
||||
html.dark ::selection {
|
||||
background-color: #115e59;
|
||||
color: #f0fdfa;
|
||||
}
|
||||
|
||||
html.dark .bg-white {
|
||||
background-color: var(--sokhan-surface);
|
||||
}
|
||||
html.dark .bg-white\/90 {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 90%, transparent);
|
||||
}
|
||||
html.dark .supports-\[backdrop-filter\]\:bg-white\/75 {
|
||||
@supports (backdrop-filter: var(--tw)) {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 75%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
html.dark .text-teal-600,
|
||||
html.dark .text-teal-700 {
|
||||
color: oklch(77.7% 0.152 181.912);
|
||||
}
|
||||
html.dark .text-teal-700\/60 {
|
||||
color: color-mix(in oklab, oklch(77.7% 0.152 181.912) 60%, transparent);
|
||||
}
|
||||
|
||||
html.dark * {
|
||||
--tw-ring-offset-color: var(--sokhan-surface);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { ChevronDown, LogOut, UserRound } from "lucide-react";
|
||||
|
||||
/**
|
||||
* The signed-in account in the header: an avatar with the email's initial
|
||||
* that opens a small menu showing the full address and Sign out. The full
|
||||
* email no longer has to squeeze into the header row (where it was
|
||||
* truncated or hidden on narrow screens).
|
||||
*/
|
||||
export function AccountMenu({
|
||||
email,
|
||||
signingOut,
|
||||
onSignOut,
|
||||
}: {
|
||||
email: string | null;
|
||||
signingOut: boolean;
|
||||
onSignOut: () => void;
|
||||
}) {
|
||||
const t = useTranslations("nav");
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const signOutRef = useRef<HTMLButtonElement>(null);
|
||||
const menuId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
signOutRef.current?.focus();
|
||||
|
||||
function onPointerDown(event: PointerEvent) {
|
||||
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
}
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
buttonRef.current?.focus();
|
||||
}
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const initial = email ? email.charAt(0).toUpperCase() : null;
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="relative">
|
||||
<button
|
||||
ref={buttonRef}
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? menuId : undefined}
|
||||
aria-label={email ? t("accountMenuFor", { email }) : t("accountMenu")}
|
||||
className="flex items-center gap-1 rounded-full p-0.5 text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<span
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-teal-100 text-sm font-bold text-teal-800"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{initial ?? <UserRound className="h-5 w-5" />}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className={`hidden h-4 w-4 transition-transform sm:block ${open ? "rotate-180" : ""}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
id={menuId}
|
||||
role="menu"
|
||||
aria-label={t("accountMenu")}
|
||||
className="absolute end-0 top-full z-50 mt-2 w-64 overflow-hidden rounded-xl border border-stone-200 bg-white shadow-lg"
|
||||
>
|
||||
<div className="border-b border-stone-100 px-4 py-3">
|
||||
<p className="text-xs text-stone-500">{email ? t("signedInLabel") : t("accountMenu")}</p>
|
||||
{email ? (
|
||||
<p
|
||||
dir="ltr"
|
||||
className="mt-0.5 break-all text-start text-sm font-medium text-stone-900"
|
||||
>
|
||||
{email}
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-0.5 text-sm font-medium text-stone-900">{t("signedIn")}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
ref={signOutRef}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onSignOut();
|
||||
}}
|
||||
disabled={signingOut}
|
||||
className="flex w-full items-center gap-2 px-4 py-2.5 text-sm font-medium text-stone-700 transition-colors hover:bg-stone-50 hover:text-stone-900 focus-visible:bg-stone-50 focus-visible:outline-none disabled:opacity-60"
|
||||
>
|
||||
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
{t("signOut")}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -34,8 +34,14 @@ export function StatusBadge({ status }: { status: JobStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determinate bar once the worker reports progress. While nothing has been
|
||||
* reported yet (queued, model loading, first seconds of decoding) it shows
|
||||
* a moving bar instead of an empty track that looks stuck.
|
||||
*/
|
||||
export function ProgressBar({ value, label }: { value: number; label?: string }) {
|
||||
const clamped = Math.min(100, Math.max(0, value));
|
||||
const indeterminate = clamped <= 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -43,13 +49,18 @@ export function ProgressBar({ value, label }: { value: number; label?: string })
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={Math.round(clamped)}
|
||||
aria-valuenow={indeterminate ? undefined : Math.round(clamped)}
|
||||
aria-busy={indeterminate || undefined}
|
||||
aria-label={label}
|
||||
>
|
||||
<div
|
||||
className="h-full rounded-full bg-teal-700 transition-[width] duration-500 ease-out"
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
{indeterminate ? (
|
||||
<div className="h-full w-2/5 rounded-full bg-teal-700/70 animate-progress-indeterminate motion-reduce:w-full motion-reduce:animate-pulse" />
|
||||
) : (
|
||||
<div
|
||||
className="h-full rounded-full bg-teal-700 transition-[width] duration-500 ease-out"
|
||||
style={{ width: `${clamped}%` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
/** The landing page's sign-in button; hidden once the visitor is signed in. */
|
||||
export function LoginCta({ className, children }: { className: string; children: ReactNode }) {
|
||||
const { ready, signedIn } = useSession();
|
||||
if (!ready || signedIn) return null;
|
||||
return (
|
||||
<Link href="/login" className={className}>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { AudioLines, LogIn, LogOut } from "lucide-react";
|
||||
import { AudioLines, LogIn } from "lucide-react";
|
||||
import { AccountMenu } from "@/components/account-menu";
|
||||
import { Link, usePathname, useRouter } from "@/i18n/navigation";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
import { logout } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
@@ -72,27 +74,9 @@ export function SiteHeader() {
|
||||
>
|
||||
{otherLocale === "en" ? "EN" : "فا"}
|
||||
</button>
|
||||
<ThemeToggle />
|
||||
{ready && signedIn && (
|
||||
<>
|
||||
{email && (
|
||||
<span
|
||||
className="hidden max-w-48 truncate text-sm text-stone-500 md:inline"
|
||||
title={t("signedInAs", { email })}
|
||||
>
|
||||
{email}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
disabled={signingOut}
|
||||
aria-label={email ? t("signOutOf", { email }) : t("signOut")}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium text-stone-600 transition-colors hover:bg-stone-100 hover:text-stone-900 focus-visible:ring-2 focus-visible:ring-teal-700 disabled:opacity-60 sm:px-3"
|
||||
>
|
||||
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signOut")}</span>
|
||||
</button>
|
||||
</>
|
||||
<AccountMenu email={email} signingOut={signingOut} onSignOut={handleSignOut} />
|
||||
)}
|
||||
{ready && !signedIn && pathname !== "/login" && (
|
||||
<Link
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { THEME_STORAGE_KEY, type Theme } from "@/lib/theme";
|
||||
|
||||
function applyTheme(theme: Theme) {
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const t = useTranslations("nav");
|
||||
const [theme, setTheme] = useState<Theme | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(document.documentElement.classList.contains("dark") ? "dark" : "light");
|
||||
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = (event: MediaQueryListEvent) => {
|
||||
let saved: string | null = null;
|
||||
try {
|
||||
saved = window.localStorage.getItem(THEME_STORAGE_KEY);
|
||||
} catch {
|
||||
}
|
||||
if (saved === "light" || saved === "dark") return;
|
||||
const next: Theme = event.matches ? "dark" : "light";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
};
|
||||
media.addEventListener("change", onChange);
|
||||
return () => media.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
const isDark = theme === "dark";
|
||||
|
||||
function toggle() {
|
||||
const next: Theme = isDark ? "light" : "dark";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
try {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, next);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
const label = isDark ? t("themeToLight") : t("themeToDark");
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg border border-stone-300 text-stone-700 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700"
|
||||
>
|
||||
{isDark ? (
|
||||
<Sun className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Moon className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export const THEME_STORAGE_KEY = "sokhan-theme";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
export const themeInitScript = `(function(){try{var t=localStorage.getItem("${THEME_STORAGE_KEY}");if(t!=="light"&&t!=="dark"){t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}document.documentElement.classList.toggle("dark",t==="dark")}catch(e){}})();`;
|
||||
Reference in new issue
Block a user