Author SHA1 Message Date
ahp 8a585fc718 fix(deploy): persist the Whisper cache and clarify the compose env file
- HF_HOME=/data/huggingface on api and worker: the model cache sat in
  the container filesystem, so every recreate (down/up, --build, a new
  image) re-downloaded the model weights — and transcription failed
  outright wherever the Hugging Face Hub is unreachable
- the postgres healthcheck probes $POSTGRES_USER / $POSTGRES_DB instead
  of a hardcoded sokhan
- compose interpolates from the .env next to deploy/docker-compose.yml,
  not the one at the repo root: the quickstart in both READMEs and the
  .env.example header now say cp .env.example deploy/.env, and the
  missing-password error names that path
2026-11-26 16:26:03 +03:30
ahp 1304b13999 fix(deploy): pre-create /data owned by appuser in the backend image
Uploaded audio lives under DATA_DIR (/data, the sokhan-data named
volume). The image never created that directory, so Docker made the
mount point root-owned on first start and every upload failed with
PermissionError once the process runs as appuser.

Docker seeds a new named volume with the mount point's ownership, so
creating /data/audio in the image, owned by appuser, fixes fresh
installs without an entrypoint chown.
2026-11-26 16:25:33 +03:30
9 changed files with 35 additions and 109 deletions

No files matched your search

+1
View File
@@ -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 ---
+13 -9
View File
@@ -5,6 +5,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
## [Unreleased]
### 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.
### Added
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
@@ -74,15 +87,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
pyproject.toml files, web/package.json, the landing site copy, the demo
Space metadata and the fine-tuned model card.
### Fixed
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
read-only volume) now answers **503** with a short message on `POST /jobs`
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
the log. The real `OSError` is logged server-side, a partially written
file is removed, and the API logs an error at startup when `DATA_DIR`
is not writable.
## [1.4.1] - 2026-11-26
### Security
+5 -1
View File
@@ -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` بگذارید. برای اعمال مهاجرت‌های اسکیما به‌صورت دستی:
+5 -1
View File
@@ -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:
+3 -3
View File
@@ -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
+3 -22
View File
@@ -25,14 +25,6 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
class StorageUnavailableError(Exception):
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
It is a server fault, not a bad upload, so the API answers 503 and the
real OSError stays in the server log instead of reaching the client.
"""
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
"""Decode any media file to mono float32 PCM at 16 kHz."""
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
@@ -110,23 +102,12 @@ def audio_dir() -> Path:
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
"""Persist an upload under DATA_DIR/audio with a safe extension.
Raises StorageUnavailableError when the directory or file cannot be
written; a partially written file is removed first.
"""
"""Persist an upload under DATA_DIR/audio with a safe extension."""
suffix = Path(original_filename).suffix.lower()
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
suffix = ".bin"
try:
path = audio_dir() / f"{job_id}{suffix}"
except OSError as exc:
raise StorageUnavailableError(str(exc)) from exc
try:
path.write_bytes(data)
except OSError as exc:
delete_audio(path)
raise StorageUnavailableError(str(exc)) from exc
path = audio_dir() / f"{job_id}{suffix}"
path.write_bytes(data)
return path
+1 -19
View File
@@ -10,13 +10,11 @@ import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sokhan import __version__
from sokhan.config import get_settings
from sokhan.core.audio import StorageUnavailableError, audio_dir
from sokhan.db import configure, create_all
logger = logging.getLogger("sokhan")
@@ -29,14 +27,6 @@ def create_app() -> FastAPI:
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
configure()
create_all()
try:
audio_dir()
except OSError as exc:
logger.error(
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
"it is; in Docker check the volume is owned by the app user",
exc,
)
if not settings.celery_enabled:
logger.warning(
"CELERY_ENABLED=false - jobs run inline in the API process; "
@@ -78,14 +68,6 @@ def create_app() -> FastAPI:
app.include_router(routes_openai.router)
app.include_router(routes_admin.router)
@app.exception_handler(StorageUnavailableError)
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"detail": "upload storage is unavailable, try again later"},
)
@app.get("/")
def root() -> dict:
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
-51
View File
@@ -1,8 +1,5 @@
import io
import shutil
from pathlib import Path
import pytest
from docx import Document
@@ -191,51 +188,3 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
assert client.get("/jobs", headers=headers).json()["total"] == 0
def _make_data_dir_unwritable(tmp_path):
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
shutil.rmtree(tmp_path / "data")
(tmp_path / "data").write_text("not a directory")
def test_upload_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = _upload(client, auth, wav_bytes)
assert response.status_code == 503
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
# No job row is left behind for an upload that was never stored.
assert client.get("/jobs", headers=auth).json()["total"] == 0
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = client.post(
"/v1/audio/transcriptions",
files={"file": ("test.wav", wav_bytes, "audio/wav")},
data={"language": "fa", "response_format": "json"},
headers=auth,
)
assert response.status_code == 503
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
def write_fails_midway(self, data):
self.open("wb").write(data[:1])
raise OSError(28, "No space left on device")
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
with pytest.raises(StorageUnavailableError):
save_upload(b"RIFF....", "job-1", "clip.wav")
assert list(audio_dir().iterdir()) == []
+4 -3
View File
@@ -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}