Author SHA1 Message Date
ahp 57be6ca2ce feat(web): dark mode with an OS-preference default and a header toggle
- ThemeToggle (sun/moon) in the site header; an explicit choice is
  saved in localStorage, otherwise prefers-color-scheme decides and OS
  changes are followed live
- an inline <head> script sets html.dark before first paint, so there
  is no flash of the wrong theme; suppressHydrationWarning on <html>
  covers the class it adds
- globals.css remaps the Tailwind palette under html.dark (stone
  inverted, accent tints darkened, text-only accent shades lifted)
  instead of adding dark: to ~230 utilities across 8 files; solid
  teal/red keep their value for white-on-accent buttons, with targeted
  overrides where they double as a text colour
- per-scheme themeColor; fa/en labels for the toggle
2026-11-26 16:25:44 +03:30
11 changed files with 169 additions and 105 deletions

No files matched your search

+5 -9
View File
@@ -37,6 +37,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
@@ -74,15 +79,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
+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()) == []
+3 -1
View File
@@ -15,7 +15,9 @@
"new": "New transcription",
"archive": "Archive",
"switchToEn": "English",
"switchToFa": "فارسی"
"switchToFa": "فارسی",
"themeToDark": "Switch to dark theme",
"themeToLight": "Switch to light theme"
},
"landing": {
"headline": "From speech to text, in moments",
+3 -1
View File
@@ -15,7 +15,9 @@
"new": "رونویسی تازه",
"archive": "آرشیو",
"switchToEn": "English",
"switchToFa": "فارسی"
"switchToFa": "فارسی",
"themeToDark": "تم تیره",
"themeToLight": "تم روشن"
},
"landing": {
"headline": "از گفتار به متن، در چند لحظه",
+9 -2
View File
@@ -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`}
>
+74
View File
@@ -1,5 +1,7 @@
@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;
@@ -21,3 +23,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);
}
+2
View File
@@ -3,6 +3,7 @@
import { useLocale, useTranslations } from "next-intl";
import { AudioLines } from "lucide-react";
import { Link, usePathname, useRouter } from "@/i18n/navigation";
import { ThemeToggle } from "@/components/theme-toggle";
export function SiteHeader() {
const t = useTranslations("nav");
@@ -60,6 +61,7 @@ export function SiteHeader() {
>
{otherLocale === "en" ? "EN" : "فا"}
</button>
<ThemeToggle />
</nav>
</div>
</header>
+64
View File
@@ -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>
);
}
+5
View File
@@ -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){}})();`;